I've struggled through a uni assignment to create a dice game. I've finished it but of course forgot to add the option to replay the game if necessary and am so lost in code that I don't even know where to being to get the game to play again. I would really appreciate some help to be able to get users to play another game if they want to or escape the console app.
using System;
public class Player {
private int score;
private string name;
private bool isAI = false;
public void reset() {
this.score = 0;
}
public void addScore(int scoreToAdd) {
this.score = this.score + scoreToAdd;
}
public int getScore() {
return this.score;
}
public string getName() {
return this.name;
}
public void setName(string name) {
this.name = name;
}
/// Prompt the player to 'roll the dice'
public void prompt() {
if (isAI) { return; }
Console.WriteLine(getName() + ", please roll the dice (press enter):");
Console.ReadLine();
}
public void promptForName() {
Console.WriteLine("Please enter your name (Enter 'cpu' to play against the computer)");
string name = Console.ReadLine();
setName(name);
// special handling for computer players.
if (name == "cpu") { isAI = true; }
else { isAI = false; }
}
public void printScore() {
Console.WriteLine(name + " score: " + this.score);
}
public int playRound(Random rnd, Die d1, Die d2, Die d3) {
// Prompt the player so the dice don't roll immediately
this.prompt();
// Roll all the dice (pass the same rng for each one)
d1.roll(rnd);
d2.roll(rnd);
d3.roll(rnd);
// Work out which dice is highest, roll the smaller 2 again
if (d1.getValue() > d2.getValue() && d1.getValue() > d3.getValue()) {
d2.roll(rnd);
d3.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d2.getValue() > d3.getValue()) {
d3.roll(rnd);
}
else {
d2.roll(rnd);
}
}
else if (d2.getValue() > d1.getValue() && d2.getValue() > d3.getValue()) {
d1.roll(rnd);
d3.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d1.getValue() > d3.getValue()) {
d3.roll(rnd);
}
else {
d1.roll(rnd);
}
}
else {
d1.roll(rnd);
d2.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d1.getValue() > d2.getValue()) {
d2.roll(rnd);
}
else {
d1.roll(rnd);
}
}
// All dice are rolled, just calculate total
int total = d1.getValue() + d2.getValue() + d3.getValue();
return total;
}
}
public class Die
{
private int value;
public int getValue()
{
return this.value;
}
public void setValue(int value)
{
this.value = value;
}
public void roll(Random rnd)
{
this.value = rnd.Next(1, 7);
}
}
public class Game
{
public static string promptForPlayType()
{
Console.WriteLine("Please enter play type ('match' or 'score')");
string playType = null;
// Make sure the user enters a valid value
while (playType != "match" && playType != "score")
{
playType = Console.ReadLine();
if (playType != "match" && playType != "score")
{
Console.WriteLine("Please enter one of the two options");
}
}
return playType;
}
// Entry point
public static void Main()
{
// Prompt the user for the game play type they'd want (match or score)
string playType = promptForPlayType();
// Create rng, need this because otherwise the seed gets re-initialised to
// the same value each time
Random rnd = new Random();
// Create the players & prompt for their names
Player p1 = new Player();
Player p2 = new Player();
p1.promptForName();
p2.promptForName();
// Create the 3 dice we'll be using
Die d1 = new Die();
Die d2 = new Die();
Die d3 = new Die();
// The big 'game loop' where everything happens
for (int i = 0; i < 5; i = i + 1)
{
// Basically everything happens in these method calls
var p1Result = p1.playRound(rnd, d1, d2, d3);
var p2Result = p2.playRound(rnd, d1, d2, d3);
// Increment score based on result
if (playType == "match")
{
if (p1Result > p2Result)
{
Console.WriteLine(p1.getName() + " won a round");
p1.addScore(1);
}
else if (p2Result > p1Result)
{
Console.WriteLine(p2.getName() + " won a round");
p2.addScore(1);
}
else
{
Console.WriteLine("Game drawn");
}
}
else if (playType == "score")
{
p1.addScore(p1Result);
p2.addScore(p2Result);
}
// Print out running totals
Console.WriteLine("Player scores:");
Console.WriteLine(p1.getName() + ": " + p1.getScore());
Console.WriteLine(p2.getName() + ": " + p2.getScore());
}
Console.WriteLine("\n");
if (p1.getScore() > p2.getScore())
{
Console.WriteLine("Player 1 won");
}
else if (p2.getScore() > p1.getScore())
{
Console.WriteLine("Player 2 won");
}
else
{
Console.WriteLine("The game was a draw");
}
}
}
Enclose it in while loop until users exit from it.
public static void Main()
{
bool flag = true;
while(flag){
//your game here
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if(playAgain == "n")
flag = false;
}
}
Related
I am trying to build a countdown timer that if the selected choice is set time, it will open and prompts the user to enter value to set the time. once the user is done in typing the numbers, it must show choices like this
Press S to start: Press P to pause
This is what I am lacking, I do not know what to code to enable to pause the time and to start it.
using System;
namespace time_console
{
class Program
{
static void Main(string[] args)
{
designNumbers Fancy = new designNumbers();
Program mainMenu = new Program();
mainMenu.RunMainMenu();
}
private void RunMainMenu()
{
string prompt = "Welcome to Neil's Countdown Timer. Select an option";
string[] options = { "Set Time", "Exit" };
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
SetTime();
break;
case 1:
Exit();
break;
}
}
private void SetTime()
{
Console.SetCursorPosition(4, 4);
Console.WriteLine("enter time in minutes:seconds ");
Console.SetCursorPosition(4, 5);
int m = Convert.ToInt32(Console.ReadLine());
Console.SetCursorPosition(4, 6);
int s = Convert.ToInt32(Console.ReadLine());
for (; ; )
{
if (s == 0 && m == 0)
{
Console.WriteLine("\nTime's up!");break;
}
if (s == 0)
{
s = 60;
m--;
}
System.Console.Clear();
Console.SetCursorPosition(4, 7);
Console.WriteLine(m + ":" + s--);
System.Threading.Thread.Sleep(1000);
}
WriteLine("Press M to return to Menu");
ConsoleKey a;
ConsoleKeyInfo b = ReadKey(true);
a = b.Key;
if(a == ConsoleKey.M)
{
RunMainMenu();
}
}
private void Exit()
{
WriteLine("press any key to exit...");
ReadKey(true);
Environment.Exit(0);
}
}
}
I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}
I made a game where you first say how many players there are and then every player throws 3 darts and it loops until one player gets 301 points and now I want to get the player who got more than 301 points from the list of players and I want to get their score so I can print out their score and say that they won at the end of the game but I can't figure out how to do that. Thanks
class Program
{
public static void Main(string[] args)
{
Game My_game = new Game();
My_game.PlayGame();
}
}
public class Game
{
private List<Player> player_list = new List<Player>();
private List<int> total_list = new List<int>();
public void PlayGame()
{
Random random_number = new Random();
int throw1;
int throw2;
int throw3;
string more_players = "yes";
while (more_players == "yes")
{
Console.WriteLine("What is the players name?: ");
player_list.Add(new Player(Console.ReadLine()));
Console.WriteLine("Are there more players?");
more_players = Console.ReadLine();
}
Console.WriteLine("\n\n Welcome to the dartgame! \n" +
"\n Game Rules: Each player throws 3 darts at a time." +
"\n Every throw can be worth 0-20 points." +
"\n Whoever gets 301 points first is the winner!");
Console.WriteLine("\nPlayers:");
foreach (var players in player_list)
{
Console.WriteLine(players);
}
int total_points = 0;
while (!player_list.Any(x => x.calculate_points() >= 301))
{
foreach (var players in player_list)
{
Console.WriteLine("\n\n\n\n");
Console.WriteLine("\n first throw for{0}!", players);
Console.WriteLine("Press space to throw a dart!");
Console.ReadKey();
throw1 = random_number.Next(1, 20);
Console.WriteLine("You got " + throw1 + " points!");
Console.WriteLine("\n second throw for{0}!", players);
Console.WriteLine("Press space to throw a dart!");
Console.ReadKey();
throw2 = random_number.Next(1, 20);
Console.WriteLine("You got " + throw2 + " points!");
Console.WriteLine("\n third throw for{0}!", players);
Console.WriteLine("Press space to throw a dart!");
Console.ReadKey();
throw3 = random_number.Next(1, 20);
Console.WriteLine("You got " + throw3 + " points!");
total_points = throw1 + throw2 + throw3;
Console.WriteLine("\nPoints for this round: " + total_points);
total_list.Add(total_points);
total_points = total_list.Sum(x => Convert.ToInt32(x));
players.Add_turn(throw1, throw2, throw3);
}
foreach (var players in player_list)
{
players.print_turns();
}
}
}
}
class Player
{
private string name;
private List<Turns> turn_list = new List<Turns>();
public Player(string _name)
{
name = _name;
}
public void Add_turn(int turn1, int turn2, int turn3)
{
turn_list.Add(new Turns(turn1, turn2, turn3));
}
public int calculate_points()
{
int total = 0;
foreach (var turns in turn_list)
{
total = total + turns.Get_Score();
}
return total;
}
public void print_turns()
{
Console.WriteLine("\n\n\n\n----------------------------------------");
Console.WriteLine("Points for {0}", name);
foreach (var turns in turn_list)
{
Console.WriteLine(turns);
}
Console.WriteLine("\n Total points: {0}", calculate_points());
}
public override string ToString()
{
return string.Format(" {0} ", name);
}
}
class Turns
{
private int turn1;
private int turn2;
private int turn3;
public Turns(int _turn1, int _turn2, int _turn3)
{
turn1 = _turn1;
turn2 = _turn2;
turn3 = _turn3;
}
public int Get_Score()
{
int totalt;
totalt = turn1 + turn2 + turn3;
return totalt;
}
public override string ToString()
{
return string.Format("\n throw 1: {0} \n throw 2: {1} \n throw 3: {2}", turn1, turn2, turn3);
}
}
Well, this is how you already check if any players match the criteria:
player_list.Any(x => x.calculate_points() >= 301)
So as soon as one does match the criteria, you can get that single player:
player_list.Single(x => x.calculate_points() >= 301)
Or all matching players, if there's more than one:
player_list.Where(x => x.calculate_points() >= 301)
Or just the first matching player, if there's more than one but you only want one:
player_list.First(x => x.calculate_points() >= 301)
Or perhaps the player with the highest score (not accounting for a tie score):
player_list.OrderByDescending(x => x.calculate_points()).First();
I recently started making a RPS game console app it worked and I decided to give myself more of a challenge and decided it will be cool if it had a win rate for both computer and player and for some reason it's not showing the win rates on the left side
EDIT: So I got it to show left but the percents remain at 0 any idea how to fix this?
abstract class Participant
{
public int wins;
int _winRate;
public int winRate
{
get
{
return _winRate;
}
set
{
if (value < 0 || value > 100)
{
throw new Exception("value cannot be less than 0 or greater than 100");
}
_winRate = value;
}
}
public abstract string Choice();
public abstract void PrintWinRate();
}
class Computer : Participant
{
string[] Rock_Paper_Scissor = {"rock","paper","scissor"};
Random rand = new Random();
public override string Choice()
{
string element = Rock_Paper_Scissor[rand.Next(3)];
return element;
}
public override void PrintWinRate()
{
winRate = (wins / Game_Logic.gamesPlayed) * 100;
string _winRate = "computer win rate: "+winRate.ToString()+"%".PadRight(10);
Console.WriteLine(_winRate);
}
}
class Player : Participant
{
public override string Choice()
{
string playerChoice = Console.ReadLine().Trim();
return playerChoice;
}
public override void PrintWinRate()
{
winRate = (wins / Game_Logic.gamesPlayed) * 100;
string _winRate = "player win rate: " + winRate.ToString()+"%".PadRight(10);
Console.WriteLine(_winRate);
}
}
class Game_Logic
{
public static int gamesPlayed;
static void Main()
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Computer comp = new Computer();
Player player = new Player();
string computerChoice;
string playerChoice;
ConsoleKeyInfo input;
bool playAgain;
int computerWins = comp.wins;
int playerWins = player.wins;
do
{
Console.Clear();
computerChoice = comp.Choice();
playerChoice = player.Choice();
Console.Clear();
while (playerChoice == computerChoice)
{
computerChoice = comp.Choice();
}
Console.WriteLine("Player: "+ playerChoice);
Console.WriteLine("\n"+"Computer: " + computerChoice);
if (playerChoice == "rock" && computerChoice == "scissor" || playerChoice == "paper" && computerChoice == "rock")
{
playerWins++;
Console.WriteLine("\n" + "You won!");
}
else if (playerChoice == "scissor" && computerChoice == "rock" || playerChoice == "rock" && computerChoice == "paper")
{
computerWins++;
Console.WriteLine("\n" + "Computer won!");
}
else if (playerChoice == "scissor" && computerChoice == "paper")
{
playerWins++;
Console.WriteLine("\n" + "You won!");
}
else if (playerChoice == "paper" && computerChoice == "scissor")
{
computerWins++;
Console.WriteLine("\n" + "Computer won!");
}
else
{
Console.WriteLine("\n" + "invalid value");
}
Game_Logic.gamesPlayed++;
Console.WriteLine("\n"+"Play again? <y/n>");
Console.WriteLine("\n");
comp.PrintWinRate();
player.PrintWinRate();
input = Console.ReadKey(true);
playAgain = input.KeyChar == 'y';
} while (playAgain);
}
}
First things first, I think there is a problem with the increment logic, not being able to increment the actual values of participant object. playerWins and computerWins are local variables of your main, and considered as new variable, not just as reference of your participant objects. Change the following lines:
playerWins++ to player.wins++ //Change the actual values of participant
computerWins++ to comp.wins++
Next, when you say left? What format specifically would you want? For now try the following lines:
string _winRate = string.Format("player win rate: {0}%", winRate);
Your game is displaying the scores but instantly clears the screen or exits.
Placing the 'PrintWinRate' calls before 'Console.ReadKey' should give you the desired behaviour!
Like this:
Console.WriteLine("\n" + "Play again? <y/n>");
Console.WriteLine("\n");
comp.PrintWinRate();
player.PrintWinRate();
input = Console.ReadKey(true);
Edit: There also seems to be a bug in the calculation for winRate.
You might want to change your value type for 'wins' from 'int' to 'float' so that it can store the fractional part of the calculation. As it is, when you expect a player to have 50% winRate it will show 0. This is because 'int' data types can not hold fractional values and will cut that part off, leaving the whole number - in this case 0.
This code should be closer to what you want:
winRate = (int)((wins / Game_Logic.gamesPlayed) * 100);
Remember to change 'wins' in your base class 'Participant' to be a float!
Im having trouble learning how to loop, and Im stuck on how to do this. Basically I was asked to program that rolls a 6 sided die and it'll ask you how many times you want to roll it. Based on how many times you roll, it will out put a table of how many times it landed on each side. This is what I have so far.
using System;
namespace Dice
{
class Program
{
static void Main(string[] args)
{
bool continueRunning = true;
int sessionNumber = 1;
DisplayInstructions();
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
aDice.RollDice();
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}
}
public static bool getYorN(string question)
{
bool validInput = false;
while (!validInput)
{
Console.WriteLine("{0}", question);
Console.WriteLine("Enter 'yes' or 'no' to continue...");
string userResponse = Console.ReadLine().ToLower();
if (userResponse == "yes" || userResponse == "no")
{
validInput = true;
switch (userResponse)
{
case "yes":
return true;
case "no":
return false;
default:
return false;
}
}
else
{
Console.Clear();
Console.WriteLine("You've entered an invalid term");
}
}
return false;
}
public static void DisplayInstructions()
{
Console.WriteLine("Welcome to the Dice Game!!");
Console.WriteLine("\n\n\nThis program will simulate rolling a die and will track the frequency \neach value is rolled.");
Console.WriteLine("\n\n\nAfter rolling the die, the program will output a summary table for the session.");
Console.WriteLine("\n\n\nPlease press any key to continue.");
Console.ReadKey();
Console.Clear();
}
public static string getInfo(string what)
{
Console.WriteLine(what);
return Console.ReadLine();
}
}
}
The class I have in this is
using System;
namespace TripCalcApp
{
class Dice
{
private int side1 = 0, side2 = 0, side3 = 0, side4 = 0, side5 = 0, side6 = 0;
Random randNum = new Random();
public Dice()
{
}
public int Side1
{
get { return side1; }
set { side1 = value; }
}
public int Side2
{
get { return side2; }
set { side2 = value; }
}
public int Side3
{
get { return side3; }
set { side3 = value; }
}
public int Side4
{
get { return side4; }
set { side4 = value; }
}
public int Side5
{
get { return side5; }
set { side5 = value; }
}
public int Side6
{
get { return side6; }
set { side6 = value; }
}
public void RollDice()
//RollDice = randNum.Next(1, 7)
{
switch (randNum.Next(1, 7))
{
case 1: side1++;
break;
case 2: side2++;
break;
case 3: side3++;
break;
case 4: side4++;
break;
case 5: side5++;
break;
case 6: side6++;
break;
}
}
public override string ToString()
{
return " Freq. Rolls " +
"________________________________________" +
"\nSide 1 of Die rolled :" + side1 +
"\nSide 2 of Die rolled :" + side2 +
"\nSide 3 of Die rolled :" + side3 +
"\nSide 4 of Die rolled :" + side4 +
"\nSide 5 of Die rolled :" + side5 +
"\nSide 6 of Die rolled :" + side6 +
"\n";
}
}
}
I had an idea on how to do loop it but Im still unsure. I thought of something like this but it doesnt work and I was hoping you guys could help me!!
int howMany = int.Parse(getInfo("How many times would you like to roll the die?"));
do
{
Dice aDice = new Dice();
for (int counter = howMany; counter > 0; counter--)
{
aDice.RollDice();
}
while (howMany < 0)
{
Console.WriteLine(aDice);
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
playAgain = getYorN("Would you like to play again?");
sessionNumber++;
}
All you need to do is call aDice.RollDice method howMany times:
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
for(int i = 0; i < howMany; i++)
{
aDice.RollDice();
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}