3주차 과제!!!
갑자기 게임 만들라고 해서 당황함
첫 번째 과제는 스네이크 게임 만들기다
static int[] dx = { 0, 1, 0, -1 };
static int[] dy = {1, 0, -1, 0 };
static int dir = 0; // → : 0, ↓ : 1, ← : 2, ↑ : 3
while (!isGameOver)
{
// 게임 보드 업데이트
updateGameBoard(gameBoard);
// 뱀이 다음에 이동할 좌표값
int nextX = curX + dx[dir];
int nextY = curY + dy[dir];
// 벽에 닿거나 뱀의 몸통에 닿으면 게임 종료
if (nextX < 0 || nextY < 0 || nextX >= GAME_BOARD_SIZE || nextY >= GAME_BOARD_SIZE ||
gameBoard[nextX, nextY] == SNAKE)
{
Console.WriteLine("게임 종료!");
Console.WriteLine("뱀 길이 : " + snakeLength);
Console.WriteLine("먹은 별의 개수 : " + star);
isGameOver = true;
}
else
{
moveSnake(nextX, nextY, gameBoard);
}
curX = nextX;
curY = nextY;
Thread.Sleep(100);
}
// 방향키 입력을 받는 Thread 생성
Thread thread = new Thread(() => getDirection());
thread.Start();
static void getDirection()
{
ConsoleKeyInfo input;
while (true)
{
input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.RightArrow:
dir = 0;
break;
case ConsoleKey.DownArrow:
dir = 1;
break;
case ConsoleKey.LeftArrow:
dir = 2;
break;
case ConsoleKey.UpArrow:
dir = 3;
break;
case ConsoleKey.Escape:
dir = 4;
Environment.Exit(0);
break;
}
}
}
internal class Program
{
const int GAME_BOARD_SIZE = 10;
const int EMPTY = 0;
const int SNAKE = 1;
const int STAR = 2;
const int FIRST_X = 5;
const int FIRST_Y = 3;
const int SPEED = 70;
static int[] dx = { 0, 1, 0, -1 };
static int[] dy = {1, 0, -1, 0 };
static Queue<int[]> queue = new Queue<int[]>(); // 뱀 몸통 좌표를 담을 큐
static int star_x = 5; // 별의 x 좌표
static int star_y = 7; // 별의 y 좌표
static int dir = 0; // → : 0, ↓ : 1, ← : 2, ↑ : 3
static int snakeLength = 3;
static int star = 0;
static void Main(string[] args)
{
int[,] gameBoard = new int[GAME_BOARD_SIZE, GAME_BOARD_SIZE];
initSnake(gameBoard);
gameBoard[star_x, star_y] = STAR;
Console.Title = "Snake Game";
Console.WriteLine("Welcome!");
Thread.Sleep(1000);
int curX = FIRST_X;
int curY = FIRST_Y;
bool isGameOver = false;
// 방향키 입력을 받는 Thread 생성
Thread thread = new Thread(() => getDirection());
thread.Start();
while (!isGameOver)
{
// 게임 보드 업데이트
updateGameBoard(gameBoard);
// 뱀이 다음에 이동할 좌표값
int nextX = curX + dx[dir];
int nextY = curY + dy[dir];
// 벽에 닿거나 뱀의 몸통에 닿으면 게임 종료
if (nextX < 0 || nextY < 0 || nextX >= GAME_BOARD_SIZE || nextY >= GAME_BOARD_SIZE ||
gameBoard[nextX, nextY] == SNAKE)
{
Console.WriteLine("게임 종료!");
isGameOver = true;
Environment.Exit(0);
}
else
{
moveSnake(nextX, nextY, gameBoard);
}
curX = nextX;
curY = nextY;
Thread.Sleep(SPEED);
}
}
// 처음 뱀의 위치를 보드에 그림
static void initSnake(int[,] gameBoard)
{
gameBoard[5, 1] = SNAKE;
gameBoard[5, 2] = SNAKE;
gameBoard[5, 3] = SNAKE;
queue.Enqueue(new int[] { 5, 1 });
queue.Enqueue(new int[] { 5, 2 });
queue.Enqueue(new int[] { 5, 3 });
}
// 게임 보드 업데이트
static void updateGameBoard(int[,] gameBoard)
{
Console.SetCursorPosition(0, 0); // 보드를 (0,0)부터 그리기 위해 커서 좌표 이동
Console.WriteLine("ESC : 종료");
gameBoard[star_x, star_y] = STAR; // 게임 보드 위에 별 좌표 설정
for (int i = 0; i < GAME_BOARD_SIZE; i++)
{
for (int j = 0; j < GAME_BOARD_SIZE; j++)
{
int curBoard = gameBoard[i, j];
if (curBoard == EMPTY)
{
Console.Write("□"); // 빈공간
} else if (curBoard == SNAKE)
{
Console.Write("■"); // 뱀
} else if(curBoard == STAR)
{
Console.Write("★"); // 별
}
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("뱀 길이 : " + snakeLength);
Console.WriteLine("먹은 별의 개수 : " + star);
}
// 방향키 입력을 받아서 뱀의 이동 방향 바꾸기
static void getDirection()
{
ConsoleKeyInfo input;
while (true)
{
input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.RightArrow:
dir = 0;
break;
case ConsoleKey.DownArrow:
dir = 1;
break;
case ConsoleKey.LeftArrow:
dir = 2;
break;
case ConsoleKey.UpArrow:
dir = 3;
break;
case ConsoleKey.Escape:
dir = 4;
Environment.Exit(0);
break;
}
}
}
// 다음 좌표로 뱀 이동시키기 (이동할 x 좌표, 이동할 y 좌표, 게임보드)
static void moveSnake(int x, int y, int[,] gameBoard)
{
// 다음에 이동할 좌표가 빈칸일 때
if (gameBoard[x, y] == EMPTY)
{
int[] last = queue.Dequeue(); // 뱀의 꼬리 부분 한칸 없애기
gameBoard[last[0], last[1]] = EMPTY;
}
// 다음에 이동할 좌표가 별일 때
else if (gameBoard[x, y] == STAR)
{
snakeLength++; // 뱀의 몸 길이 증가
star++; // 먹은 별 개수 증가
// 빈칸 중에서 임의로 골라 별 좌표 업데이트
do
{
star_x = new Random().Next(0, GAME_BOARD_SIZE);
star_y = new Random().Next(0, GAME_BOARD_SIZE);
} while (gameBoard[star_x, star_y] == SNAKE);
}
gameBoard[x, y] = SNAKE; // 다음 이동할 좌표를 뱀으로 바꿔줌
queue.Enqueue(new int[] { x, y }); // 뱀 몸통 업데이트
}
}
거 블랙잭씨 좀 나와봐유.
스네이크 게임이 더 오래 걸릴 줄 알았는데 스네이크는 천사였던 건에 대하여.
예외처리 지옥 시작
요약하자면 21에 가까운 숫자를 만드는 사람이 이기는 게임
아이고 머리야
const int SPADE = 0;
const int HEART = 1;
const int DIAMOND = 2;
const int CLOVER = 3;
static Dictionary<int, bool[]> cardDeck = new Dictionary<int, bool[]>();
// player 손에 있는 카드
static List<int[]> playerHand = new List<int[]>();
// dealer 손에 있는 카드
static List<int[]> dealerHand = new List<int[]>();
베팅 금액 정하기 -> 이 부분은 설명할게 딱히 없으니 넘어감
카드 나눠주기
// Hit인 경우 새 카드를 뽑음 (새 카드를 뽑는 사람 player or dealer)
static void getNewCard(int personType)
{
int shape = new Random().Next(0, 4);
int cardNum = new Random().Next(1, 14);
if (!cardDeck[shape][cardNum])
{
cardDeck[shape][cardNum] = true;
if (personType == PLAYER_TYPE)
{
playerHand.Add(new int[] { shape, cardNum });
} else
{
dealerHand.Add(new int[] { shape, cardNum });
}
}
}
플레이어 플레이 시작
// BlackJack 판단 여부 (BlackJack 여부를 판단 받을 사람 player or dealer)
static int BlackJack(int personType)
{
if (personType == PLAYER_TYPE)
{
if ((playerHand[0][1] == 1 && playerHand[1][1] >= 10) ||
(playerHand[0][1] >= 10 && playerHand[1][1] == 1))
{
return 1;
}
else
{
return -1;
}
} else
{
if ((dealerHand[0][1] == 1 && dealerHand[1][1] >= 10) ||
(dealerHand[0][1] >= 10 && dealerHand[1][1] == 1))
{
return 1;
}
else
{
return -1;
}
}
}
// Hit인 경우 새 카드를 받고, Bust 여부 판단 (Hit를 한 사람 player or dealer)
static bool Hit(int personType)
{
getNewCard(personType);
return isBust(personType);
}
// Bust 여부 판단 (Bust 여부를 판단 받을 사람 player or dealer)
static bool isBust(int personType)
{
if (personType == PLAYER_TYPE)
{
int sum = 0;
foreach (int[] card in playerHand)
{
if (card[1] >= 11) sum += 10;
else sum += card[1];
}
if (sum > 21) return true;
} else
{
int sum = 0;
foreach (int[] card in dealerHand)
{
if (card[1] >= 11) sum += 10;
else sum += card[1];
}
if (sum > 21) return true;
}
return false;
}
if (playerMoney - curBetMoney < 0)
Console.WriteLine("베팅 금액 부족으로 Double Down 할 수 없습니다. 다시 고르세요.");
else
{
playerMoney -= curBetMoney;
curBetMoney *= 2;
}
getNewCard(PLAYER_TYPE); // DoubleDown 선언 후 새 카드를 뽑음
isPlayerEnd = true;
if (isBust(PLAYER_TYPE)) // Bust
{
Console.WriteLine("Bust!");
isGameOver = true;
}
딜러 플레이 시작
int result = -1; // player, dealer 승패 여부 (2일 때는 무승부)
while (!isDealerEnd)
{
// 현재 dealer 카드의 합계
int dealerSum = 0;
foreach (int[] card in dealerHand)
{
if (card[1] >= 11) dealerSum += 10;
else dealerSum += card[1];
}
// 21을 초과할 경우 딜러 패배
if (dealerSum > BLACKJACK)
{
isDealerEnd = true;
result = PLAYER_TYPE;
}
// 17 ~ 21일 경우 player와 카드 합 비교
else if (dealerSum >= 17)
{
// dealer 카드 합이 딱 21인 경우 dealer 승리
// player가 승리할 수는 없음 (앞에서 블랙잭인 경우를 걸러냈으므로 이 경우 무조건 player 카드 합은 21보다 작기 때문)
if (BlackJack(DEALER_TYPE) == 1) result = DEALER_TYPE;
else result = compareSum();
isDealerEnd = true;
}
// 16 이하인 경우
else
{
// dealer는 히트 카드를 받고 Bust 여부 판단
if (Hit(DEALER_TYPE))
{
// Bust이면 player 승리
isDealerEnd = true;
result = PLAYER_TYPE;
}
}
}
너무 .. 길어서....
여기서 확인.....
GitHub_Black_Jack_Game
블랙잭을 해본 적이 없어서 룰은 좀 다를 수도 있겠지만
아무튼 구현했다는 것에 의미를 두는..네....
??? : 아니 어떻게 스플릿이 없을 수가 있삼?
나 :
낡고 지쳤지만
오늘 하루도 끗!!!!!!!!!!!
마 참 내
끗