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.
Related
Guys I've been stuck for hours right now,
any help is appreciated.
I am currently building a console app to input a list on the number 1 option
and then present it on the number 2 option
My problem is the console doesn't seem to read my input specifically on this part here
Console.Write("Masukkan Judul".PadRight(24) + ": ");
list[list.GetUpperBound(0)].Judul = Console.ReadLine();
I'm not sure what part should i post , so i copied all my code here
Thanks for your time
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp2
{
class Class1
{
enum Kategori
{
Textbook = 1, Kamus, Novel, Majalah
}
enum Penerbit
{
Gramedia = 1, Kompas, Tribun, Erlangga, Grasindo
}
struct Alas
{
public Kategori Kategori;
public Penerbit Penerbit;
public string Judul;
public double Harga;
public double Diskon;
public double Subtotal;
}
static void Main(string[] args)
{
Alas[] list = new Alas[0];
int pilih,jlhbuku,pil1,pil2 ;
double Total = 0;
Kategori Buku;
Penerbit Editor;
Ulang:
Console.Clear();
Console.Title= "Buku";
Console.WriteLine(new string(' ', 18)+"MENU");
Console.WriteLine(new string('=', 40));
Console.WriteLine("1. Input Data");
Console.WriteLine("2. Tampil Data");
Console.WriteLine("3. Keluar");
Console.WriteLine(new string('=', 40));
Console.Write("Masukkan Kode [1-3] : ");
pilih = int.Parse(Console.ReadLine());
if (pilih ==1)
{
Array.Resize(ref list, list.Count() + 1);
Console.Clear();
Console.WriteLine(new string('=', 40));
Console.WriteLine(new string(' ', 15) + "INPUT DATA");
Console.WriteLine(new string('=', 40));
Console.Write("Masukkan jumlah buku : ");
jlhbuku = int.Parse(Console.ReadLine());
Array.Resize(ref list, list.Count() + jlhbuku);
for (int i = 1; i <= list.GetUpperBound(0); i++)
{
Console.WriteLine("\nKategori Buku:");
Console.WriteLine("1. Textbook");
Console.WriteLine("2. Kamus");
Console.WriteLine("3. Novel");
Console.WriteLine("4. Majalah");
Console.Write("Masukkan Kategori [1-4] : ");
pil1 = int.Parse(Console.ReadLine());
Buku = (Kategori)pil1;
if (pil1 == 1)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Textbook;
}
if (pil1 == 2)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Kamus;
}
if (pil1 == 3)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Novel;
}
if (pil1 == 4)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Majalah;
}
Console.WriteLine("\nPenerbit:");
Console.WriteLine("1. Gramedia");
Console.WriteLine("2. Kompas");
Console.WriteLine("3. Tribun");
Console.WriteLine("4. Erlangga");
Console.WriteLine("5. Grasindo");
Console.Write("Masukkan Penerbit [1-5] : ");
pil2 = int.Parse(Console.ReadLine());
Editor = (Penerbit)pil2;
if (pil1 == 1)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Gramedia;
}
if (pil1 == 2)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Kompas;
}
if (pil1 == 3)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Tribun;
}
if (pil1 == 4)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Erlangga;
}
if (pil1 == 5)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Grasindo;
}
**Console.Write("Masukkan Judul".PadRight(24) + ": ");
list[list.GetUpperBound(0)].Judul = Console.ReadLine();**
Console.Write("Masukkan Harga".PadRight(24) + ": ");
list[list.GetUpperBound(0)].Harga = double.Parse(Console.ReadLine());
Buku = (Kategori)list[list.GetUpperBound(0)].Kategori;
Editor = (Penerbit)list[list.GetUpperBound(0)].Penerbit;
list[list.GetUpperBound(0)].Diskon = 0.1* list[list.GetUpperBound(0)].Harga;
list[list.GetUpperBound(0)].Subtotal = list[list.GetUpperBound(0)].Harga - list[list.GetUpperBound(0)].Diskon;
}
goto Ulang;
}
if (pilih == 2)
{
if (list.Count() == 0)
{
Console.WriteLine("Belum ada pesanan.");
Console.ReadKey();
goto Ulang;
}
else
{
DateTime Date = DateTime.Now;
Console.Clear();
Console.Write("Tanggal : "+ (Date.ToString(" dd-MMMM-yyyy", new System.Globalization.CultureInfo("id-ID"))));
Console.WriteLine();
Console.WriteLine(new string('=', 80));
Console.WriteLine("Kategori".PadRight(10) +"Penerbit".PadRight(10) +"Judul".PadRight(15) + "Harga".PadRight(15) + "Diskon".PadRight(15) + "Subtotal");
Console.WriteLine(new string('=', 80));
for (int i = 0; i < list.GetUpperBound(0); i++)
{
Console.WriteLine(list[i].Kategori.ToString().PadRight(10) + list[i].Penerbit.ToString().PadRight(10) + list[i].Judul.ToString().PadRight(15) + list[i].Harga.ToString().PadRight(15) + list[i].Diskon.ToString("N2").PadRight(15) + list[i].Subtotal.ToString());
Total += list[i].Subtotal;
}
Console.WriteLine(new string('=', 80));
Console.Write(new string(' ', 57)+"Total : " + Total.ToString("Rp #.###,00"));
Console.ReadKey();
goto Ulang;
}
}
if (pilih == 3)
{
Environment.Exit(0);
}
else
{
Console.WriteLine("Kode tidak valid.");
Console.ReadKey();
goto Ulang;
}
Console.ReadKey();
}
}
}
When you fill your data, you do this:
for (int i = 1; i <= list.GetUpperBound(0); i++)
But when you print your data, you do this:
for (int i = 0; i < list.GetUpperBound(0); i++)
Hence, you try to print list[0], which does not have any data. Therefore, you get a NullReferenceException when accessing the string variable.
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.
so as the title says my C# code is not running/debugging even though i have 0 errors being shown.
I begin the debugging and all that happens is the console screen flashes quickly then exits with 0 errors. Even the .exe in the bin\debug folder does the exact same. All i'm receiving is a wall of text in the output section.
Algorithms.vshost.exe' (CLR v4.0.30319: Algorithms.vshost.exe): Loaded C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll. Symbols loaded.
The thread 0x12b8 has exited with code 0 (0x0).
The thread 0x289c has exited with code 0 (0x0).
The program [15012] Algorithms.vshost.exe has exited with code 0 (0x0).
I hope this is understandable enough! I would appreciate any help, thanks!
Code as requested by some! I hope it's helpful! I appreciate all the answers and help so far!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmsResit
{
class Program
{
private static void Main(string[] args)
{ }
public static void AlgorithmSortInt(int[] array)
{
int j = array.Length - 1;
int x, i, temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[1 + 1] = temp;
}
}
public static void AlgorithmSortDouble(double[] array)
{
int j = array.Length - 1;
int x, i;
double temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[i + 1] = temp;
}
}
public static void AlgorithmDateTime(DateTime[] array)
{
int j = array.Length - 1;
int x, i;
DateTime temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[i + 1] = temp;
}
}
public static void StringToSort(string[] array)
{
int x = array.Length - 1;
for (int j = 0; j < x; j++)
{
for (int i = x; i > j; i--)
{
if (((IComparable)array[i - 1]).CompareTo(array[i]) > 0)
{
var temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
}
}
}
}
static void main(string[] args)
{
string[] Day1 = System.IO.File.ReadAllLines(#"TextFiles/Day_1.txt");
List<int> Day1List = new List<int>();
foreach (string Day in Day1)
{
int Days = Convert.ToInt32(Day);
Day1List.Add(Days);
}
int[] Day1Arr = Day1List.ToArray();
string[] Depth1 = System.IO.File.ReadAllLines(#"TextFiles/Depth_1.txt");
List<double> Depth1List = new List<double>();
foreach (string Depth in Depth1)
{
double Depths = Convert.ToDouble(Depth);
Depth1List.Add(Depths);
}
double[] Depth1Arr = Depth1List.ToArray();
string[] IRISID1 = System.IO.File.ReadAllLines(#"TextFiles/IRIS_ID_1.txt");
List<int> Iris1List = new List<int>();
foreach (string IRIS in IRISID1)
{
int Iris = Convert.ToInt32(IRIS);
Iris1List.Add(Iris);
}
int[] Iris1Arr = Iris1List.ToArray();
string[] Latitude1 = System.IO.File.ReadAllLines(#"TextFiles/Latitude_1.txt");
List<double> Latitude1List = new List<double>();
foreach (string Lat in Latitude1)
{
double Latitude = Convert.ToDouble(Latitude1);
Latitude1List.Add(Latitude);
}
double[] Latitude1Arr = Latitude1List.ToArray();
string[] Longitude1 = System.IO.File.ReadAllLines(#"TextFiles/Longitude_1.txt");
List<double> Longitude1List = new List<double>();
foreach (string Longitude in Longitude1)
{
double Longitudes = Convert.ToDouble(Longitude1);
Longitude1List.Add(Longitudes);
}
double[] Longitude1Arr = Longitude1List.ToArray();
string[] Magnitude1 = System.IO.File.ReadAllLines(#"TextFiles/Magnitude_1.txt");
List<Double> Magnitude1List = new List<Double>();
foreach (string Magnitude in Magnitude1)
{
double Magnitudes = Convert.ToDouble(Magnitude1);
Magnitude1List.Add(Magnitudes);
}
double[] Magnitude1Arr = Magnitude1List.ToArray();
string[] Month1 = System.IO.File.ReadAllLines(#"TextFiles/Month_1.txt");
string[] Region1 = System.IO.File.ReadAllLines(#"TextFiles/Region_1.txt");
string[] Time1 = System.IO.File.ReadAllLines(#"TextFiles/Time_1.txt");
List<DateTime> Time1List = new List<DateTime>();
foreach (string Time in Time1)
{
DateTime Times = Convert.ToDateTime(Time);
Time1List.Add(Times);
}
DateTime[] Time1Arr = Time1List.ToArray();
string[] Timestamp1 = System.IO.File.ReadAllLines(#"TextFiles/Timestamp_1.txt");
List<int> Timestamp1List = new List<int>();
foreach (string Timestamp in Timestamp1)
{
int Timestamps = Convert.ToInt32(Timestamp);
Timestamp1List.Add(Timestamps);
}
int[] Timestamp1Arr = Timestamp1List.ToArray();
string[] Year1 = System.IO.File.ReadAllLines(#"TextFiles/Year_1.txt");
List<int> Year1List = new List<int>();
foreach (String Date in Year1)
{
int Dates = Convert.ToInt32(Date);
Year1List.Add(Dates);
}
int[] Year1Arr = Year1List.ToArray();
string UserArrayChoice, AscOrDescChoice;
int ArrayChoice;
int count = 0;
do
{
count++;
Console.Write("{0} ", Day1Arr[count]);
Console.Write("{0} ", Depth1[count]);
Console.Write("{0} ", IRISID1[count]);
Console.Write("{0} ", Latitude1Arr[count]);
Console.Write("{0} ", Longitude1Arr[count]);
Console.Write("{0} ", Magnitude1Arr[count]);
Console.Write("{0} ", Month1[count]);
Console.Write("{0} ", Region1[count]);
Console.Write("{0} ", Time1Arr[count]);
Console.Write("{0} ", Timestamp1Arr[count]);
Console.Write("{0}", Year1Arr[count]);
Console.Write("\n");
} while (count < Year1Arr.Length - 1);
Console.WriteLine("Enter the number of the file you would like to sort... \n1 ) Day_1.txt\n2 ) Depth_1.txt\n3 ) IRIS_ID_.txt\n4 ) Latitude_1.txt\n5 ) Longitude_1.txt\n6 ) Magnitude_1.txt\n7 ) Month_1.txt\n8 ) Region_1.txt\n9 ) Time_1.txt\n10 ) Timestamp_1.txt\n11 ) Year_1.txt\n12");
UserArrayChoice = Console.ReadLine();
ArrayChoice = Convert.ToInt32(UserArrayChoice);
switch (UserArrayChoice)
{
case "1":
UserArrayChoice = "Day_1.txt";
break;
case "2":
UserArrayChoice = "Depth_1.txt";
break;
case "3":
UserArrayChoice = "IRIS_ID_1.txt";
break;
case "4":
UserArrayChoice = "Latitude_1.txt";
break;
case "5":
UserArrayChoice = "Longitude_1.txt";
break;
case "6":
UserArrayChoice = "Magnitude_1.txt";
break;
case "7":
UserArrayChoice = "Month_1.txt";
break;
case "8":
UserArrayChoice = "Region_1.txt";
break;
case "9":
UserArrayChoice = "Time_1.txt";
break;
case "10":
UserArrayChoice = "Timestamp_1.txt";
break;
case "11":
UserArrayChoice = "Year_1.txt";
break;
default:
break;
}
Console.WriteLine("---------------------------------------------------------------------------");
Console.WriteLine("{0} Has been selected, would you like to sort by Ascending or Descending? ", UserArrayChoice);
Console.WriteLine("---------------------------------------------------------------------------");
AscOrDescChoice = Console.ReadLine();
if (AscOrDescChoice == "Ascending" | AscOrDescChoice == "ascending")
{
Console.WriteLine("---------------------------------");
Console.WriteLine("{0} Will sort in Ascending order!", UserArrayChoice);
Console.WriteLine("---------------------------------");
switch (ArrayChoice)
{
case 1:
AlgorithmSortInt(Day1Arr);
foreach (int temp in Day1Arr)
{
Console.WriteLine("{0} ", temp);
}
break;
case 2:
AlgorithmSortDouble(Depth1Arr);
foreach (double temp in Depth1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 3:
AlgorithmSortInt(Iris1Arr);
foreach (int temp in Iris1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 4:
AlgorithmSortDouble(Latitude1Arr);
foreach (double temp in Latitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 5:
AlgorithmSortDouble(Longitude1Arr);
foreach (double temp in Longitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 6:
AlgorithmSortDouble(Magnitude1Arr);
foreach (double temp in Magnitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 7:
StringToSort(Month1);
foreach (string temp in Month1)
{
Console.WriteLine("{0}", temp);
}
break;
case 8:
StringToSort(Region1);
foreach (string temp in Region1)
{
Console.WriteLine("{0}", temp);
}
break;
case 9:
AlgorithmDateTime(Time1Arr);
foreach (DateTime temp in Time1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 10:
AlgorithmSortInt(Timestamp1Arr);
foreach (int temp in Timestamp1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 11:
AlgorithmSortInt(Year1Arr);
foreach (int temp in Year1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
}
}
else if (AscOrDescChoice == "Descending" | AscOrDescChoice == "descending")
{
Console.WriteLine("----------------------------------");
Console.WriteLine("{0} Will sort in Descending order!", UserArrayChoice);
Console.WriteLine("----------------------------------");
switch (ArrayChoice)
{
case 1:
AlgorithmSortInt(Day1Arr);
Array.Reverse(Day1Arr);
foreach (int temp in Day1Arr)
{
Console.WriteLine("{0} ", temp);
}
break;
case 2:
AlgorithmSortDouble(Depth1Arr);
Array.Reverse(Depth1Arr);
foreach (double temp in Depth1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 3:
AlgorithmSortInt(Iris1Arr);
Array.Reverse(Iris1Arr);
foreach (int temp in Iris1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 4:
AlgorithmSortDouble(Latitude1Arr);
Array.Reverse(Latitude1Arr);
foreach (double temp in Latitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 5:
AlgorithmSortDouble(Longitude1Arr);
Array.Reverse(Longitude1Arr);
foreach (double temp in Longitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 6:
AlgorithmSortDouble(Magnitude1Arr);
Array.Reverse(Magnitude1Arr);
foreach (double temp in Magnitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 7:
StringToSort(Month1);
Array.Reverse(Month1);
foreach (string temp in Month1)
{
Console.WriteLine("{0}", temp);
}
break;
case 8:
StringToSort(Region1);
Array.Reverse(Region1);
foreach (string temp in Region1)
{
Console.WriteLine("{0}", temp);
}
break;
case 9:
AlgorithmDateTime(Time1Arr);
Array.Reverse(Time1Arr);
foreach (DateTime temp in Time1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 10:
AlgorithmSortInt(Timestamp1Arr);
Array.Reverse(Timestamp1Arr);
foreach (int temp in Timestamp1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 11:
AlgorithmSortInt(Year1Arr);
Array.Reverse(Year1Arr);
foreach (int temp in Year1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
}
}
else
{
Console.WriteLine("-------------------");
Console.WriteLine("Incorrect Response!");
Console.WriteLine("-------------------");
}
Console.WriteLine("Enter the number of the file you would like to search... \n1 ) Day_1.txt\n2 ) Depth_1.txt\n3 ) IRIS_ID_1\n4 ) Latitude_1\n5 ) Longitude_1\n6 ) Magnitude_1\n7 ) Month_1\n8 ) Region_1\n9 ) Time_1\n10 ) Timestamp_1\n11 ) Year_1\n12");
UserArrayChoice = Console.ReadLine();
ArrayChoice = Convert.ToInt32(UserArrayChoice);
switch (UserArrayChoice)
{
case "1":
UserArrayChoice = "Day_1.txt";
break;
case "2":
UserArrayChoice = "Depth_1.txt";
break;
case "3":
UserArrayChoice = "IRIS_ID_1.txt";
break;
case "4":
UserArrayChoice = "Latitude_1.txt";
break;
case "5":
UserArrayChoice = "Longitude_1.txt";
break;
case "6":
UserArrayChoice = "Magnitude_1.txt";
break;
case "7":
UserArrayChoice = "Month_1.txt";
break;
case "8":
UserArrayChoice = "Region_1.txt";
break;
case "9":
UserArrayChoice = "Time_1.txt";
break;
case "10":
UserArrayChoice = "Timestamp_1.txt";
break;
case "11":
UserArrayChoice = "Year_1.txt";
break;
default:
break;
}
Console.WriteLine("--------------------------------------------------------------------");
Console.WriteLine("{0} has been selected! Please enter what you would like to search - ", UserArrayChoice);
Console.WriteLine("--------------------------------------------------------------------");
string SearchTemp = Console.ReadLine();
bool Found = false;
int counter = 0;
switch (ArrayChoice)
{
case 1:
int SearchDay = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Day1Arr.Length; x++)
{
if (SearchDay == Day1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 2:
double DepthSearch = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Depth1Arr.Length; x++)
{
if (DepthSearch == Depth1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful!:-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 3:
int SearchIris = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Iris1Arr.Length; x++)
{
if (SearchIris == Iris1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 4:
double SearchLatitude = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Latitude1Arr.Length; x++)
{
if (SearchLatitude == Latitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 5:
double SearchLong = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Longitude1Arr.Length; x++)
{
if (SearchLong == Longitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 6:
double SearchMag = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Magnitude1Arr.Length; x++)
{
if (SearchMag == Magnitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 7:
foreach (var Months in Month1)
{
if (Months.Contains(SearchTemp))
{
count++;
Found = true;
Console.Write("{0} ", Day1Arr[counter]);
Console.Write("{0} ", Depth1Arr[counter]);
Console.Write("{0} ", Iris1Arr[counter]);
Console.Write("{0} ", Latitude1Arr[counter]);
Console.Write("{0} ", Longitude1Arr[counter]);
Console.Write("{0} ", Magnitude1Arr[counter]);
Console.Write("{0} ", Month1[counter]);
Console.Write("{0} ", Region1[counter]);
Console.Write("{0} ", Time1Arr[counter]);
Console.Write("{0} ", Timestamp1Arr[counter]);
Console.Write("{0} ", Year1Arr[counter]);
Console.Write("\n");
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 8:
foreach (var Regions in Region1)
{
if (Regions.Contains(SearchTemp))
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 9:
DateTime SearchDate = Convert.ToDateTime(SearchTemp);
for (int x = 0; x < Time1Arr.Length; x++)
{
if (SearchDate == Time1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 10:
int SearchTimestamp = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Timestamp1Arr.Length; x++)
{
if (SearchTimestamp == Timestamp1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 11:
int SearchYear = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Year1Arr.Length; x++)
{
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
}
}
}
}
What I know that it is just debugging message. You can switch that off by right clicking into the output window and uncheck the thread ended message.
http://msdn.microsoft.com/en-us/library/bs4c1wda.aspx
(1)Please add a breakpoint in your app, and then debug it again.
Like this thread:
Keeping console window open when debugging.
(2)If you run it with “start without debugging”, it would not be closed. You could also add Console.ReadLine()in your app like this thread.
(3)If you just debug your app and get this messages, please also enable the Exceptions settings under Debugger->Windows menu, and make sure that no Exception.
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.
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]);
}
}