Game.cpp
user_6225994
plain_text
2 years ago
1.6 kB
9
Indexable
#include "Game.h"
#include "Windows.h"
#include <conio.h>
#include <iostream>
using namespace std;
Game::Game() {
_mapGame = new Map();
_mapGame->DisPlayMap();
_apple = new Apple(_mapGame);
_snake = new Snake(_mapGame);
_snake->DisPlaySnake();
_score = 0;
}
void Game::Loop() {
_apple->GeneratePosition();
DisplayScore();
while (1) {
CheckKey();
_snake->Move();
if(_snake->_status == -1) break;
if(CheckSnakeEatApple())
DisplayScore();
Sleep(100);
}
if(system("CLS")) system("clear");
gotoxy(0, 0);
cout << "Game over, your score: " << _score << endl;
system("pause");
}
void Game::CheckKey() {
if (_kbhit()) {
int tmp = _getch();
if (tmp == (int)KEY_UP) {
if(_snake->_dir != DOWN)
_snake->_dir = UP;
}
else if (tmp == (int)KEY_DOWN) {
if (_snake->_dir != UP)
_snake->_dir = DOWN;
}
else if (tmp == (int)KEY_LEFT) {
if (_snake->_dir != RIGHT)
_snake->_dir = LEFT;
}
else if (tmp == (int)KEY_RIGHT) {
if (_snake->_dir != LEFT)
_snake->_dir = RIGHT;
}
}
}
bool Game::CheckSnakeEatApple(){
Point headSnake = _snake->_body.front();
if (headSnake._x == _apple->_pos._x && headSnake._y == _apple->_pos._y){
_snake->_status = 1;
//do {
_apple->GeneratePosition();
//}
//while(1);
_score++;
return true;
}
_snake->_status = 0;
return false;
}
Game::~Game(){
delete _mapGame;
delete _apple;
delete _snake;
}
void Game::DisplayScore(){
gotoxy(_mapGame->_w+1, 0);
cout << "Your score: " << _score;
}
Editor is loading...