뱀 게임
이번에는 c++을 이용해 간단한 뱀 게임을 만들어 보았다. 거의 30분 정도 걸린 듯 하다. 예전에 20살 때 프로젝트로 c를 이용하여 소코반 게임을 만들었던 경험이 있었는데 c++을 이용해서도 한번 간단한 콘솔 게임을 만들어 보고 싶어서 만들어 보았다. 유튜브의 간단한 게임 제작 영상을 바탕으로 만들었으며 굉장히 조잡하긴 하지만 작동은 잘 된다. 오랜만에 enum을 활용하여 코드를 짜본 것 같다.
전체 코드
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool gameOver;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirectoin { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirectoin dir;
void Setup() {
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw() {
system("cls");
for (int i = 0; i < width + 2; ++i)
cout << "#";
cout << endl;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (j == 0)
cout << "#";
if (i == y && j == x)
cout << "O";
else if (i == fruitY && j == fruitX)
cout << "F";
else {
bool print = false;
for (int k = 0; k < nTail; ++k) {
if (tailX[k] == j && tailY[k] == i) {
cout << "o";
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; ++i)
cout << "#";
cout << endl;
cout << "Score : " << score << endl;
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; ++i) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
/*if (x > width || x < 0 || y > height || y < 0)
gameOver = true;*/
if (x >= width) x = 0; else if (x < 0) x = width - 1;
if (y >= height) y = 0; else if (y < 0) y = height - 1;
for (int i = 0; i < nTail; ++i)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
++nTail;
}
}
int main()
{
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(10);
}
return 0;
}
코드 풀이
간단히 코드 풀이를 해보자면, 함수는 크게 Setup(), Draw(), Input(), Logic()으로 나눌 수 있다.
void Setup() {
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
먼저 Setup() 함수 이다. Setup()은 게임의 시작에 실행되며 뱀의 스타트 위치와 여러 변수의 초기값을 설정해 준다.
void Draw() {
system("cls");
for (int i = 0; i < width + 2; ++i)
cout << "#";
cout << endl;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (j == 0)
cout << "#";
if (i == y && j == x)
cout << "O";
else if (i == fruitY && j == fruitX)
cout << "F";
else {
bool print = false;
for (int k = 0; k < nTail; ++k) {
if (tailX[k] == j && tailY[k] == i) {
cout << "o";
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; ++i)
cout << "#";
cout << endl;
cout << "Score : " << score << endl;
}
Draw() 함수이다. Draw() 함수는 맵과 뱀을 콘솔에 그려주는 함수로, system(“cls”) 함수를 이용하여 콘솔 창을 수시로 갱신해주며 그려주게 된다. system(“cls”)는 엄청나게 느린 함수이기 때문에 갱신을 해주게 되는 과정에서 많이 느려지게된다. 뱀의 꼬리 부분은 tailX[], tailY[] 즉 꼬리의 위치에 꼬리를 출력해주고 아니면 빈칸을 출력하는 방식으로 구현됬다.
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
Input() 함수이다. Input() 함수는 키보드에 눌려지는 값을 받아와 move를 구현한 함수이다. _kbhit()는 키보드를 누른 경우 0이 아닌 값을 반환하고 그렇지 않으면 0을 반환한다. _getch()는 입력된 문자를 반환하는 함수이다.
void Logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; ++i) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
/*if (x > width || x < 0 || y > height || y < 0)
gameOver = true;*/
if (x >= width) x = 0; else if (x < 0) x = width - 1;
if (y >= height) y = 0; else if (y < 0) y = height - 1;
for (int i = 0; i < nTail; ++i)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
++nTail;
}
}
Logic() 함수이다. Logic() 함수는 뱀 게임의 전체적인 계산들을 해주는 함수이다. 뱀 머리의 위치와 과일을 먹었을 경우 과일의 재배치와 점수 추가등의 계산을 해준다. 주목할 점은 tailX[]와 tailY[]를 이용하여 이전 x, y 즉 뱀 머리의 이전 위치를 저장하여 꼬리가 이전 위치를 찾아가도록 반복문을 사용하여 뒤로 전달해주는 부분이다.