스파르타 내일배움캠프/Today I Learned
Today I Learned - Day 6 [틱택토 제작하기]
불면증 도사
2024. 9. 19. 20:48
금일은 C#의 기본 문법에 대해서 공부하였습니다. 얼마 전 문법 톺아보기로도 한번 접했기도 한 지라, 전체적으로 복습한다는 느낌에 추가로 스파게티 코드 예방을 위해 '쉽게 알아볼 수 있게끔 하는 것'에 주의하여 작업했습니다.
코드
더보기
int[,] board = new int[3, 3];
bool turnInit, turnPlayer;
turnInit = (new Random().NextDouble() < 0.5f);
turnPlayer = turnInit;
InitBoard();
while (true)
{
DisplayBoard();
int result = CheckWinner();
if (result == 1)
{
Console.WriteLine("\nPlayer WIn!\n");
break;
}
else if (result == -1)
{
Console.WriteLine("\nCPU WIn!\n");
break;
}
else if (CheckBoard())
{
Console.WriteLine("\nDraw\n");
break;
}
else
{
if (turnPlayer)
PlayerAction();
else
CPUAction();
turnPlayer = !turnPlayer;
}
}
void InitBoard()
{
for (int i = 0; i < board.GetLength(0); i++)
for (int j = 0; j < board.GetLength(1); j++)
board[i, j] = 0;
}
void DisplayBoard()
{
for (int j = board.GetLength(0) - 1; j > -1; j--)
{
for (int i = 0; i < board.GetLength(1); i++)
{
if (board[i, j] == 1)
Console.Write("×");
else if(board[i, j] == -1)
Console.Write("○");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
bool SetBoard(int x, int y, int stone)
{
if (board[x, y] == 0)
{
board[x, y] = stone;
return true;
}
else
return false;
}
int CheckWinner()
{
int result = 0;
for (int i = 0; i < board.GetLength(0); i++)
if (board[i, 0] == board[i, 1] && board[i, 0] == board[i, 2])
result = board[i, 0];
for (int j = 0; j < board.GetLength(1); j++)
if (board[0, j] == board[1, j] && board[0, j] == board[2, j])
result = board[0, j];
if (board[0, 0] == board[1, 1] && board[0, 0] == board[2, 2])
result = board[0, 0];
if (board[0, 2] == board[1, 1] && board[0, 2] == board[2, 0])
result = board[2, 0];
return result;
}
bool CheckBoard()
{
bool result = true;
for (int i = 0; i < board.GetLength(0); i++)
for (int j = 0; j < board.GetLength(1); j++)
if (board[i, j] == 0)
result = false;
return result;
}
void PlayerAction()
{
Console.Write("Please play your next stone[x,y]: ");
string playCoordinate = Console.ReadLine();
string[] playCoordinateIndivisual = playCoordinate.Split(",");
int playX = Convert.ToInt32(playCoordinateIndivisual[0]);
int playY = Convert.ToInt32(playCoordinateIndivisual[1]);
bool success = SetBoard(playX, playY, 1);
if (!success)
{
Console.WriteLine("Wrong Position! Try Again!");
PlayerAction();
}
}
void CPUAction()
{
bool isMoved = false;
int stoneX = 0;
int stoneY = 0;
List<int[]> outList = new List<int[]>();
while (!isMoved)
{
stoneX = new Random().Next(0, 3);
stoneY = new Random().Next(0, 3);
isMoved = SetBoard(stoneX, stoneY, -1);
}
Console.WriteLine($"CPU plays stone in[x, y]: {stoneX},{stoneY}");
}