我有一个想要在其中选择球员的网格中移动的程序。当从最后一行的第一个位置移动时,由于值超出了数组的大小,它给了我一条错误消息,我不知道如何解决它。而且,当我按下按钮时如何使它自动移动,因此我不必在两次按下之间按Enter即可进行注册?
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);
}
}
}
}
由主持人最后编辑: