How to make a game move continuously - c#

I'm trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). I've got halfway through, however, when a player makes a move, the board will simply reset to normal for the next move. Any thoughts on how I can make another move to the board and it takes into account the previous move?
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static string firstMove;
static bool gameStatus = true;
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
PlayingGame();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\t\t" + underline + "Welcome to NIM!\n"+ reset);
Thread.Sleep(1000);
Console.WriteLine(underline + "The rules are as follows:\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Thread.Sleep(1500);
}
static void InitialBoardSetUp()
{
Console.WriteLine(underline + "This is how the board is formatted:\n" + reset);
Thread.Sleep(750);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
Console.Write("███ ");
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void WhoGoesFirst()
{
string[] PossibleChoices = { "Computer", "You" };
Random WhoGoesFirst = new Random();
int WGFIndex = WhoGoesFirst.Next(0, 2);
firstMove = PossibleChoices[WGFIndex];
Console.WriteLine("Randomly selecting who goes first...");
Thread.Sleep(1000);
Console.WriteLine("{0} will go first!\n", firstMove);
Thread.Sleep(1000);
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 8);
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 8);
Console.WriteLine("Computer is making its move... ");
Thread.Sleep(1000);
Console.WriteLine("Computer has decided to remove {0} blocks from stack number {1}.\n", CompRemovedSelection, CompStackSelection);
Thread.Sleep(1000);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == CompStackSelection && i <= CompRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.WriteLine();
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == PlayerStackSelection && i <= PlayerRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayingGame()
{
int gameNumber = 1;
while (gameStatus == true)
{
Console.WriteLine(underline + "Round " + gameNumber+ ":\n" + reset);
WhoGoesFirst();
if (firstMove == "Computer")
{
ComputerMove();
}
else
{
PlayerMove();
}
gameNumber += 1;
playAgain();
}
}
static void playAgain()
{
Console.Write("Do you wish to play again? (Y/N): ");
char playAgain = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
if (playAgain == 'Y')
{
gameStatus = true;
}
else if (playAgain == 'N')
{
gameStatus = false;
}
}

In PlayingGame() you need to create a game loop.
static void PlayingGame()
{
int turn = // randomly choose 0 or 1 (whose turn is it)
bool finished = false;
while(!finished)
{
if(turn==0)
{
ComputerMove();
} else {
PlayerMove();
}
finished = CheckForEndOfGame();
turn = 1 - turn;
}
}
I do strongly suggest to create a Game class that handles the logic of the game and separate the UI (like messages etc) from the game mechanics. This is C# after all, and object oriented approaches are strongly encouraged.
You need to keep track of that game board and whose turn it is and what has been played in this Game class and display on the screen things based on the values (the state) of the game.

Related

Formatting Issue with for loop c#

I'm trying to create a game called 'NIM' (See code introduction if you aren't familiar). When I output the 'blocks' they aren't spaced out evenly. I may be missing the obvious, but can someone point out where I'm going wrong.
using System;
using System.Threading;
namespace NIM
{
class Program
{
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\tWelcome to NIM!\n");
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Console.WriteLine("Initialising the board:\n");
Thread.Sleep(2000);
}
static void InitialBoardSetUp()
{
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + "\t");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" "+ i);
for (int j = 1; j <= 7; j++)
{
Console.Write(" ███\t");
}
Console.Write("\n");
}
}
}
}
The code below is your code with some minor modifications. \t has been removed and replaced with spaces. Spaces added before writing the column headers. Added comments.
Try the following:
using System;
using System.Threading;
namespace NIM
{
class Program
{
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\tWelcome to NIM!\n");
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Console.WriteLine("Initialising the board:\n");
//Thread.Sleep(2000);
}
static void InitialBoardSetUp()
{
//add space for row numbers
Console.Write(" ");
//print column headers
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
//print row numbers
Console.Write(" " + i);
for (int j = 1; j <= 7; j++)
{
//print blocks
Console.Write(" ███ ");
}
Console.Write("\n");
}
}
}
}

breaks while loop when all die rolls the same number

using System;
using System.Collections.Generic;
namespace AnyDice
{
class Program
{
static void Main(string[] args)
{
int diceSides;
int rollDie;
int count = 0;
bool keepRolling = true;
List<int> num = new List<int>();
Random random = new Random();
Console.Write("Write the number of sides of your die: ");
diceSides = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Type the numbers of the die");
for (int i = 0; i < diceSides; i++)
{
int rank = 1 + i;
Console.Write(rank + "~~> ");
num.Add(Convert.ToInt32(Console.ReadLine()));
}
num.Sort();
Console.WriteLine("\nHere's the die and its contents");
for (int i = 0; i < num.Count; i++)
{
Console.Write("[");
Console.Write(num[i]);
Console.Write("]");
}
Console.WriteLine("\nHow many times do you want to roll at once");
rollDie = Convert.ToInt32(Console.ReadLine());
while (keepRolling)
{
for (int i = 0; i < rollDie; i++)
{
Console.Write("[");
Console.Write(num[random.Next(num.Count)]);
Console.Write("]");
count++;
}
Console.ReadLine();
}
Console.WriteLine("It took you " + count + " attempts");
Console.ReadLine();
}
}
}
For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks.
I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.
We have Linq. It lives in the System.Linq namespace and this might help you.
I'll should two ways of checking if all die are the same:
int first = dies.First();
if (dies.All(i => i == first))
{
// break if all are equals to the first die
}
Or using Distinct we can filter out any copies.
if (dies.Distinct().Count() == 1)
{
// if we only have unique items and the count is 1 every die is the same
}
I am not 100% sure I understand your requirement, but in any case, you should write a separate function that returns a flag indicating whether the array is in a state that should trigger a break.
bool KeepRolling(int[] num)
{
for (int i=0; i<num.Length; i++)
{
if (num[i] >= i) return false;
}
return true;
}
Then just call it from within your loop:
keepRolling = KeepRolling(num);
while (keepRolling)
{
rolls.Clear();
for (int i = 0; i < rollDie; i++)
{
var firstRoll = num[random.Next(num.Count)];
rolls.Add(firstRoll);
Console.Write(firstRoll + " ");
count++;
}
if (rolls.Distinct().Count() == 1)
{
Console.WriteLine("It took you " + count + " attempts");
keepRolling = false;
break;
}
Console.ReadLine();
}

Error in parsing an input string to int value in c#

First if works great
Second if throws an exception
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray;
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0);
}
if (numbersArray[i] > numbersArray[i - 1])
{
if (numInput == "") {
break;
}
}
}
i++;
}
Console.WriteLine("You entered this series: ");
for (int j = 0; j < numbersArray.Length; j++)
{
Console.WriteLine(" " + numbersArray[j]);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
}
}
You can't parse a string wihout digits like numInput = ""
EDIT: Try this code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray = new []{1};
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
if (numInput == null || !numInput.All(char.IsDigit)) continue;
if (numInput != "")
{
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0); // <-- Code is unreachable!
}
}
i++;
}
else if(i >= 1)
{
break;
}
}
Console.WriteLine("You entered this series: ");
foreach (int t in numbersArray)
{
Console.WriteLine(" " + t);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
Console.ReadLine();
}
I assume you are trying to look at a index not existing.
Not sure of your language but I guess numbersArray[0] is the first index and numbersArray[1] is the second. So when you input your first number then you try to look at numbersArray[1] which doesn't exist.

C# Homework Dice Game

Im taking and Into c# course and Im having alot of fun learning, however Im getting stuck on this one assignment--I have to simulate rolling a 6 sided dice/die 500 times (user must input the number of rolls) while displaying the frequency of each side(1-6) and % roll. In addition I cant use arrays.
So To start what I did was Initiate a bool to loop my code because I have to ask the user if they want to roll again. Then I created a variable for dice1 and set it to a Random number between 1-6. I tried setting a variable to a console readline that was equal to the dice1 to have the user enter the number. This is pretty much where I get stuck and cant move forward.
I know many of you are much more knowledgeable than I am so It'd be great If anyone could give me some advice.
Here's what I have so far:
static void Main(string[] args)
{
//Initiate Looping Seqence
bool choice = true;
while (choice)
{
//Display Introduction and Instructions
Console.WriteLine("Welcome To The Dice Game!");
Console.WriteLine("This Program will simulate rolling a die and will track");
Console.WriteLine("the Frequency each value is rolled Then Display a Session Summary");
Console.WriteLine("Press any key to continue.....");
Console.ReadKey();
Console.Clear();
Console.WriteLine("How many times would you like to roll the die?");
Random randomNum = new Random();
int dice1;
dice1 = randomNum.Next(1, 7);
int choice2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.WriteLine(dice1);
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int s6 = 0;
Console.WriteLine("Would you Like to Run This Program Again?");
Console.WriteLine("Type \"yes\" to re-run or Type \"no\" to exit?");
Console.ReadKey();
string option;
option = Console.ReadLine();
}
}
// public static double RollDice()
//{
// was not sure if to create a dice roll method
//}
}
}
Have a break, take my code ヽ(^o^)丿
class Program {
#region lambda shortcuts
static Action<object> Warn = m => {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(m);
};
static Action<object> Info = m => {
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(m);
};
static Action<object> WriteQuery = m => {
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(m);
};
static Action BreakLine = Console.WriteLine;
#endregion
static void Main(string[] args) {
Console.Title = "The Dice Game";
while(true) {
bool #continue = RunDiceGame();
if(!#continue) {
break;
}
Console.Clear();
}
}
static bool RunDiceGame() {
//Display Introduction and Instructions
Info("Welcome To The Dice Game!");
Info("This Program will simulate rolling a dice and keeps track of the results");
BreakLine();
WriteQuery("Dice roll count: ");
int rollCount = ReadInt32();
WriteQuery("Random number generator seed: ");
Random rng = new Random(ReadInt32());
BreakLine();
BreakLine();
//map dice value to dice count
var diceValues = new Dictionary<int, int>((int)rollCount);
for(int i = 0; i < 6; i++) {
diceValues.Add(i, 0);
}
//roll dice
for(int i = 0; i < rollCount; i++) {
int diceValue = rng.Next(6); //roll 0..5
diceValues[diceValue]++;
}
//print results
for(int i = 0; i < 6; i++) {
int valueRollAbsolute = diceValues[i];
double valueRollCountRelative = valueRollAbsolute / (double) rollCount;
Info(string.Format("Value: {0}\tCount: {1:0,0}\tPercentage: {2:0%}", i + 1, valueRollAbsolute, valueRollCountRelative));
}
BreakLine();
BreakLine();
WriteQuery("Type 'yes' to restart, 'no' to exit.");
BreakLine();
return ReadYesNo();
}
#region console read methods
static int ReadInt32() {
while(true) {
string input = Console.ReadLine();
try {
return Convert.ToInt32(input);
} catch(FormatException) {
Warn("Not a number: " + input);
}
}
}
static bool ReadYesNo() {
while(true) {
string option = Console.ReadLine();
switch(option.ToLowerInvariant()) {
case "yes":
return true;
case "no":
return false;
default:
Warn("Invalid option: " + option);
break;
}
}
}
#endregion
}
Here is some code to simulate the rolls & get how many times a number popped up
int rollAmount = 500;
int dice;
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int s6 = 0;
Random random = new Random();
for(int i = 0; i <= rollAmount; i++){
dice = random.next(1,7);
Console.Writeline("Roll " + i + ": " + dice.ToString());
if(dice == 1) s1++;
else if(dice == 2) s2++;
else if(dice == 3) s3++;
...
}
Console.Writeline("1 Percentage: " + ((s1 / rollAmount) * 100) + "%");
Console.Writeline("2 Percentage: " + ((s2 / rollAmount) * 100) + "%");
Console.Writeline("3 Percentage: " + ((s3 / rollAmount) * 100) + "%");
...
Console.Writeline("Done");

Keeping track of what the user inputs

This is my hangman code, and its almost good up to the point where it displays the guessed letters. It only displays the most recent guessed letter but I want it to continue on from whats left off. Such as if a person guess "A" and then "L" then Guessed letters are A, L.
I tried using a for loop after "Guessed letters are" but then it gives me the output
"A, A, A, A, A". What should I do to fix this problem?
class Hangman
{
public string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
public string[] torture = new string[6] { "left arm", "right arm", "left leg", "right leg", "body", "head" };
public char[] guessed = new char[26];
int i;
public void randomizedWord()
{
Random random = new Random();
int index = random.Next(0, 5);
char[] hidden = new char[words[index].Length];
string word = words[index];
Console.WriteLine(words[index]);
Console.Write("The word is: ");
for (i = 0; i < hidden.Length; i++)
{
Console.Write('-');
hidden[i] = '-';
}
Console.WriteLine();
int lives = 6;
do
{
Console.WriteLine("Guess a letter: ");
char userinput = Console.ReadLine().ToCharArray()[0];
index++;
guessed[index] = userinput;
Console.WriteLine("Guessed letters are: " + guessed[index]);
bool foundLetter = false;
for (int i = 0; i < hidden.Length; i++)
{
if (word[i] == userinput)
{
hidden[i] = userinput;
foundLetter = true;
Console.WriteLine("You guessed right!");
}
}
for (int x = 0; x < hidden.Length; x++)
{
Console.Write(hidden[x]);
}
if (!foundLetter)
{
Console.WriteLine(" That is not a correct letter");
lives--;
if (lives == 5)
{
Console.WriteLine("You lost a " + torture[0]);
}
else if (lives == 4)
{
Console.WriteLine("You lost the " + torture[1]);
}
else if (lives == 3)
{
Console.WriteLine("You lost your " + torture[2]);
}
else if (lives == 2)
{
Console.WriteLine("You lost the " + torture[3]);
}
else if (lives == 1)
{
Console.WriteLine("You lost your " + torture[4]);
}
else
{
Console.WriteLine("You lost your " + torture[5]);
Console.WriteLine("You lose!");
break;
}
}
bool founddash = false;
for (int y = 0; y < hidden.Length; y++)
{
if (hidden[y] == '-')
{
founddash = true;
}
}
if (!founddash)
{
Console.WriteLine(" You Win! ");
break;
}
Console.WriteLine();
} while (lives != 0);
}
I was going to post on your other thread Hangman Array C#
Try changing this line
Console.WriteLine("Guessed letters are: " + guessed[index]);
To
Console.WriteLine("Guessed letters are: " + string.Join(" ", guessed).Trim());
I had a play with your hangman game and came up with this solution (while we are doing your homework). Although not related to the question.
public class HangCSharp
{
string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
List<char> guesses;
Random random = new Random();
string word = "";
string current = "";
int loss = 0;
readonly int maxGuess = 6;
int highScrore = 0;
public void Run()
{
word = words[random.Next(0, words.Length)];
current = new string('-', word.Length);
loss = 0;
guesses = new List<char>();
while (loss < maxGuess)
{
Console.Clear();
writeHeader();
writeLoss();
writeCurrent();
var guess = Console.ReadKey().KeyChar.ToString().ToUpper()[0];
while (!char.IsLetterOrDigit(guess))
{
Console.WriteLine("\nInvalid Guess.. Please enter a valid alpha numeric character.");
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
while (guesses.Contains(guess))
{
Console.WriteLine("\nYou have already guessed {0}. Please try again.", guess);
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
guesses.Add(guess);
if (!isGuessCorrect(guess))
loss++;
else if (word == current)
break;
}
Console.Clear();
writeHeader();
writeLoss();
if (loss >= maxGuess)
writeYouLoose();
else
doYouWin();
Console.Write("Play again [Y\\N]?");
while (true)
{
var cmd = (Console.ReadLine() ?? "").ToUpper()[0];
if (cmd != 'Y' && cmd != 'N')
{
Console.WriteLine("Invalid Command. Type Y to start again or N to exit.");
continue;
}
else if (cmd == 'Y')
Run();
break;
}
}
bool isGuessCorrect(char guess)
{
bool isGood = word.IndexOf(guess) > -1;
List<char> newWord = new List<char>();
for (int i = 0; i < word.Length; i++)
{
if (guess == word[i])
newWord.Add(guess);
else
newWord.Add(current[i]);
}
current = string.Join("", newWord);
return isGood;
}
void writeCurrent()
{
Console.WriteLine("Enter a key below to guess the word.\nHint: {0}", current);
if (guesses.Count > 0)
Console.Write("Already guessed: {0}\n", string.Join(", ", this.guesses));
Console.Write(":");
}
void writeHeader()
{
Console.WriteLine("Hang-CSharp... v1.0\n\n");
if (highScrore > 0)
Console.WriteLine("High Score:{0}\n\n", highScrore);
}
void writeYouLoose()
{
Console.WriteLine("\nSorry you have lost... The word was {0}.", word);
}
void doYouWin()
{
Console.WriteLine("Congratulations you guessed the word {0}.", word);
int score = maxGuess - loss;
if (score > highScrore)
{
highScrore = score;
Console.WriteLine("You beat your high score.. New High Score:{0}", score);
}
else
Console.WriteLine("Your score:{0}\nHigh Score:{1}", score, highScrore);
}
void writeLoss()
{
switch (loss)
{
case 1:
Console.WriteLine(" C");
break;
case 2:
Console.WriteLine(" C{0} #", Environment.NewLine);
break;
case 3:
Console.WriteLine(" C\n/#");
break;
case 4:
Console.WriteLine(" C\n/#\\");
break;
case 5:
Console.WriteLine(" C\n/#\\\n/");
break;
case 6:
Console.WriteLine(" C\n/#\\\n/ \\");
break;
}
Console.WriteLine("\n\nLives Remaining {0}.\n", maxGuess - loss);
}
}
Can be run as new HangCSharp().Run();
The index variable is being set to a random number when the random word is selected in this line.
int index = random.Next(0, 5);
Then that index is being used to store the guesses in the do..while loop. However, since index starts from a random number between 0 and 5 you see unexpected behaviour.
Set index to 0 in the line before the do..while loop and the for loop (or the alternatives suggested elsewhere) should work e.g. as so
index = 0;
int lives = 6;
do
{
// rest of the code

Categories