C语言实现贪吃蛇游戏

2020-01-06 18:28:39丽君

游戏结束界面


void gameover(void) { // give you some introduction when you lose the game.
 system("cls");
 printf("Game over!!!n");
 printf("Do you want to continue? y or nn");
 char start; // in order to judge whether you still want to play the game.
 while (1) {
  start = getch();
  if (start == 'y') {
   system("cls");
   initial_the_game();
   break;
  } else if (start == 'n') {
   system("cls");
   con = 0; // in order to let the game end.
   printf("See you next time! ^-^n");
   break;
  } else {
   printf("Please press the correct buttom.n");
  }
 }
}

图像实现方式


void output(void) { // put the cuttent game map.
 printf("THE INTERESTING SNAKE GAME CREATED BY LONGJ =,=n");
 printf("use w~s~a~d to control the snake's movementn");
 printf("ATTENTION: the @ can speed up your lovely snake~~n");
 int i, j;
 for (i = 0; i < 12; i++) {
  for (j = 0; j < 12; j++) { 
   printf("%c", map[i][j]);
   if (j == 11)
    printf("n");
  }
 }
 printf("Your current_speed is %dn", current_speed);
 printf("The number of your food undigested is %d (when it comes to 5, your speed will be accelerated!) n", energy);
 printf("SCORE = %dn", score);
 return;
}

蛇的行走实现


void snakemove(int dx, int dy) { // all the conditions are comparing the head and the next position.
 int i;
 if (snakeY[snakeLength - 1] + dy == snakeY[snakeLength - 2] && snakeX[snakeLength - 1] + dx == snakeX[snakeLength - 2])
  return; // to prevent it go to itslef.
 if (map[snakeY[snakeLength - 1] + dy][snakeX[snakeLength - 1] + dx] == 'X') {
  gamestate = 0;
  return;
 }
 if (map[snakeY[snakeLength - 1] + dy][snakeX[snakeLength - 1] + dx] == '*') {
  gamestate = 0;
  return;
 }
 if (map[snakeY[snakeLength - 1] + dy][snakeX[snakeLength - 1] + dx] == ' '
  || map[snakeY[snakeLength - 1] + dy][snakeX[snakeLength - 1] + dx] == '@') {
  map[snakeY[0]][snakeX[0]] = ' '; // clear the former_tail
  if (map[snakeY[snakeLength - 1] + dy][snakeX[snakeLength - 1] + dx] == '@'
  && current_speed > 100) { // what will happen when your snake eats the @
   current_speed -= 100;
   put_accelerate();
  }
  for (i = 0; i < snakeLength - 1; ++i) {
   snakeX[i] = snakeX[i + 1];
   snakeY[i] = snakeY[i + 1];
  }
  snakeX[snakeLength - 1] += dx;
  snakeY[snakeLength - 1] += dy;
  for (i = 0; i < snakeLength - 1; i++) // write down the current snake location
   map[snakeY[i]][snakeX[i]] = 'X';
  map[snakeY[snakeLength - 1]][snakeX[snakeLength - 1]] = 'H';
 }
 if (map[snakeY[snakeLength - 1] + dy][snakeX[snakeLength - 1] + dx] == '$') {
  map[snakeY[snakeLength - 1]][snakeX[snakeLength - 1]] = 'X';
  snakeLength++;
  snakeX[snakeLength - 1] = snakeX[snakeLength - 2] + dx;
  snakeY[snakeLength - 1] = snakeY[snakeLength - 2] + dy;
  map[snakeY[snakeLength - 1]][snakeX[snakeLength - 1]] = 'H';
  score++;
  energy++;
  if (energy == 5 && current_speed > 50) {
   current_speed -= 50;
   energy = 0;
  }
  put_money();
 }
 system("cls");
 output();
 return;
}