C语言实现贪吃蛇游戏

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

6)手动模式实现


void edition_handed(void) {
 system("cls");
 output();
 char ch = 'd';
 while (gamestate) {
  switch (ch) {
   case 'a': // go left
    while (1) {
     snakemove(-1, 0);
     Sleep(current_speed);
     if (gamestate == 0) // to break the loop if the snake hit the wall or itself.
      break;
     if (kbhit() != 0) { // to change the direction
      ch = getch();
     if (ch == 's' || ch == 'w')
      break;
     else 
      ch = 'a';
     }
    }
    break;
   case 'd': // go right
    while (1) {
     snakemove(1, 0);
     Sleep(current_speed);
     if (gamestate == 0)
      break;
     if (kbhit() != 0)
      ch = getch();
     if (ch == 's' || ch == 'w')
      break;
     else 
      ch = 'd';
    } 
    break;
   case 's': // go down
    while (1) {
     snakemove(0, 1);
     Sleep(current_speed);
     if (gamestate == 0)
      break;
     if (kbhit() != 0)
      ch = getch();
     if (ch == 'a' || ch == 'd')
      break;
     else 
      ch = 's';
    }
    break;
   case 'w': // go up
    while (1) {
     snakemove(0, -1);
     Sleep(current_speed);
     if (gamestate == 0)
      break;
     if (kbhit() != 0)
      ch = getch();
     if (ch == 'a' || ch == 'd')
      break;
     else 
      ch = 'w';
    }
    break;
  }
  if (gamestate == 0)
   break;
 } 
 return;
}

7)自动模式实现


void edition_presentation(void) { // for ai
 system("cls");
 int i, min = 10000;
 output();
 char ch;
 char quit = 'o';
 int k;
 while (gamestate) { // find the shortest way;
  min = 10000;
  if (judge(-1, 0)) distance[0] = dis(-1, 0);
  if (judge(1, 0)) distance[1] = dis(1, 0);
  if (judge(0, 1)) distance[2] = dis(0, 1);
  if (judge(0, -1)) distance[3] = dis(0, -1);
  for (i = 0; i < 4; i++) {
   if (min >= distance[i]) {
    min = distance[i];
    k = i;
   }
  }
  Sleep(current_speed);
  switch (movable[k]) {
   case 'a': // go left
    snakemove(-1, 0);
    break;
   case 'd': // go right
    snakemove(1, 0);
    break;
   case 's': // go down
    snakemove(0, 1);
    break;
   case 'w': // go up
    snakemove(0, -1);
    break; 
  }
  if (gamestate == 0)
   break;
  system("cls");
   output();
 }
 return;
}

8)其他辅助函数

欢迎界面


void welcome(void) { // just for some introduction
 printf("WELCOME TO THE SNAKE'S WORLD !!!!n");
 printf("n");
 printf("n");
 printf("Please choose the edition you want.n");
 printf("n");
 printf("n");
 printf("The 'h' is for the hand-operated and the 'p' is for the simple presentationn");
 printf("n");
 printf("n");
 printf("Attention: the presentation still has a liitle bug, while it can be moving right for a period of time...n ");
 return;
}