贪食蛇

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;                  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值