I would like to set the position of the cursor in the Console to the last visible line. How can I do this?
Cheers,
Pete
If you mean the last line of the window, you can use a mixture of Console.CursorTop, and Console.WindowHeight and Console.WindowTop. Sample code:
using System;
class Test
{
static void Main()
{
Console.Write("Hello");
WriteOnBottomLine("Bottom!");
Console.WriteLine(" there");
}
static void WriteOnBottomLine(string text)
{
int x = Console.CursorLeft;
int y = Console.CursorTop;
Console.CursorTop = Console.WindowTop + Console.WindowHeight - 1;
Console.Write(text);
// Restore previous position
Console.SetCursorPosition(x, y);
}
}
Note that this has to take account of Console.WindowTop to find out where you are within the buffer...
I also had to solve this problem and came out with this:
public class Program
{
static int id = 0 , idOld = 0, idSelected = -1;
static string[] samples;
public static void Main()
{
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WindowWidth = 90;
Console.WindowHeight = 36;
Console.WindowTop = 5;
Console.Title = "My Samples Application";
Console.InputEncoding = Encoding.GetEncoding("windows-1251");
samples = new string[50];
for (int i = 0; i < samples.Length; i++)
samples[i] = "Sample" + i;
LoopSamples();
}
static void SelectRow(int y, bool select)
{
Console.CursorTop = y + 1;
Console.ForegroundColor = select ? ConsoleColor.Red : ConsoleColor.Yellow;
Console.WriteLine("\t{0}", samples[y]);
Console.CursorTop = y;
}
static void LoopSamples()
{
int last = samples.Length - 1;
ShowSamples();
SelectRow(0, true);
while (true)
{
while (idSelected == -1)
{
idOld = id;
ConsoleKey key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.UpArrow:
case ConsoleKey.LeftArrow: if (--id < 0) id = last; break;
case ConsoleKey.DownArrow:
case ConsoleKey.RightArrow: if (++id > last) id = 0; break;
case ConsoleKey.Enter: idSelected = id; return;
case ConsoleKey.Escape: return;
}
SelectRow(idOld, false);
SelectRow(id, true);
}
}
}
static void ShowSamples()
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Use arrow keys to select a sample. Then press 'Enter'. Esc - to Quit");
for (int i = 0; i < samples.Length; i++)
Console.WriteLine("\t{0}", samples[i]);
}
}
Related
I make this little Escape Room game where the player needs to collect a key for getting out of the room. How can I make the Key disappear whenever the player steps on it? This is my code so far. I know I haven't used any methods because I haven't learned it in university so far.. So it would be great if anyone has a simple solution or help for me. Thanks in advance! <3
static void Main(string[] args)
{
ConsoleKeyInfo consoleKey;
int XPositionCursor = 5;
int YPositionCursor = 5;
int MapWidth = 20;
int MapHeight = 20;
char Wall = '█';
bool GameOver = true;
char Key = '#';
char Character = 'H';
int[,] MapGenerationArray = new int[MapWidth, MapHeight];
Random RandomKeyCoordinate = new Random();
Random RandomDoorCoordinate = new Random();
#region Instructions
Console.WriteLine("Wähle eine Breite für dein Spielfeld:");
string MapWidthString = Console.ReadLine();
MapWidth = int.Parse(MapWidthString);
Console.Clear();
Console.WriteLine("Wähle eine Höhe für dein Spielfeld:");
string MapHeightString = Console.ReadLine();
MapHeight = int.Parse(MapHeightString);
Console.Clear();
Console.WriteLine($"Dein Spielfeld wird {MapWidth} x {MapHeight} groß sein!");
Console.ReadLine();
#endregion
Vector2 KeyCoordinate = new Vector2();
KeyCoordinate.X = RandomKeyCoordinate.Next(1, MapWidth - 1);
KeyCoordinate.Y = RandomKeyCoordinate.Next(1, MapHeight - 1);
Vector2 DoorCoordinate1 = new Vector2();
DoorCoordinate1.X = RandomDoorCoordinate.Next(0, MapWidth);
DoorCoordinate1.Y = RandomDoorCoordinate.Next(0, 0);
bool PlayerIsOnKeyPosition = XPositionCursor == KeyCoordinate.X && YPositionCursor == KeyCoordinate.Y;
bool PlayerCarryingKey = false;
do
{
#region Map
Console.Clear();
for (int i = 0; i < MapWidth; i++)
{
Console.SetCursorPosition(i, 0);
Console.Write(Wall);
}
for (int i = 0; i < MapWidth; i++)
{
Console.SetCursorPosition(i, MapHeight);
Console.Write(Wall);
}
for (int i = 0; i < MapHeight; i++)
{
Console.SetCursorPosition(0, i);
Console.Write(Wall);
}
for (int i = 0; i < MapHeight; i++)
{
Console.SetCursorPosition(MapWidth, i);
Console.Write(Wall);
}
#endregion
Console.SetCursorPosition(XPositionCursor, YPositionCursor);
Console.CursorVisible = false;
Console.Beep(200, 100);
Console.Write(Character);
if (PlayerIsOnKeyPosition)
{
PlayerCarryingKey = true;
}
if (PlayerCarryingKey == true)
{
Console.SetCursorPosition((int)DoorCoordinate1.X, (int)DoorCoordinate1.Y);
Console.Write(' ');
}
else
{
Console.SetCursorPosition((int)KeyCoordinate.X, (int)KeyCoordinate.Y);
Console.Write(Key);
Console.SetCursorPosition((int)DoorCoordinate1.X, (int)DoorCoordinate1.Y);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(Wall);
Console.ResetColor();
}
#region CharacterMovement
consoleKey = Console.ReadKey(true);
Console.Clear();
switch (consoleKey.Key)
{
case ConsoleKey.UpArrow:
YPositionCursor--;
break;
case ConsoleKey.DownArrow:
YPositionCursor++;
break;
case ConsoleKey.LeftArrow:
XPositionCursor--;
break;
case ConsoleKey.RightArrow:
XPositionCursor++;
break;
}
if (YPositionCursor < 1) { YPositionCursor = 1; }
if (XPositionCursor < 1) { XPositionCursor = 1; }
if (YPositionCursor >= MapHeight - 1) { YPositionCursor = MapHeight - 1; };
if (XPositionCursor >= MapWidth - 1) { XPositionCursor = MapWidth - 1; };
#endregion
} while (GameOver == true);
}
}
As #doctorlove wrote, you are calculating whether player has a key before your main loop (do/while).
But you should do this inside main loop, every time player changes his position.
Replace line if (PlayerIsOnKeyPosition) with this if (XPositionCursor == KeyCoordinate.X && YPositionCursor == KeyCoordinate.Y).
P.S. Good idea is to use methods (functions) to split code into smaller chunks :)
I am trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). The subroutine 'ComputerMove();' does not execute for some reason, why is that? I am yet to finish but it is the ComputerMove subroutine that I am confused with. Apologies in advance if I am missing something obvious.
(Edit: There is no error message, just a blank console)
using System;
using System.Threading;
namespace THE_NIM
{
class Program
{
static char[,] Board = new char[7, 12];
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static bool GameStatus = false;
static string firstMove;
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 PrintBoard()
{
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i <= 6; i++)
{
Console.Write(" ");
for (int j = 0; j <= 11; j++)
{
Console.Write(Board[i, j]);
}
Console.WriteLine();
Console.WriteLine();
}
}
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 PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
switch (PlayerStackSelection)
{
case(1):
PlayerStackSelection = 0;
break;
case (2):
PlayerStackSelection = 2;
break;
case (3):
PlayerStackSelection = 4;
break;
case (4):
PlayerStackSelection = 6;
break;
case (5):
PlayerStackSelection = 8;
break;
case (6):
PlayerStackSelection = 10;
break;
}
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == ' ')
{
spaces += 1;
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + PlayerRemovedSelection); i++)
{
Board[i, PlayerStackSelection] = ' ';
}
}
PrintBoard();
CheckIfBoardEmpty();
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 7);
int PreChangeStack = CompStackSelection;
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 7);
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
while (spaces == 7)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
CompStackSelection = CompStack.Next(1, 7);
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if ((nearestBlock + CompRemovedSelection) !< 8)
{
while ((nearestBlock + CompRemovedSelection) !< 8)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + CompRemovedSelection); i++)
{
Board[i, CompStackSelection] = ' ';
}
}
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, PreChangeStack);
Thread.Sleep(1000);
PrintBoard();
CheckIfBoardEmpty();
}
static void CheckIfBoardEmpty()
{
bool keepGoing = false;
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (Board[i,j] == '█')
{
GameStatus = false;
keepGoing = true;
break;
}
}
}
if (keepGoing != true)
{
Console.Write("BOARD EMPTY");
GameStatus = true;
}
}
static void Main(string[] args)
{
Introduction();
WhoGoesFirst();
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (j % 2 == 0)
{
Board[i, j] = '█';
}
else
{
Board[i, j] = ' ';
}
}
}
if (firstMove == "You")
{
while (GameStatus == false)
{
PlayerMove();
ComputerMove();
}
}
else
{
while (GameStatus == false)
{
ComputerMove();
PlayerMove();
}
}
}
}
}
I was trying to create an RPG. I have a problem with the menu where I can choose a class.
I was trying to create an menu where you can control the directions with the arrow keys to the specific class which then get highlighted with the foreground color red, like in a real game when you want to choose something you just use the arrow keys and the thing you are on gets highlighted.
My problem is I can't specify the location of the arrow keys when I press the arrow key. I can only go to the first location and another problem is when I highlight the rpg class to show the user where he is, all rpg classes get the foreground color. I used Console.Read to separate them but now I always have to press Enter to change the color.
Here is the code. I think after you opened the code u will understand my problem.
Best regards Csharpnoob61.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Enter_Eingabe
{
class Program
{
static void Main(string[] args)
{
//ints
int char_HP_Current = 20;
int char_HP_Full = 100;
double char_Exp_Current = 10;
double char_Exp_Full = 100;
int char_Level_Current = 1;
int GameOver = 0;
int char_Move_Left_Right = 0;
int char_Move_Up_Down = 8;
int Error = 0;
int Resting_Time = 0;
int Attack_Bonus = 0;
int Speech_Bonus = 0;
int Sneak_Bonus = 0;
int Armor_Bonus = 0;
int Casting_Bonus = 0;
//Strings
string char_Name = "";
string Current_Command;
string char_Status = "";
string char_Class;
string test;
Console.Clear();
Console.SetCursorPosition(0, 8);
do
{
string text = "Guardian";
Console.SetCursorPosition(15, 8);
Console.WriteLine(text);
Console.SetCursorPosition(45, 8);
Console.WriteLine("Paladin");
Console.SetCursorPosition(30, 8);
Console.WriteLine("Outlaw");
ConsoleKeyInfo KeyInfo;
KeyInfo = Console.ReadKey(true);
switch (KeyInfo.Key)
{
//Player Controlls
case ConsoleKey.RightArrow:
Console.SetCursorPosition(0, 8);
if (char_Move_Left_Right < 78)
{
char_Move_Left_Right+=14;
Console.SetCursorPosition(char_Move_Left_Right, char_Move_Up_Down);
Console.WriteLine("_");
Console.SetCursorPosition(char_Move_Left_Right - 1, char_Move_Up_Down);
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("_");
Console.ForegroundColor = ConsoleColor.White;
if (char_Move_Left_Right == 14)
{
if (char_Move_Up_Down == 8)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.SetCursorPosition(15, 8);
Console.WriteLine(text);
Console.Read();
}
Console.ForegroundColor = ConsoleColor.White;
}
}
if (char_Move_Left_Right == 29)
{
if (char_Move_Up_Down == 8)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.SetCursorPosition(30,8);
Console.WriteLine("Outlaw");
Console.Read();
}
Console.ForegroundColor = ConsoleColor.White;
}
if (char_Move_Left_Right == 44)
{
if (char_Move_Up_Down == 8)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.SetCursorPosition(45, 8);
Console.WriteLine("Paladin");
Console.ReadLine();
}
Console.ForegroundColor = ConsoleColor.White;
}
break;
case ConsoleKey.LeftArrow:
if (char_Move_Left_Right > 1)
{
char_Move_Left_Right--;
Console.SetCursorPosition(char_Move_Left_Right, char_Move_Up_Down);
Console.WriteLine("_");
Console.SetCursorPosition(char_Move_Left_Right + 1, char_Move_Up_Down);
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("_");
Console.ForegroundColor = ConsoleColor.White;
}
else { }
break;
case ConsoleKey.UpArrow:
if (char_Move_Up_Down > 3)
{
char_Move_Up_Down--;
Console.SetCursorPosition(char_Move_Left_Right, char_Move_Up_Down);
Console.WriteLine("_");
Console.SetCursorPosition(char_Move_Left_Right, char_Move_Up_Down + 1);
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("_");
Console.ForegroundColor = ConsoleColor.White;
}
else { }
break;
case ConsoleKey.DownArrow:
if (char_Move_Up_Down < 21)
{
char_Move_Up_Down++;
Console.SetCursorPosition(char_Move_Left_Right, char_Move_Up_Down);
Console.WriteLine("_");
Console.SetCursorPosition(char_Move_Left_Right, char_Move_Up_Down - 1);
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("_");
Console.ForegroundColor = ConsoleColor.White;
}
else { }
break;
}
}while (Error == 0);
}
}
}
Instead of writing every combination by hand, here is what I would do: Use a helper class for common tasks like these kind of multiple-choice actions, pass a set of options and wait for the user to make a selection.
public class ConsoleHelper
{
public static int MultipleChoice(bool canCancel, params string[] options)
{
const int startX = 15;
const int startY = 8;
const int optionsPerLine = 3;
const int spacingPerLine = 14;
int currentSelection = 0;
ConsoleKey key;
Console.CursorVisible = false;
do
{
Console.Clear();
for (int i = 0; i < options.Length; i++)
{
Console.SetCursorPosition(startX + (i % optionsPerLine) * spacingPerLine, startY + i / optionsPerLine);
if(i == currentSelection)
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(options[i]);
Console.ResetColor();
}
key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.LeftArrow:
{
if (currentSelection % optionsPerLine > 0)
currentSelection--;
break;
}
case ConsoleKey.RightArrow:
{
if (currentSelection % optionsPerLine < optionsPerLine - 1)
currentSelection++;
break;
}
case ConsoleKey.UpArrow:
{
if (currentSelection >= optionsPerLine)
currentSelection -= optionsPerLine;
break;
}
case ConsoleKey.DownArrow:
{
if (currentSelection + optionsPerLine < options.Length)
currentSelection += optionsPerLine;
break;
}
case ConsoleKey.Escape:
{
if (canCancel)
return -1;
break;
}
}
} while (key != ConsoleKey.Enter);
Console.CursorVisible = true;
return currentSelection;
}
}
The one above for example can be used like this:
int selectedClass = ConsoleHelper.MultipleChoice(true, "Warrior", "Bard", "Mage", "Archer",
"Thief", "Assassin", "Cleric", "Paladin", "etc.");
selectedClass will simply be the index of the selected option when the function returns (or -1 if the user pressed escape). You might want to add additional parameters like a banner text ("Select class") or formatting options.
Should look something like this:
You can of course add additional marks like _these_ or > those < to further highlight the current selection.
I am just in my early days of learning C# and I got the task to build a "Tik Tak Toe" - game via console application; but I have a huge problem seeing mistakes in my code: when I enter a line and a column, the program will just print the pawn and color from the first player. And somehow my second problem is, that when it comes to the next player, the console won't save the current game stats and will draw a new field.
What did I code wrong?
namespace Tik_Tak_Toe_
{
class Program
{
static int[,] field = new int[3, 3];
static Player[] p;
static int i;
static bool gamerunning = true;
static Random rnd = new Random();
static int currentplayer = 0;
static int column;
static int line;
static int playercolumn = 7;
static int playerline = 7;
static void Main(string[] args)
{
INITIALIZE();
Console.Clear();
DrawField();
currentplayer = rnd.Next(1, 2);
while (gamerunning==true)
{
UPDATE();
}
Console.ReadLine();
}
static void INITIALIZE()
{
playerconfiguration();
DrawField();
}
static void playerconfiguration()
{
p = new Player[2];
for (i = 0; i <= 1; i++)
{
Console.WriteLine("Player " + (i + 1) + ", enter your name!");
p[i].name = Console.ReadLine();
Console.WriteLine(p[i].name + ", choose a color: ");
ColorConfiguration();
Console.WriteLine("... and your symbol example: X or O: ");
p[i].pawn = Console.ReadKey().KeyChar;
Console.WriteLine();
}
}
static void ColorConfiguration()
{
Console.WriteLine("Type one of the following colors: blue, pink, yellow, white, red oder darkblue");
bool whatcolorinput = true;
while (whatcolorinput == true)
{
string whatcolor = Console.ReadLine();
switch (whatcolor)
{
case "blue":
p[i].color = ConsoleColor.Cyan;
whatcolorinput = false;
break;
case "pink":
p[i].color = ConsoleColor.Magenta;
whatcolorinput = false;
break;
case "yellow":
p[i].color = ConsoleColor.Yellow;
whatcolorinput = false;
break;
case "white":
p[i].color = ConsoleColor.White;
whatcolorinput = false;
break;
case "red":
p[i].color = ConsoleColor.Red;
whatcolorinput = false;
break;
case "darkblue":
p[i].color = ConsoleColor.DarkCyan;
whatcolorinput = false;
break;
default:
Console.WriteLine("Type one of the following colors: blue, pink, yellow, white, red oder darkblue");
break;
}
}
}
static void UPDATE()
{
DrawField();
Console.WriteLine(p[currentplayer].name + ", it's your turn!");
PlayerInput();
UpdateField();
currentplayer = (currentplayer + 1) % 2;
}
static void DrawField()
{
for ( column=0; column<field.GetLength(1); column++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((column+1) + "|");
Console.ResetColor();
for ( line=0; line<field.GetLength(0); line++)
{
if (field[column,line]==0 && (column != playercolumn || line != playerline))
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[playercolumn, playerline]].color;
Console.Write(" " + p[field[playercolumn, playerline]].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
static void PlayerInput()
{
Console.WriteLine("First, choose a column: ");
bool columninput = true;
while (columninput == true)
{
try
{
playercolumn = Convert.ToInt32(Console.ReadLine());
if (column < 1 || column > 3)
{
Console.WriteLine("Choose a column.");
}
else
{
columninput = false;
}
}
catch
{
Console.WriteLine("Choose a column.");
}
}
playercolumn -= 1;
Console.WriteLine("... and now a line");
bool lineinput = true;
while (lineinput == true)
{
try
{
playerline = Convert.ToInt32(Console.ReadLine());
if (line < 1 || line > 3)
{
Console.WriteLine("Choose a line.");
}
else
{
lineinput = false;
}
}
catch
{
Console.WriteLine("Choose a line.");
}
}
playerline -= 1;
}
static void UpdateField()
{
}
static void FINISH()
{
}
}
}
You just have just global variables to store playercolumn and playerline.
Each time you execute PlayerInputyou will replace the values this variables had.
You will need a 3x3 matrix to store the player choices, then print this matrix as a board. Id a column and row was already chosen, you need to refuse the user input.
Looks like you want to store user moves in field global variable, but you're not assigning that anywhere.
I modified the code, in update, repeat the PlayerInput until a its valid for update:
do
{
PlayerInput();
} while (!UpdateField());
In DrawField check onli for values in field variable, not the player input
static void DrawField()
{
for (column = 0; column < field.GetLength(1); column++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((column + 1) + "|");
Console.ResetColor();
for (line = 0; line < field.GetLength(0); line++)
{
if (field[column, line] == 0)
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[column, line] - 1].color;
Console.Write(" " + p[field[column, line] - 1].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
And implemented the UpdateField:
static bool UpdateField()
{
if (field[playercolumn, playerline] != 0)
{
Console.WriteLine("Column already chosen");
return false;
}
field[playercolumn, playerline] = currentplayer + 1;
return true;
}
It still need to check when the game finish.
You've got a lot of problems in your code. First of all, you was never storing the player input in the field array, so obviously when you were redrawing the table, only the last input was drawn. You were also exchanging some variables as line and playerline. After solving this problems and some minor ones and adding a Player class (i hope it is more or less like this as you don't provided it) , the code that correctly draws the board is more or less this:
class Program
{
static int[,] field = new int[3, 3];
static Player[] p;
static int i;
static bool gamerunning = true;
static Random rnd = new Random();
static int currentplayer = 0;
static int playercolumn = 7;
static int playerline = 7;
static void Main(string[] args)
{
INITIALIZE();
Console.Clear();
DrawField();
currentplayer = rnd.Next(1, 2);
while (gamerunning == true)
{
UPDATE();
}
Console.ReadLine();
}
public class Player
{
public string name { get; set; }
public char pawn { get; set; }
public ConsoleColor color { get; set;}
}
static void INITIALIZE()
{
playerconfiguration();
DrawField();
}
static void playerconfiguration()
{
p = new Player[2];
for (i = 0; i <= 1; i++)
{
p[i] = new Player();
Console.WriteLine("Spieler " + (i + 1) + ", gib deinen Namen ein!");
p[i].name = Console.ReadLine();
Console.WriteLine(p[i].name + ", wähle deine Farbe: ");
ColorConfiguration();
Console.WriteLine("... und nun dein Symbol z.B. X oder O: ");
p[i].pawn = Console.ReadKey().KeyChar;
Console.WriteLine();
}
}
static void ColorConfiguration()
{
Console.WriteLine("Gib eine der folgenden Farben ein: blau, pink, gelb, weiss, rot oder dunkelblau");
bool whatcolorinput = true;
while (whatcolorinput == true)
{
string whatcolor = Console.ReadLine();
switch (whatcolor)
{
case "blau":
p[i].color = ConsoleColor.Cyan;
whatcolorinput = false;
break;
case "pink":
p[i].color = ConsoleColor.Magenta;
whatcolorinput = false;
break;
case "gelb":
p[i].color = ConsoleColor.Yellow;
whatcolorinput = false;
break;
case "weiss":
p[i].color = ConsoleColor.White;
whatcolorinput = false;
break;
case "rot":
p[i].color = ConsoleColor.Red;
whatcolorinput = false;
break;
case "dunkelblau":
p[i].color = ConsoleColor.DarkCyan;
whatcolorinput = false;
break;
default:
Console.WriteLine("Gib eine der folgenden Farben ein: blau, pink, gelb, weiss, rot oder dunkelblau");
break;
}
}
}
static void UPDATE()
{
DrawField();
Console.WriteLine(p[currentplayer].name + ", du bist dran!");
PlayerInput();
UpdateField();
currentplayer = (currentplayer + 1) % 2;
}
static void DrawField()
{
for (int line = 0; line < field.GetLength(1); line++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((line + 1) + "|");
Console.ResetColor();
for (int column = 0; column < field.GetLength(0); column++)
{
if (field[line, column] == 0)
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[line, column]-1].color;
Console.Write(" " + p[field[line, column] -1].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
static void PlayerInput()
{
Console.WriteLine("Wähle zuerst eine Spalte: ");
bool lineinput = true;
while (lineinput == true)
{
try
{
playerline = Convert.ToInt32(Console.ReadLine());
if (playerline < 1 || playerline > 3)
{
Console.WriteLine("Wähle eine Spalte.");
}
else
{
lineinput = false;
}
}
catch
{
Console.WriteLine("Wähle eine Spalte.");
}
}
bool columninput = true;
while (columninput == true)
{
try
{
playercolumn = Convert.ToInt32(Console.ReadLine());
if (playercolumn < 1 || playercolumn > 3)
{
Console.WriteLine("Wähle eine Zeile.");
}
else
{
columninput = false;
}
}
catch
{
Console.WriteLine("Wähle eine Zeile.");
}
}
playercolumn -= 1;
Console.WriteLine("... und nun eine Spalte");
//field[line-1, column] = new int();
playerline -= 1;
field[playerline, playercolumn] = currentplayer+1;
}
static void UpdateField()
{
}
static void FINISH()
{
}
}
Study this code and compare it with yours to see what were your mistakes. Of course, you must still check if a position is alreay taken,when one player has won and when there are no moves left and the result of the game is a draw.
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");