-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmysnake.cpp
More file actions
165 lines (144 loc) · 2.69 KB
/
Copy pathmysnake.cpp
File metadata and controls
165 lines (144 loc) · 2.69 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include<iostream>
#include<conio.h>
#include<cstdlib>
using namespace std;
void run ();
bool running;
void mapdef();
void changedirection(char);
void generatefood();
void updatemap();
void printmap();
void clearScreen();
int map[20][20], foodx,foody,direction=1; //1 for up
int headx,heady,tailx,taily,score=3;
int directiongrid[20][20]; //2 for down
int main()
{
for(int i=0;i<20;++i) //3 for left
for(int j=0;j<20;++j) //4 for right
map[i][j]='\0';
run();
return 0;
}
void run()
{ mapdef();
running=true;
while(running)
{
if(kbhit())
changedirection(getch());
updatemap();
clearScreen();
printmap();
_sleep(500);
}
cout<<endl;
cout<<"Your score is "<<score;
}
void clearScreen()
{
system("cls");
}
void mapdef()
{
for(int i=0;i<20;++i)
for(int j=0;j<20;++j)
if(i==0||i==19||j==0||j==19)
map[i][j]=1 ; // 1 is used for map outline
map[10][10]=map[11][10]=map[12][10]=2;
directiongrid[10][10]=directiongrid[11][10]=directiongrid[12][10]=1;
generatefood();
headx=10;
heady=10;
tailx=12;
taily=10;
}
void generatefood()
{
do
{
foodx=rand()%18+1;
foody=rand()%18+1;
}while(map[foodx][foody]==2);
map[foodx][foody]=3;
}
void changedirection(char dir)
{
switch(dir)
{
case 'w': if(direction!=2)
direction=1;
break;
case 's' : if(direction!=1)
direction=2;
break;
case 'a' : if(direction!=4)
direction=3;
break;
case 'd' : if(direction!=3)
direction=4;
break;
}
}
void updatemap()
{ directiongrid[headx][heady]=direction;
switch(direction)
{
case 1: headx= headx-1;
break;
case 2: headx= headx+1;
break;
case 3: heady= heady-1;
break;
case 4: heady= heady+1;
break;
}
if(map[headx][heady]==3)
{
map[headx][heady]=2;
score=score+1;
generatefood();
}
else if(map[headx][heady]==2||map[headx][heady]==1)
{
running=false;
}
else
{
map[headx][heady]=2;
map[tailx][taily]='\0';
switch(directiongrid[tailx][taily])
{
case 1: tailx=tailx-1;
break;
case 2: tailx=tailx+1;
break;
case 3: taily=taily-1;
break;
case 4: taily=taily+1;
break;
}
}
}
void printmap()
{
for(int i=0;i<20;++i)
{
for(int j=0;j<20;++j)
{
if(map[i][j]!='\0')
{
if(map[i][j]==1)
cout<<'x';
else if(map[i][j]==2)
cout<<'o';
else if(map[i][j]==3)
cout<<'0';
}
else if(map[i][j]=='\0')
cout<<" ";
}
cout<<endl;
}
}