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
|
//SimpleSnakeGame.cpp
//Date : 30/7/2015
#include <iostream>
#include <cstdlib>
bool gameover;
const int width = 20;
const int height = 10;
enum eDirection {STOP = 0, LEFT, RIGHT, UP, DOWN};
eDirection dir;
int x, y, foodx, foody, score;
void setUp();
//1)set the snake at the centre of the map.
//2)set the food position
void draw();
/*
draw the map:
#########
# #
#########
*/
void input();
//get the input of W, A, S, D from the keyboard.
//make switch case.
void logic();
//1)direction of the snake using W,A,S,D.
//2)Random food position
//3)Eat the food and generate another position.
//4)Hit the wall = GameOver.
//5)Tail of the snake grow when eat the food.
using namespace std;
int main()
{
srand(time(0));
setUp();
while(!gameover)
{
draw();
}
return 0;
}
void setUp()
{
gameover = false;
dir = STOP;
x = width/2;
y = height/2;
foodx = rand()%width;
foody = rand()%height;
}
void draw()
{
system("clear");
for(int i = 0; i < width; i++)
cout << "#";
cout << endl;
for(int j = 0; j < height; 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 == foodx && j == foody)
cout << "F";
else
cout << " ";
}
cout << endl;
}
for(int i = 0; i < width; i++)
cout << "#";
cout << endl;
}
void input()
{
if(_kbhit())
{
switch(_getch())
{
case 'a':
dir = LEFT;
break;
case 'w':
dir = UP;
break;
case 'd':
dir = RIGHT;
break;
case 's':
dir = DOWN;
break;
case 'x';
gameover = true;
}
}
}
void logic()
{
switch (dir)
{
case 'LEFT':
x --;
break;
case 'UP':
y --;
break;
case 'RIGHT':
x ++;
break;
case 'DOWN':
y ++;
break;
default:
break;
}
if(x > width || x < 0)
gameover = true;
if(y > height || y < 0)
gameover =true;
if(x == foodx && y == foody)
{
score = score + 10;
foodx = rand()%width;
foody = rand()%height;
}
}
|