-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsnake_map.cpp
103 lines (96 loc) · 2.41 KB
/
snake_map.cpp
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
95
96
97
98
99
100
101
102
103
#include "snake_map.h"
#include <pthread.h>
#include <iostream>
#include <vector>
#include <utility>
#include <stdlib.h>
#include <time.h>
#include "macros.h"
using namespace std;
SnakeMap::SnakeMap(Snake *snake)
{
this->snake = snake;
clear_map(this->map_array);
srand(time(NULL));
update_snake_food(true);
}
void SnakeMap::redraw(void)
{
clear_map(this->map_array);
for (int i = 0; i < MAP_END; i++)
{
cout << endl;
}
update_score();
vector<pair<int, int>> snake_parts = snake->snake_parts;
for (int i = 0; i < snake_parts.size(); i++)
{
pair<int, int> tmp = snake_parts[i];
map_array[tmp.first][tmp.second] = SNAKE_CHAR;
}
update_snake_head(map_array, snake);
update_snake_food(false);
map_array[snake_food.first][snake_food.second] = SNAKE_FOOD_CHAR;
for (int i = 0; i < MAP_HEIGHT; i++)
{
for (int j = 0; j < MAP_WIDTH; j++)
{
cout << map_array[i][j] << " ";
}
cout << endl;
}
}
void SnakeMap::update_snake_food(bool force_update)
{
if (snake->food_eaten || force_update)
{
while (true)
{
int random_i = rand() % MAP_WIDTH;
int random_j = rand() % MAP_HEIGHT;
if (map_array[random_i][random_j] == MAP_CHAR)
{
snake_food = make_pair(random_i, random_j);
snake->set_snake_food(snake_food);
snake->food_eaten = false;
break;
}
}
}
}
void clear_map(char map_array[MAP_HEIGHT][MAP_WIDTH])
{
for (int i = 0; i < MAP_HEIGHT; i++)
{
for (int j = 0; j < MAP_WIDTH; j++)
{
map_array[i][j] = MAP_CHAR;
}
}
}
void update_snake_head(char map_array[MAP_HEIGHT][MAP_WIDTH], Snake *snake)
{
char snake_head_char = SNAKE_CHAR;
enum Direction direction = snake->get_direction();
switch (direction)
{
case West:
snake_head_char = SNAKE_HEAD_WEST;
break;
case North:
snake_head_char = SNAKE_HEAD_NORTH;
break;
case East:
snake_head_char = SNAKE_HEAD_EAST;
break;
case South:
snake_head_char = SNAKE_HEAD_SOUTH;
break;
}
pair<int, int> snake_head = snake->snake_head;
map_array[snake_head.first][snake_head.second] = snake_head_char;
}
void SnakeMap::update_score(void)
{
cout << "Score:" << snake->length << endl;
}