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
|
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <Windows.h>
using namespace std;
void clearscreen(); //used to prevent flicker
void movement(int left, int right, int up, int down, int &y, int &x); //used to recoodrinate the snake
int main() {
char map[20][40]; //decleares the map
//loads the bottom and top of the map with a border
for(int i=0; i < 40; ++i) {
map[0][i] = '#';
map[19][i] = '#';
}
//loads the rest of the map with vertical borders and space between them
for(int i=1; i < 19; ++i) {
for(int j=0; j < 41; ++j) {
map[i][0] = '#';
map[i][39] = '#';
if(j < 39) {
map[i][j] = ' ';
}
}
}
char snake = 'o';
int y=9, x=19; //used to coordinate the snake
int left=0, right=0, up=0, down=0; //used to determine which direction the snake should go
int foodcount = 0; //counts ammount of food eaten
int eaten = 0; //used to check if the snake ate food
//generates the food
char food = 'x';
int a, b; //used to position the food
srand(time(0));
a = rand() % 17 + 1;
Sleep(25);
b = rand() % 37 + 1;
map[a][b] = food;
for(;;) { //the game loop
clearscreen();
map[y][x] = snake; //places the snake
//displays the map
for(int i=0; i < 20; ++i) {
for(int j=0; j < 40; ++j) {
cout << map[i][j];
if(j >= 39) {
cout << endl;
}
}
}
cout << "Food eaten: " << foodcount << endl; //displays ammount of food eaten
//checks if the snake moves in another direction
if(GetAsyncKeyState(VK_LEFT)) {
right=0, up=0, down=0;
left = 1;
}
else if(GetAsyncKeyState(VK_RIGHT)) {
left=0, up=0, down=0;
right = 1;
}
else if(GetAsyncKeyState(VK_UP)) {
right=0, left=0, down=0;
up = 1;
}
else if(GetAsyncKeyState(VK_DOWN)) {
left=0, up=0, right=0;
down = 1;
}
//moves the snake
map[y][x] = ' ';
movement(left, right, up, down, y, x);
map[y][x] = snake;
//checks if the player crashed into the border
if(x == 0 || y == 0 || x == 39 || y == 19) {
cout << "\nYou lost!" << endl;
cin.get();
return 0;
}
if(map[y][x] == map[a][b]) {
++foodcount;
++eaten;
}
//if the snake ate food, generate a new one
if(eaten > 0) {
eaten = 0;
a = rand() % 18 + 1;
Sleep(25);
b = rand() % 38 + 1;
map[a][b] = food;
}
}
return 0;
}
void movement(int left, int right, int up, int down, int &y, int &x) {
if(left > 0) {
--x;
return;
}
else if(right > 0) {
++x;
return;
}
else if(up > 0) {
--y;
Sleep(20);
return;
}
else if(down > 0) {
++y;
Sleep(20);
return;
}
}
void clearscreen()
{
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
|