-
Notifications
You must be signed in to change notification settings - Fork 0
/
snek.cpp
143 lines (121 loc) · 2.33 KB
/
snek.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
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
#include<iostream>
#include<conio.h>
#include<windows.h>
#include<ctime>
using namespace std;
bool gameover;
//game window resolution
const int width =50;
const int length=20;
//snek position
int x,y;
//fruit position
int fruitx,fruity;
//score
int score;
//direction tracking with enums
enum direction {STOP=0,LEFT,RIGHT,UP,DOWN};
direction dir;
void fruitpos(){
fruitx=rand() % 45+3;
fruity=rand() % 15+3;
}
void setup(){
gameover=false;
dir = STOP;
x=width/2;
y=length/2;
fruitpos();
score=0;
}
void draw(){
system("cls");
//border "#"s
for(int i=0;i<width;i++){
cout << "#";
}
cout << endl;
for(int j=1;j<length;j++){
for(int i=0;i<width;i++){
if(i==0){
cout << "#";
}else if (i==width-1){
cout << "#";
}else{
if(i==x && j==y){
cout << "O";
}else if (i==fruitx && j == fruity){
cout << "F";
}else{
cout << " ";
}
}
}
cout << endl;
}
for(int i=0;i<width;i++){
cout << "#";
}
cout << endl << "your score is = " << score;
}
void input(){
if(_kbhit()){
switch (_getch())
{
case 'w':
dir = UP;
break;
case 'a':
dir = LEFT;
break;
case 's':
dir = DOWN;
break;
case 'd':
dir = RIGHT;
break;
case '`':
gameover=true;
break;
}
}
}
void logic(){
switch(dir)
{
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if(x<1 || x>width-2){
gameover=true;
}
if(y<1 || y>length-1){
gameover=true;
}
if(x==fruitx && y == fruity){
score++;
fruitpos();
}
}
int main(){
srand((unsigned) time(0));
setup();
while(!gameover){
draw();
input();
logic();
Sleep(3);
}
getch();
return 0;
}