After having said hello to the world, we can move on to creating a simple game. We won't be needing any art assets for this one since we'll be making the entire game through code alone. We used C# during the last lesson, and we'll do so again here. This is a simple guide on how you can create a game of "Rock, Paper, Scissors" with randomized elements and variables where you play against the computer.
Let's start by creating a new project. Nothing special needs to be done, just create a new project as you did during the previous lesson. We'll be naming this project RPS, but you can choose whatever name you wish.
Instead of going through the code one line at a time, we're going to show you the full working code right away. Inspect it carefully. Afterwards, we're going to separate it into smaller chunks and go through what is happening in each segment.
using System;
namespace RPS
{
class Program
{
static void Main(string[] args)
{
string ans = "";
int count = 0;
int count1 = 0;
Console.WriteLine("Welcome to RPS, time to play");
while (ans != "NO")
{
Console.WriteLine("Make your choice:\n1->ROCK\n2->PAPER\n3->SCISSORS");
string[] choices = new string[3] { "ROCK", "PAPER", "SCISSORS" };
Random rnd = new Random();
int n = rnd.Next(0, 3);
Console.WriteLine("Enter your choice:");
string user = Console.ReadLine().ToUpper();
Console.WriteLine("Computer:" + choices[n]);
if (user == "ROCK" && choices[n] == "SCISSORS")
{
Console.WriteLine("You win");
count += 1;
}
else if (user == "ROCK" && choices[n] == "PAPER")
{
Console.WriteLine("Computer wins");
count1 += 1;
}
else if (user == "PAPER" && choices[n] == "ROCK")
{
Console.WriteLine("You win");
count += 1;
}
else if (user == "PAPER" && choices[n] == "SCISSORS")
{
Console.WriteLine("Computer wins");
count1 += 1;
}
else if (user == "SCISSORS" && choices[n] == "ROCK")
{
Console.WriteLine("Computer wins");
count1 += 1;
}
else if (user == "SCISSORS" && choices[n] == "PAPER")
{
Console.WriteLine("You win");
count += 1;
}
else
{
Console.WriteLine("Same choices");
}
Console.WriteLine("Play again(YES/NO):");
ans = Console.ReadLine().ToUpper();
Console.WriteLine("---------------------------------------");
}
Console.WriteLine("User wins " + count + " times");
Console.WriteLine("Computer wins " + count1 + " times");
}
}
}
Answer the following question about the material you just learned.