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.
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 making a os with Cosmos and working in a text editor
I copied the code from LiquidEditor but it does not seem to work very well with lines, so I tried to inplement a little line system, but it gives me an error: Enum.ToString() is not implemented.
Kernel code:
using System;
using System.Collections.Generic;
using System.Text;
using Sys = Cosmos.System;
using Filesystem = Cosmos.System.FileSystem.CosmosVFS;
using VFSFilesystem = Cosmos.System.FileSystem.VFS.VFSManager;
namespace LDCM
{
public class Kernel : Sys.Kernel
{
Filesystem filesystem = new Filesystem();
protected override void BeforeRun()
{
Console.Clear();
VFSFilesystem.RegisterVFS(filesystem, false);
}
protected override void Run()
{
LiquidEditor.Start(#"0:\");
Console.WriteLine(System.IO.File.ReadAllText(#"0:\0.txt"));
Console.ReadKey(true);
}
}
}
LiquidEditor code:
using System;
using System.Collections.Generic;
using System.Text;
namespace LDCM
{
public class LiquidEditor
{
public static String version = "0.2";
public static Char[] line = new Char[80]; public static int pointer = 0;
public static List<String> lines = new List<String>();
public static String[] final;
public static void Start(String currentdirectory)
{
Console.Clear();
Utils.WriteTextCentered("Liquid Editor by TheCool1James & valentinbreiz");
Utils.WriteTextCentered("Version " + version);
Console.Write("Filename: ");
String filename = Console.ReadLine();
Start(filename, currentdirectory);
}
public static void Start(String filename, String currentdirectory)
{
if (System.IO.File.Exists(currentdirectory + filename))
{
Console.Clear();
drawTopBar();
Console.SetCursorPosition(0, 1);
ConsoleKeyInfo c; cleanArray(line);
List<String> text = new List<String>();
text.Add(System.IO.File.ReadAllText(currentdirectory + filename));
String file = "";
foreach (String value in text)
{
file = file + value;
}
Console.Write(file);
while ((c = Console.ReadKey(true)) != null)
{
drawTopBar();
Char ch = c.KeyChar;
if (c.Key == ConsoleKey.Escape)
break;
else if (c.Key == ConsoleKey.F1)
{
Console.Clear();
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
Utils.WriteTextCentered("Liquid Editor by TheCool1James & valentinbreiz");
Utils.WriteTextCentered("Version " + version);
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
lines.Add(new String(line).TrimEnd());
final = lines.ToArray();
String foo = Utils.ConcatString(final);
System.IO.File.Create(currentdirectory + filename);
System.IO.File.WriteAllText(currentdirectory + filename, file + foo);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("'" + filename + "' has been saved in '" + currentdirectory + "' !");
Console.ForegroundColor = ConsoleColor.White;
Console.ReadKey();
break;
}
else if (c.Key == ConsoleKey.F2)
{
Start(currentdirectory);
break;
}
switch (c.Key)
{
case ConsoleKey.Home: break;
case ConsoleKey.PageUp: break;
case ConsoleKey.PageDown: break;
case ConsoleKey.End: break;
case ConsoleKey.UpArrow:
if (Console.CursorTop > 1)
{
Console.CursorTop = Console.CursorTop - 1;
}
break;
case ConsoleKey.DownArrow:
if (Console.CursorTop < 24)
{
Console.CursorTop = Console.CursorTop + 1;
}
break;
case ConsoleKey.LeftArrow: if (pointer > 0) { pointer--; Console.CursorLeft--; } break;
case ConsoleKey.RightArrow: if (pointer < 80) { pointer++; Console.CursorLeft++; if (line[pointer] == 0) line[pointer] = ' '; } break;
case ConsoleKey.Backspace: deleteChar(); break;
case ConsoleKey.Delete: deleteChar(); break;
case ConsoleKey.Enter:
lines.Add(new String(line).TrimEnd()); cleanArray(line); Console.CursorLeft = 0; Console.CursorTop++; pointer = 0;
break;
default: line[pointer] = ch; pointer++; Console.Write(ch); break;
}
}
Console.Clear();
}
else
{
Console.Clear();
drawTopBar();
Console.SetCursorPosition(0, 1);
ConsoleKeyInfo c; cleanArray(line);
while ((c = Console.ReadKey(true)) != null)
{
drawTopBar();
Char ch = c.KeyChar;
if (c.Key == ConsoleKey.Escape)
break;
else if (c.Key == ConsoleKey.F1)
{
Console.Clear();
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
Utils.WriteTextCentered("Liquid Editor by TheCool1James & valentinbreiz");
Utils.WriteTextCentered("Version " + version);
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
lines.Add(new String(line).TrimEnd());
final = lines.ToArray();
String foo = Utils.ConcatString(final);
System.IO.File.Create(currentdirectory + filename);
System.IO.File.WriteAllText(currentdirectory + filename, foo);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("'" + filename + "' has been saved in '" + currentdirectory + "' !");
Console.ForegroundColor = ConsoleColor.White;
Console.ReadKey();
break;
}
else if (c.Key == ConsoleKey.F2)
{
Start(currentdirectory);
break;
}
switch (c.Key)
{
case ConsoleKey.Home: break;
case ConsoleKey.PageUp: break;
case ConsoleKey.PageDown: break;
case ConsoleKey.End: break;
case ConsoleKey.UpArrow:
if (Console.CursorTop > 1)
{
Console.CursorTop = Console.CursorTop - 1;
}
break;
case ConsoleKey.DownArrow:
if (Console.CursorTop < 23)
{
Console.CursorTop = Console.CursorTop + 1;
}
break;
case ConsoleKey.LeftArrow: if (pointer > 0) { pointer--; Console.CursorLeft--; } break;
case ConsoleKey.RightArrow: if (pointer < 80) { pointer++; Console.CursorLeft++; if (line[pointer] == 0) line[pointer] = ' '; } break;
case ConsoleKey.Backspace: deleteChar(); break;
case ConsoleKey.Delete: deleteChar(); break;
case ConsoleKey.Enter:
lines.Add(new String(line).TrimEnd()); cleanArray(line); Console.CursorLeft = 0; Console.CursorTop++; pointer = 0;
break;
default: line[pointer] = ch; pointer++; Console.Write(ch); break;
}
}
Console.Clear();
}
}
public static void cleanArray(Char[] c)
{
for (int i = 0; i < c.Length; i++)
c[i] = ' ';
}
public static void drawTopBar()
{
int x = Console.CursorLeft, y = Console.CursorTop;
Console.SetCursorPosition(0, 0);
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
Console.Write("Liquid Editor v" + version + " ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("[F1]Save [F2]New [ESC]Exit\n");
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
Console.SetCursorPosition(x, y);
}
public static void deleteChar()
{
if ((Console.CursorLeft >= 1) && (pointer >= 1))
{
pointer--;
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
line[pointer] = ' ';
}
else if ((Console.CursorTop >= 2))
{
Console.CursorTop--;
Console.Write(new String(' ', lines[lines.Count - 1].Length - 1));
Console.CursorTop--;
lines.RemoveAt(lines.Count - 1);
line = lines[lines.Count - 1].ToCharArray();
}
}
public static void listCheck()
{
foreach (var s in lines)
Console.WriteLine(" List: " + s + "\n");
}
private String[] arrayCheck(String[] s)
{
foreach (var ss in s)
{
Console.WriteLine(" Line: " + ss + "\n");
}
return s;
}
}
}
Utils code:
using System;
using System.Collections.Generic;
using System.Text;
namespace LDCM
{
public static class Utils
{
public static void WriteTextCentered(String content)
{
Console.Write(new string(' ', (Console.WindowWidth - content.Length - 2) / 2));
Console.WriteLine(content);
}
public static String ConcatString(String[] s)
{
String t = "";
if (s.Length >= 1)
{
for (int i = 0; i < s.Length; i++)
{
if (!String.IsNullOrWhiteSpace(s[i]))
t = String.Concat(t, s[i].TrimEnd(), Environment.NewLine);
}
}
else
t = s[0];
t = String.Concat(t, '\0');
return t;
}
}
}
The code you mentioned works fine on my environment in this way:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
List<String> lines = new List<String>();
Char[] line = new Char[80];
lines.Add("Giorgi");
lines.Add("Davut");
Console.Write(new String('_', lines[lines.Count - 1].Length - 1));
lines.RemoveAt(lines.Count - 1);
line = lines[lines.Count - 1].ToCharArray();
}
}
}
I couldn't post this in comments to check if it is valued or not, but let me know if it is improveable.
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.
Ok for my program I am trying to get it so that when I have a Key press on my program and say I Press L and it moves in the 4x4 2d array and I get to pit which I designated as P on the array I want it to know it hit the P and print out you have a hit a Pit or if I reach where it has G on the array I want it to print out you have found gold. Any help is appreciated.
using System;
namespace DragonCave
{
public struct DragonPlayer
{
public int X, Y;
public string CurrentMove;
}
public class DragonGameboard
{
public string[,] GameboardArray;
public DragonPlayer Player;
private Random r;
public DragonGameboard(){
GameboardArray = new string[4,4];
Player.CurrentMove = "";
r = new Random();
Player.X = r.Next(0, 4);
Player.Y = r.Next(0, 4);
GenerateRandomBoard();
}
private void GenerateRandomBoard()
{
//Put a dot in every spot
int row;
int col;
for (row = 0; row < 4; row++)
{
for (col = 0; col < 4; col++)
{
Console.Write(GameboardArray[row, col] = ".");
}
//Console.WriteLine();
}
//Randomly Places the entrance, dragon, pit and gold.
GameboardArray[r.Next(0,4), r.Next(0, 4)] = "E";
GameboardArray[r.Next(0,4), r.Next(0,4)] = "D";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "G";
}
public void PrintBoard()
{
int row;
int col;
for (row = 0; row < 4; row++)
{
for (col = 0; col < 4; col++)
{
Console.Write(GameboardArray[row, col] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("Cheat you are in" + Player.X + "," + Player.Y);
//fill with room numbers
}
public void ProcessMove(string move)
{
switch (move)
{
case "F":
Console.WriteLine("You chose forward");
break;
case "L":
Player.X--;
Player.Y--;
//Console.WriteLine("You chose Left");
Console.WriteLine("A Breeze is in the air");
break;
case "R":
Player.X++;
Player.Y++;
if (GameboardArray)
Console.WriteLine("You chose Right");
break;
case "G":
Console.WriteLine("You chose Grab gold");
break;
case "S":
Console.WriteLine("You chose Shoot arrow");
break;
case "C":
Console.WriteLine("You chose Climb");
break;
case "Q":
Console.WriteLine("You chose Quit");
break;
case "X":
Console.WriteLine("You chose Cheat");
PrintBoard();
break;
default:
Console.WriteLine("Invalid move!!!!!!!!!!1");
break;
}
}
}
Just check what the string is at GameboardArray[player.x, player.y].
public void ProcessTileEvent()
{
if( Player.X >= 0 && Player.X < 4 && Player.Y >= 0 && Player.Y < 4 )
{
switch( GameboardArray[Player.X, Player.Y] )
{
case "G":
Console.WriteLine( "You found gold!" );
break;
case "P":
Console.WriteLine( "You fell in a pit!" );
break;
}
}
}
You'd probably want to do this every time the player moves.
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]);
}
}