Receiving error while compiling with paper rock scissors - c#

I'm trying to compile this code but I get an "not all code paths return a value" in judgeRockPaperScissors(). I need the three methods to work in the main method. I not sure what is wrong. I was having issues with converting int to strings as well. Any help would be great! Thank you!
using System;
using System.Windows.Forms;
class RockPaperScissors
{
static string response;
static string respond;
static string player1Sel;
static int player2Sel;
static int result;
static Random numberGenerator = new Random(); //Generates a random number.
public static void Main(string[] args)
{
Console.Write("Do you want to play Rock, Paper, Scissors?");// User writes yes or anything else.
respond = Console.ReadLine();
respond = respond.ToUpper(); //Makes the responce uppercase.
while (respond == "YES")
{ //Beginning of "while loop".
player1Sel = promptForInput();
player2Sel = generateAutoSelect();
result = judgeRockPaperScissors();
switch (result)
{
case 00:
Console.WriteLine("Draw!");
break;
case 12:
Console.WriteLine("Paper covers rock. Player 2 Wins!");
break;
case 23:
Console.WriteLine("Scissors cut paper. Player 2 Wins!");
break;
case 31:
Console.WriteLine("Rock smashes scissors. Player 2 Wins!");
break;
case 13:
Console.WriteLine("Rock smashes scissors. Player 1 Wins!");
break;
case 21:
Console.WriteLine("Paper covers rock. Player 1 Wins!");
break;
case 32:
Console.WriteLine("Scissors cut paper. Player 1 Wins!");
break;
}// End of switch.
Console.Write("Do you want to play again?");// Where the player decides to play again.
respond = Console.ReadLine();
respond = respond.ToUpper();
} //End of "while loop".
} //End of Main.
private static int judgeRockPaperScissors()
{
throw new NotImplementedException();
}
public static string promptForInput()
{
Console.Write("Player one, make a selection. Type 1=rock, 2=paper, or 3=scissors and press enter: ");
player1Sel = Console.ReadLine();
if (player1Sel == "")
{
MessageBox.Show("You must select a valid choice.");
Environment.Exit(0);
}
else
if (int.Parse(player1Sel) < 1 | int.Parse(response) > 3)
{
MessageBox.Show(response + " - is not a valid choice.");
Environment.Exit(0);
}
return player1Sel;
}// End of promptForInput.
public static int generateAutoSelect()
{
int player2Sel = numberGenerator.Next(1, 4);//Generates random number between 1 and 3.
if (player2Sel == 1)
{
MessageBox.Show("Player2 chose rock.");
}
else
if (player2Sel == 2)
{
MessageBox.Show("Player2 chose paper.");
}
else
if (player2Sel == 3)
{
MessageBox.Show("Player2 chose scissors.");
}
return player2Sel;
} // End of generateAutoSelect.
public static string judgeRockPaperScissors(int player1Sel, int player2Sel)
{
if (player1Sel == player2Sel)
{ return "00"; }
else if (player1Sel == 1 && player2Sel == 2)
{ return "12"; }
else if (player1Sel == 2 && player2Sel == 3)
{ return "23"; }
else if (player1Sel == 3 && player2Sel == 1)
{ return "31"; }
else if (player1Sel == 1 && player2Sel == 3)
{ return "13"; }
else if (player1Sel == 2 && player2Sel == 1)
{ return "21"; }
else if (player1Sel == 3 && player2Sel == 2)
{ return "32"; }
}// End of judgeRockPaperScissors.
} // End of class.

The compiler does not know that you have handled all possible cases in your if/else if blocks because the range of int is far more than 0-2. The easiest way to get your code compiling is to add a generic else block:
...
else
{
throw new ArgumentException("Player selections out of range");
}
Since the input is invalid throw an exception.
On a side note, using strings the way you are is definitely not the right approach.

Update the function to return null if no conditions are met:
public static string judgeRockPaperScissors(int player1Sel, int player2Sel)
{
if (player1Sel == player2Sel)
{ return "00"; }
else if (player1Sel == 1 && player2Sel == 2)
{ return "12"; }
else if (player1Sel == 2 && player2Sel == 3)
{ return "23"; }
else if (player1Sel == 3 && player2Sel == 1)
{ return "31"; }
else if (player1Sel == 1 && player2Sel == 3)
{ return "13"; }
else if (player1Sel == 2 && player2Sel == 1)
{ return "21"; }
else if (player1Sel == 3 && player2Sel == 2)
{ return "32"; }
return null;
}
That way it will always return with something. You'll also want to add a null check on the result variable in your main function to make sure it didn't return null.

Related

All paths don't return a value

I'm not sure what exactly is wrong with my code because it was working before but now it's showing me this error.
main.cs(179,20): error CS0161: `CarProgram.ChangeGears(int, string)':
not all code paths return a value
The program is for car functions, like a simulator in a way, but I want to get this first error out of the way before moving on to the rest.
Here's the code
private static int ChangeGears(int s, string g)
{
Console.WriteLine("Inside the function Change Gears");
if (s == 0)
{
string haveGear;
Console.WriteLine("What gear would you like to have?");
haveGear = Console.ReadLine();
haveGear = haveGear.ToUpper();
if (haveGear == "P" || haveGear == "R" || haveGear == "N" || haveGear == "D")
{
switch (haveGear)
{
case "P":
{
Console.WriteLine("You are in park");
break;
}
case "N":
{
Console.WriteLine("You are in neutral");
break;
}
case "D":
{
Console.WriteLine("You are in drive");
break;
}
case "R":
{
Console.WriteLine("You are in reverse");
break;
}
}//close
g = haveGear;
}
else
{
Console.WriteLine("The speed must be 0 to change gears.");
}
Console.WriteLine("Gear is "+ g);
return 0;
}
}// close ChangeGears
Please, format out your routine,
private static int ChangeGears(int s, string g) {
Console.WriteLine("Inside the function Change Gears");
if (s == 0) {
...
/* Some logic here */
...
return 0; // <- when s == 0 ChangeGears returns 0
}
//TODO: return value when s != 0
}// close ChangeGears
And you clearly see that ChangeGears doesn't return anything when s != 0
It's in the ChangeGears Method:
You are saying:
if(condition)
{
// Do Stuff
return 0;
}
// Here is implicitly:
if (not Condition)
{
//Do nothing
}
The else also needs a return.
Additionally, the error message gives you the information you need.
main.cs(179,20): error CS0161
Is saying line 179 is the method with the issue.

Dividing by Zero Exeption, knowing why it gets thrown, not knowing how to fix it

For better understanding I will first post my Program Class.
Program.cs
namespace BeginnersGuidToLifting
{
class Program
{
public static readonly int width = 85;
public static readonly int height = 35;
public static readonly User user = new User();
public static readonly Goal goal = new Goal();
public static Calories calories = new Calories();
public static Nutrition nutrition = new Nutrition();
public static Menu menu = new Menu();
static void InitUser()
{
Console.WriteLine("\n### About You ###\n");
user.Name = Question.AskString("Name: ");
user.Age = Question.AskInt("Age: ");
user.Gender = Question.AskString("Gender(m/f): ");
user.Height = Question.AskInt("Height(cm): ");
user.Weight = Question.AskInt("Weight(kg): ");
}
static void InitGoals()
{
Console.WriteLine("\n### What are your Goals ### \n");
goal.GainWeight();
goal.LoseWeight();
goal.GetStronger();
goal.GetLeaner();
goal.StayFit();
goal.Hypertrophy();
Console.Write("Answer: ");
var input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.D1:
goal.GoalStatusGainWeight = true;
goal.GoalMessage = "Your Goal is to Gain Weight";
break;
case ConsoleKey.D2:
goal.GoalStatusLoseWeight = true;
goal.GoalMessage = "Your Goal is to Lose weight";
break;
case ConsoleKey.D3:
goal.GoalStatusGetStronger = true;
goal.GoalMessage = "Your Goal is to get Stronger";
break;
case ConsoleKey.D4:
goal.GoalStatusGetLeaner = true;
goal.GoalMessage = "Your Goal is to get Leaner";
break;
case ConsoleKey.D5:
goal.GoalStatusStayFit = true;
goal.GoalMessage = "Your Goal is to Stay Fit";
break;
case ConsoleKey.D6:
goal.GoalStatusHypertrophy = true;
goal.GoalMessage = "Your Goal is Hypertrophy";
break;
default:
Console.WriteLine("Error");
break;
}
}
static void InitMenu()
{
menu.ShowMenu();
menu.Discalmer = false;
//menu.Disclamer();
}
static void BmiResult()
{
var bodyType = user.GetBodyType();
if (bodyType == User.BodyType.ReallyUnderweight)
{
Console.WriteLine("Really Underweigt");
}
else if (bodyType == User.BodyType.Underweight)
{
Console.WriteLine("Underweight");
}
else if (bodyType == User.BodyType.CloseToUnderwight)
{
Console.WriteLine("Close to Underweight");
}
else if (bodyType == User.BodyType.Healthy)
{
Console.WriteLine("at a Healthy Weight");
}
else if (bodyType == User.BodyType.Overweight)
{
Console.WriteLine("Overweight");
}
else if (bodyType == User.BodyType.Obese)
{
Console.WriteLine("Obese");
}
else if (bodyType == User.BodyType.SeverlyObese)
{
Console.WriteLine("Serverley Obese");
}
else if (bodyType == User.BodyType.MorbidlyObese)
{
Console.WriteLine("Morbidly Obese");
}
}
static void Main(string[] args)
{
Console.Title = "Beginers Guide To Lifting";
Console.SetWindowSize(width, height);
Console.SetBufferSize(width, height);
InitMenu();
var userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.D1:
InitUser();
InitGoals();
break;
case ConsoleKey.D2:
Console.WriteLine("Press 2");
break;
default:
Console.WriteLine("Why y no work");
break;
}
//Status So Far
Console.WriteLine("\n### Your Stats ### \n");
Console.WriteLine("Name: {0} \nAge: {1} \nHeight: {2} \nWeight: {3}", user.Name, user.Age, user.Height, user.Weight);
Console.WriteLine("Goal: {0}", goal.GoalMessage);
BmiResult();
Console.Write("\nContinue(y/n) to The Programm?: ");
if (Console.ReadLine() == "y")
{
Console.Clear();
}
//Gain Weight Goal
//Introduce 5x5
var exercise = new FiveByFive();
exercise.printIntroduction();
//Show Exercises
exercise.printWorkoutWeek1();
exercise.printWorkoutWeek2();
//Show Nutrition
if (goal.GoalStatusGainWeight == true)
{
switch (user.Gender)
{
case "male":
case "m":
case "Male":
calories.GainCaloriesMale(user);
break;
case "female":
case "f":
case "Female":
calories.GainCaloriesFemale(user);
break;
}
}
//Lose Weight
if (goal.GoalStatusLoseWeight == true)
{
switch (user.Gender)
{
case "male":
case "m":
case "Male":
calories.LoseCaloriesMale(user);
break;
case "female":
case "f":
case "Female":
calories.LoseCaloriesFemale(user);
break;
}
}
}
}
}
The Problem is in my Main Method.
InitMenu();
var userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.D1:
InitUser();
InitGoals();
break;
case ConsoleKey.D2:
Console.WriteLine("Press 2");
break;
default:
Console.WriteLine("Why y no work");
break;
}
When I press one, it should happen what it shows.
Init User and Init User Goals.
How ever when i press 2 it brings me to the User.cs class,
where i am doing the Math for the Users BMI.
I dont really understand why it would do that when pressing 2, because all i want to display is "Press 2" Or later to be added A disclamer.
The Exeption
System.DivideByZeroException: 'Attempted to divide by zero.'
Is thrown because it tries to divde 0 with 0 and that is because there is no input from the user yet. Because all i would like to do by pressing 2 is display another window with some text. And that is is.
I really dont understand why it jumps to the User class.
Here is User.cs for better understanding.
namespace BeginnersGuidToLifting
{
class User
{
public enum BodyType
{
ReallyUnderweight,
Underweight,
CloseToUnderwight,
Healthy,
Overweight,
Obese,
SeverlyObese,
MorbidlyObese
}
public string Name;
//private string _gender;
public string Gender;
private int _weight;
private int _height;
private int _age;
public int Age
{
get => _age;
set
{
if (value >= 0)
{
_age = value;
}
}
}
public int Weight
{
get => _weight;
set
{
if (value >= 0)
{
_weight = value;
}
}
}
public int Height
{
get => _height;
set
{
if (value >= 0)
{
_height = value;
}
}
}
//TODO
//public string Gender
//{
// get => _gender;
// set
// {
// if (value == "female" || value == "f" || value == "male" || value == "m" )
// _gender = value;
// else
// {
// Console.WriteLine("Value Wrong");
// }
// }
//}
public int GetBmi()
{
Console.WriteLine("Weight:"+Weight);
//var bmi = Math.Round((Weight / Math.Pow(Height, 2)) * 10000);
int bmi = Weight / (Height * Height) * 10000;
Console.WriteLine("Your Body Mass Index: " + bmi);
Console.Write("That Means That you are: ");
return bmi;
}
public BodyType GetBodyType()
{
int bmi = GetBmi();
if (bmi < 16)
return BodyType.ReallyUnderweight;
else if (bmi >= 16 && bmi <= 17)
return BodyType.Underweight;
else if (bmi >= 17 && bmi <= 18.5)
return BodyType.CloseToUnderwight;
else if (bmi >= 18.5 && bmi <= 25)
return BodyType.Healthy;
else if (bmi >= 25 && bmi <= 30)
return BodyType.Overweight;
else if (bmi >= 30 && bmi <= 35)
return BodyType.Obese;
else if (bmi >= 35 && bmi <= 40)
return BodyType.SeverlyObese;
return BodyType.MorbidlyObese;
}
}
}
Summary
A switch command calls 2 actions when number 1 and number 2 is
pressed on the keyboard.
When pressing 1 everything works fine and
does what it should.
When pressing 2 it tries to do the math for
something there is no input yet, Because input is only asked when
pressing 1.
Thank you in advance for taking the time to read this.
Any input is welcome. I hope everything is clear to understand.
After you press '2' and it exits the switch, it calls BmiResult(), which calls methods in the user class.
BmiResult() calls user.GetBodyType(), which calls GetBmi() on the user class. This is where your calculation happens, but since you didn't set any of the values on the user, every thing defaults to zero. Which means you are doing this:
int bmi = 0 / (0 * 0) * 10000;
Order of operations means it does this:
int bmi = (0 / 0) * 10000;
because division and multiplication are executed within parantheses first, then left to right.
However, multiplying zero by anything would still be zero, so you need to check if the divisor would be zero before doing the calculation, or wrap the code in a try/catch and handle it.

Name doesn't exist in the current context error happening in the same class

I'm making a simple rock paper scissors game that uses keyboard input. I've realised that it's a better thing to type 1 for rock 2 for scissors etc than to write rock paper or scissors, but I want the console to write at the end what each player chose(rock, paper or scissors) instead of 1,2,3.
So when the string that has the number gets correct user input, another string
becomes rock paper or scissors.However, although I'm only using one class and initialising RealChoice1 and RealChoice2 at the beginning of the while, I get the "name doesn't exist in the current context" error for both of them
while (true)
{
string RealChoice2;
string RealChoice1;
while (true)
{
var key1 = System.Console.ReadKey(true);
if (key1.Key == ConsoleKey.Enter)
break;
Choice1 += key1.KeyChar;
}
if (Choice1 == "exit")
return (int)ExitCode.UserInputExit;
else if (Choice1 != "1" && Choice1 != "2" && Choice1 != "3")
{
Choice1 = null;
Console.WriteLine("");
Console.WriteLine("Please write 1, 2 or 3");
}
else if (Choice1 == "1" || Choice1 == "2" || Choice1 == "3")
{
switch (Convert.ToInt32(Choice1))
{
case 1:
RealChoice1 = "Rock";
break;
case 2:
RealChoice1 = "Scissors";
break;
case 3:
RealChoice1 = "Paper";
break;
}
break;
}
} //End of player 1 input
string Choice2 = null;
Console.WriteLine("");
Console.WriteLine("Player2, please type what you choose");
//Player2Input:
while (true)
{
while (true)
{
var key2 = System.Console.ReadKey(true);
if (key2.Key == ConsoleKey.Enter)
break;
Choice2 += key2.KeyChar;
}
if (Choice2 == "exit")
return (int)ExitCode.UserInputExit;
else if (Choice2 != "1" && Choice2 != "2" && Choice2 != "3")
{
Choice2 = null;
Console.WriteLine("");
Console.WriteLine("Please write 1, 2 or 3");
}
else if (Choice2 == "1" || Choice2 == "2" || Choice2 == "3")
{
switch (Convert.ToInt32(Choice2))
{
case 1:
RealChoice2 = "Rock";
break;
case 2:
RealChoice2 = "Scissors";
break;
case 3:
RealChoice2 = "Paper";
break;
}
break;
}
}
You need to declare your variables outside of the while loop if you want them to be available everywhere in the scope of your code. Currently, since you're declaring them within the first while loop, they wouldn't be available where you're using them inside the second while loop.

Class / Method not returning the correct value

Probably a pretty newb question but here we go.
I am quite new to this and right now i have reached my first logic problem i guess.
I've created a class + method which is supposed to return me a Int32 value and it returns something that is, atleast in my eyes, unreachable. I also dont want this value to be returned.
Here's the code:
public static Int32 SetInterval(ConsoleKeyInfo cki)
{
if (cki.Key == ConsoleKey.D1 || cki.Key == ConsoleKey.D2 || cki.Key == ConsoleKey.D3 || cki.Key == ConsoleKey.D4 || cki.Key == ConsoleKey.D5 || cki.Key == ConsoleKey.D6)
{
if (cki.Key == ConsoleKey.D1)
{
return 10000;
}
else if (cki.Key == ConsoleKey.D2)
{
return 20000;
}
else if (cki.Key == ConsoleKey.D3)
{
return 30000;
}
else if (cki.Key == ConsoleKey.D4)
{
return 45000;
}
else if (cki.Key == ConsoleKey.D5)
{
return 60000;
}
else if (cki.Key == ConsoleKey.D6)
{
return 120000;
}
}
else
{
SetInterval(Console.ReadKey());
}
return 50;
}
And here is how i execute it within my main class:
static int interval;
interval = DefineInterval.SetInterval(Console.ReadKey());
Console.WriteLine("");
Console.WriteLine(interval.ToString());
So whats happening now is:
If i press one of the 6 numbers correctly without pressing any other key before, its just fine. The output is normal and as it's supposed to be.
Then again, when i press, for example "a6" on my Keyboard all i get is:
"
a6
50
"
Any ideas? Also probably not the best way to do such a thing.
The recursive call to SetInterval in the else block doesn't do anything with the return value. What you want is this:
public static Int32 SetInterval(ConsoleKeyInfo cki)
{
if (cki.Key == ConsoleKey.D1)
{
return 10000;
}
else if (cki.Key == ConsoleKey.D2)
{
return 20000;
}
else if (cki.Key == ConsoleKey.D3)
{
return 30000;
}
else if (cki.Key == ConsoleKey.D4)
{
return 45000;
}
else if (cki.Key == ConsoleKey.D5)
{
return 60000;
}
else if (cki.Key == ConsoleKey.D6)
{
return 120000;
}
else
{
return SetInterval(Console.ReadKey());
}
}
Note that I also moved the unnecessary if statement surrounding the first else if chain.
public static Int32 SetInterval(ConsoleKeyInfo cki)
{
if (cki.Key == ConsoleKey.D1 || cki.Key == ConsoleKey.D2 || cki.Key == ConsoleKey.D3 || cki.Key == ConsoleKey.D4 || cki.Key == ConsoleKey.D5 || cki.Key == ConsoleKey.D6)
{
if (cki.Key == ConsoleKey.D1)
{
return 10000;
}
else if (cki.Key == ConsoleKey.D2)
{
return 20000;
}
else if (cki.Key == ConsoleKey.D3)
{
return 30000;
}
else if (cki.Key == ConsoleKey.D4)
{
return 45000;
}
else if (cki.Key == ConsoleKey.D5)
{
return 60000;
}
else if (cki.Key == ConsoleKey.D6)
{
return 120000;
}
}
else
{
return SetInterval(Console.ReadKey());
}
}
You are recursively calling your method. When you give correct input, it goes fine.
Else it goes to get correct input, and after that correct input it returns the default value from the first call of the method.
Solution:
Just remove the return 50 and set:
else
{
return SetInterval(Console.ReadKey());
}
Quick question- why would you press "a6" ? is it by mistake and you want this to be read as just 6 by your program and move on or is there a different reason behind it? If that is the reason then you need to remove the return 50 and place return SetInterval(Console.ReadKey()) in else.

Algorithm for scissor paper stone

I am using the following method which works but wondering if there is a better algorithm to perform the test. Is there a better way to do it? Doing this in C# but putting syntax aside, believe the algorithm is going to be the same across OOP languages. Thank you.
public String play(int userInput)
{ //ComputerIn is a randomly generated number between 1-3
ComputerIn = computerInput();
if (ComputerIn == userInput)
return "Draw";
else if (ComputerIn == 1 && userInput == 2)
return "Win";
else if (ComputerIn == 2 && userInput == 3)
return "Win";
else if (ComputerIn == 3 && userInput == 1)
return "Win";
else if (ComputerIn == 1 && userInput == 3)
return "Lose";
else if (ComputerIn == 2 && userInput == 1)
return "Lose";
else
return "Lose";
}
if ((ComputerIn) % 3 + 1 == userInput)
return "Win";
else if ((userInput) % 3 + 1 == ComputerIn)
return "Lose"
else
return "Draw"
If you wrap 3 around to 1 (using %) then the winner is always 1 greater than the loser.
This approach is more natural when you use 0-2, in which case we would use (ComputerIn+1)%3. I came up with my answer by subbing ComputerIn with ComputerIn-1 and UserInput with UserInput-1 and simplifying the expression.
Edit, looking at this question after a long time. As written, if the ComputerIn is not used anywhere else, and is only used to determine win/lose/draw, then this method is actually equivalent to:
if (ComputerIn == 1)
return "Win";
else if (ComputerIn == 2)
return "Lose"
else
return "Draw"
This can even be further simplified to
return new String[]{"Win", "Lose", "Draw"}[ComputerIn-1];
The results from this are entirely indistinguishable. Unless the randomly generated number is exposed to outside of this method. No matter what your input is, there's always 1/3 chance of all possibilities. That is, what you're asking for, is just a complicated way of returning "Win", "Lose", or "Draw" with equal probability.
Here's one of many possible solutions. This will print Win.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Input userInput = Input.Rock;
Result result = Play(userInput);
Console.WriteLine(Enum.GetName(result.GetType(), result));
Console.ReadKey();
}
static Result Play(Input userInput)
{
Input computer = Input.Scissors;
switch (userInput)
{
case Input.Paper:
switch (computer)
{
case Input.Paper: return Result.Draw;
case Input.Rock: return Result.Win;
case Input.Scissors: return Result.Lose;
default: throw new Exception("Logic fail.");
}
case Input.Rock:
switch (computer)
{
case Input.Paper: return Result.Lose;
case Input.Rock: return Result.Draw;
case Input.Scissors: return Result.Win;
default: throw new Exception("Logic fail.");
}
case Input.Scissors:
switch (computer)
{
case Input.Paper: return Result.Win;
case Input.Rock: return Result.Lose;
case Input.Scissors: return Result.Draw;
default: throw new Exception("Logic fail.");
}
default: throw new Exception("Logic fail.");
}
}
}
enum Input
{
Rock,
Paper,
Scissors
}
enum Result
{
Lose,
Draw,
Win
}
}
This is how I would do it:
public class Program
{
public enum RPSPlay { Rock, Scissors, Paper }
public enum RPSPlayResult { Win, Draw, Loose }
public static readonly int SIZE = Enum.GetValues(typeof(RPSPlay)).Length;
static RPSPlayResult Beats(RPSPlay play, RPSPlay otherPlay)
{
if (play == otherPlay) return RPSPlayResult.Draw;
return ((int)play + 1) % SIZE == (int)otherPlay
? RPSPlayResult.Win
: RPSPlayResult.Loose;
}
static void Main(string[] args)
{
Random rand = new Random();
while (true)
{
Console.Write("Your play ({0}) (q to exit) : ", string.Join(",", Enum.GetNames(typeof(RPSPlay))));
var line = Console.ReadLine();
if (line.Equals("q", StringComparison.OrdinalIgnoreCase))
return;
RPSPlay play;
if (!Enum.TryParse(line, true, out play))
{
Console.WriteLine("Invalid Input");
continue;
}
RPSPlay computerPlay = (RPSPlay)rand.Next(SIZE);
Console.WriteLine("Computer Played {0}", computerPlay);
Console.WriteLine(Beats(play, computerPlay));
Console.WriteLine();
}
}
}
I would prefer to use a static 3x3 matrix to store the possible outcomes. But it is a question of taste, and I am a mathematician.
Here is one-liner that we created at lunchtime.
using System;
public class Rps {
public enum PlayerChoice { Rock, Paper, Scissors };
public enum Result { Draw, FirstWin, FirstLose};
public static Result Match(PlayerChoice player1, PlayerChoice player2) {
return (Result)((player1 - player2 + 3) % 3);
}
public static void Main() {
Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Rock), Result.Draw);
Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Paper), Result.Draw);
Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Scissors), Result.Draw);
Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Scissors), Result.FirstWin);
Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Paper), Result.FirstLose);
Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Rock), Result.FirstWin);
Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Scissors), Result.FirstLose);
Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Paper), Result.FirstWin);
Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Rock), Result.FirstLose);
}
public static void Test(Result sample, Result origin) {
Console.WriteLine(sample == origin);
}
}
\From A java beginner Perspective. User plays with the computer to infinity.
import java.util.Scanner;
public class AlgorithmDevelopmentRockPaperScissors{
public static void main(String[] args){
System.out.println("\n\nHello Eric today we are going to play a game.");
System.out.println("Its called Rock Paper Scissors.");
System.out.println("All you have to do is input the following");
System.out.println("\n 1 For Rock");
System.out.println("\n 2 For Paper");
System.out.println("\n 3 For Scissors");
int loop;
loop = 0;
while (loop == 0){
System.out.println("\n\nWhat do you choose ?");
int userInput;
Scanner input = new Scanner(System.in);
userInput = input.nextInt();
while (userInput > 3 || userInput <= 0 ){ //ensure that the number input by the sure is within range 1-3. if else the loop trap.
System.out.println("Your choice "+userInput+" is not among the choices that are given. Please enter again.");
userInput = input.nextInt();
}
switch (userInput){
case 1:
System.out.println("You Chose Rock.");
break;
case 2:
System.out.println("You Chose Paper.");
break;
case 3:
System.out.println("You Chose Scissors");
break;
default:
System.out.println("Please Choose either of the choices given");
break;
}
int compInput;
compInput = (int)(3*Math.random()+1);
switch (compInput){
case 1:
System.out.println("\nComputer Chooses Rock.");
break;
case 2:
System.out.println("\nComputer Chooses Paper.");
break;
case 3:
System.out.println("\nComputer Chooses Scissors");
break;
}
if (userInput == compInput){
System.out.println(".........................................");
System.out.println("\nYou Both chose the same thing, the game ends DRAW.");
System.out.println(".........................................");
}
if (userInput == 1 && compInput == 2){
System.out.println(".........................................");
System.out.println("\nComputer wins because Paper wraps rock.");
System.out.println(".........................................");
}
if (userInput == 1 && compInput == 3){
System.out.println(".........................................");
System.out.println("\nYou win because Rock breaks Scissors.");
System.out.println(".........................................");
}
if (userInput == 2 && compInput == 1){
System.out.println(".........................................");
System.out.println("\nYou win Because Paper wraps Rock");
System.out.println(".........................................");
}
if (userInput == 2 && compInput == 3){
System.out.println(".........................................");
System.out.println("\nComputer wins because Scissors cut the paper");
System.out.println(".........................................");
}
if (userInput == 3 && compInput == 1){
System.out.println(".........................................");
System.out.println("\nComputer Wins because Rock Breaks Scissors.");
System.out.println(".........................................");
}
if (userInput == 3 && compInput == 2){
System.out.println(".........................................");
System.out.println("\nYou win because scissors cut the paper");
System.out.println(".........................................");
}
}
}
}
A simple JavaScript implementation using sine wave function to calculate result:
<script>
var tab = ["Lose","Draw","Win"];
var dict = ["Paper","Stone","Scissors"];
var i,text = '';
for (i = 0; i < dict.length; i++) {
text += i + '-' + dict[i] + ' ';
}
var val1 = parseInt(prompt(text));
var val2 = Math.floor(Math.random() * 3);
alert('Computer chose: ' + dict[val2]);
result = Math.sin((val1*180+1) - (val2*180+1));
alert(tab[Math.round(result)+1]);
</script>
No if's required, just for fun...
Check it
Observation: The user wins if userInput is only one ahead of computerInput (case of (1,2), (2,3)) or lag two (case of (3,1)).
Conversely, if userInput lags one behind computerInput or two ahead, the user loses.
In the modulo 3, the lag one is the same as the advance two.
(-1 mod 3 == 2 mod 3 == 2)
int decision = (userInput - computerInput + 3) % 3;
String[] answer = {"Draw", "Win", "Lose"};
return answer[decision];

Categories