porkshopp
Active member
I have this program in which I want to move around in a grid of the players choosing. When moving from the first position of the last row it gives me an error message since the value is outside of the size of the array, I have no idea how to fix it. And also, how can I make it move automatically when I have pressed a button, so I don't have to press enter between for the press to register?
C#:
using System;
namespace ConsoleApp2
{
class Program
{
static void Print(int[] board, int Pos, int rGrid)
{
Console.ForegroundColor = ConsoleColor.Yellow;
int i = 0;
while (i < (rGrid*rGrid))
{
board[Pos] = 5;
if ((i + 1) % rGrid == 0)
{
if (board[i] == board[Pos]) Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(board[i]);
Console.ForegroundColor = ConsoleColor.Yellow;
}
else
{
if (board[i] == board[Pos]) Console.ForegroundColor = ConsoleColor.Green;
Console.Write(board[i]);
Console.ForegroundColor = ConsoleColor.Yellow;
}
i++;
}
}
static void Clear(int[] board, int rGrid)
{
int h = 0;
while (h < (rGrid*rGrid))
{
board[h] = 0;
h++;
}
}
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Enter CellGrid");
string grid = Console.ReadLine();
int rGrid;
if (int.TryParse(grid, out rGrid))
{
Console.Clear();
int Pos = rGrid;
int[] board = new int[(rGrid*rGrid)];
int j = 0;
while (j < (rGrid*rGrid))
{
board[j] = 0;
j++;
}
Choose:
int i = 0;
while (i < 10)
{
Print(board, Pos, rGrid);
string answer = Console.ReadLine();
Clear(board, rGrid);
if (answer == "w")
{
if ((Pos - rGrid) >= 0) Pos -= rGrid;
else Pos += ((rGrid*rGrid)-rGrid);
}
else if (answer == "s")
{
if ((Pos + rGrid) <= (rGrid * rGrid)) Pos += rGrid;
else
{
Pos -= ((rGrid * rGrid) - rGrid);
}
}
else if (answer == "d")
{
if ((Pos + 1) > ((rGrid*rGrid)-1))
{
Pos = 0;
}
else Pos++;
}
else if (answer == "a")
{
if ((Pos - 1) < 0)
{
Pos = (rGrid*rGrid)-1;
}
else Pos--;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Invalid Syntax!]");
Console.ReadKey();
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
goto Choose;
}
Console.Clear();
}
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Invalid Syntax!]");
Console.ReadKey();
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Main(null);
}
}
}
}
Last edited by a moderator: