-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.cpp
More file actions
94 lines (81 loc) · 1.93 KB
/
Game.cpp
File metadata and controls
94 lines (81 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <vector>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include "Game.h"
using namespace std;
Game::Game(int _width, int _height)
: width(_width), height(_height),
squares(_height, vector<CellType>(_width, CELL_EMPTY)),
snake(*this, Position(_width/2, _height/2)),
currentDirection(Direction::RIGHT),
status(GAME_RUNNING),
score(0)
{
addCherry();
}
Game::~Game()
{
//dtor
}
void Game::snakeMoveTo(Position pos) {
switch(getCellType(pos)) {
case CELL_OFF_BOARD:
case CELL_SNAKE: status = GAME_OVER; break;
case CELL_CHERRY: score++; snake.eatCherry(); addCherry();
default: setCellType(pos, CELL_SNAKE);
}
}
void Game::snakeLeave(Position position)
{
setCellType(position,CELL_EMPTY);
}
void Game::processUserInput(Direction direction)
{
inputQueue.push(direction);
}
bool Game::canChange(Direction current, Direction next) const {
if (current == UP || current == DOWN)
return next == LEFT || next == RIGHT;
return next == UP || next == DOWN;
}
void Game::nextStep()
{
while (!inputQueue.empty())
{
Direction next = inputQueue.front();
inputQueue.pop();
if (canChange(currentDirection, next))
{
currentDirection = next;
break;
}
}
snake.move(currentDirection);
}
void Game::setCellType(Position pos, CellType cellType)
{
if (pos.isInsideBox(0, 0, width, height)) squares[pos.y][pos.x] = cellType;
}
CellType Game::getCellType(Position pos) const
{
return pos.isInsideBox(0, 0, width, height) ? squares[pos.y][pos.x] : CELL_OFF_BOARD;
}
void Game::setGameStatus(GameStatus status)
{
}
void Game::addCherry()
{
do {
Position p(rand() % width, rand() % height);
if (getCellType(p) == CELL_EMPTY) {
setCellType(p, CELL_CHERRY);
cherryPosition = p;
break;
}
} while (true);
}
vector<Position> Game::getSnakePositions() const
{
return snake.getPositions();
}