snake.c
#include"snake.h"
int main(void) {
put_money();
output();
char move = 'd';
while (1) {
if (kbhit())
scanf("%c", &move);
switch (move) {
case 'w':snakeMove(0,-1); break;
case 's':snakeMove(0,1); break;
case 'a':snakeMove(-1,0); break;
case 'd':snakeMove(1,0); break;
}
if (gameover())
output();
else
break;
while (getchar() != '\n')
continue;
}
printf("Game Over!!!");
return 0;
}
void snakeMove(int x, int y) {
snakeY[snakeLength] = snakeY[snakeLength - 1] + y;
snakeX[snakeLength] = snakeX[snakeLength - 1] + x;
}
void put_money(void) {
int x = 0, y = 0;
srand((unsigned int)time(0));
for (;map[y][x] != BLANK_CELL;) {
x = rand() % 10 + 1;
y = rand() % 10 + 1;
}
map[y][x] = SNAKE_FOOD;
}
void output(void) {
int i = 0, j = 0;
for (i = 0; i < snakeLength - 1; ++i)
map[snakeY[i]][snakeX[i]] = SNAKE_BODY;
map[snakeY[i]][snakeX[i]] = SNAKE_HEAD;
for (i = 0; i < 12; ++i) {
for (j = 0; j < 12; ++j)
putchar(map[i][j]);
putchar('\n');
}
}
int gameover(void) {
int i;
if (map[snakeY[snakeLength]][snakeX[snakeLength]] == BLANK_CELL) {
map[snakeY[0]][snakeX[0]] = ' ';
for (i = 0; i < snakeLength - 1; ++i) {
snakeX[i] = snakeX[i + 1];
snakeY[i] = snakeY[i + 1];
}
snakeX[i] = snakeX[snakeLength];
snakeY[i] = snakeY[snakeLength];
return 1;
}
else if (map[snakeY[snakeLength]][snakeX[snakeLength]] == SNAKE_FOOD && snakeLength < SNAKE_MAX_LENGTH) {
++snakeLength;
put_money();
return 1;
}
else
return 0;
}
snake.h
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<ncurses.h>
#define SNAKE_MAX_LENGTH 20
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define BLANK_CELL ' '
#define SNAKE_FOOD '$'
#define WALL_CELL '*'
void snakeMove(int, int);
void put_money(void);
void output(void);
int gameover(void);
char map[12][12] =
{"************",
"*XXXXH *",
"* *",
"* *",
"* *",
"* *",
"* *",
"* *",
"* *",
"* *",
"* *",
"************"};
int snakeX[SNAKE_MAX_LENGTH] = {1,2,3,4,5};
int snakeY[SNAKE_MAX_LENGTH] = {1,1,1,1,1};
int snakeLength = 5;