亲宝软件园·资讯

展开

C语言实现贪吃蛇 70行C语言代码实现贪吃蛇

Keepower 人气:0
想了解70行C语言代码实现贪吃蛇的相关内容吗,Keepower在本文为您仔细讲解C语言实现贪吃蛇的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C语言,贪吃蛇,下面大家一起来学习吧。


#include <stdio.h> 
#include <Windows.h> 
#include <conio.h> 
#include <time.h> 
 
#define MAX_WIDE 50 
#define MAX_HIGH 16 
 
short dx = 1, dy = 0, randxy, score = 0; 
COORD coord; 
 
struct Snake{ 
 short len; 
 short body[MAX_WIDE*MAX_HIGH]; 
}snake; 
 
void draw() 
{ 
 for(short i = 0; i < snake.len; i++){ 
  coord.X = snake.body[i] & 127; 
  coord.Y = snake.body[i] >> 8; 
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); 
  putchar('*'); 
 } 
 coord.X = randxy & 127; 
 coord.Y = randxy >> 8; 
 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); 
 putchar('*'); 
} 
void run() 
{ 
 char key; 
 short i, j; 
 while( snake.body[0] > 0 && ( (snake.body[0] & 127) < MAX_WIDE) && (snake.body[0]>>8 < MAX_HIGH) ){ 
  draw(); 
  for(;kbhit();) key = getch(); 
  switch(key){ 
  case 'W': dx = 0, dy = -1; break; 
  case 'S': dx = 0, dy = 1; break; 
  case 'A': dx = -1, dy = 0; break; 
  case 'D': dx = 1, dy = 0; break; 
  } 
  for(j = 1; j < snake.len; j++) 
   if(snake.body[j] == snake.body[0]) 
    return; 
  if(randxy == snake.body[0]){ 
    snake.len++, score += 10; 
    randxy = ((rand() % 16 + 0) <<8) | (rand() % 50 + 0); 
  } 
  for(i = snake.len-1; i > 0; i--) 
   snake.body[i] = snake.body[i-1]; 
  snake.body[0] = ((snake.body[0] & 127) + dx) | ((snake.body[0] >>8) + dy)<<8; 
  Sleep(500); 
  system("cls"); 
 } 
} 
int main() 
{ 
 snake.body[MAX_WIDE*MAX_HIGH] = 0; 
 snake.body[0] = (MAX_HIGH/2)<<8 | MAX_WIDE/2; 
 snake.len = 1; 
 srand((unsigned)time(NULL)); 
 randxy = ((rand() % 16 + 0) <<8) | (rand() % 50 + 0); 
 SMALL_RECT rect; 
 rect.Top = 0, rect.Left = 0; 
 rect.Bottom = MAX_HIGH, rect.Right = MAX_WIDE; 
 SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), true, &rect); 
 run(); 
 printf("Your Score:%d", score); 
 return 0; 
} 

环境:VC++6.0 

该代码效率不高,代码又难读,仅供娱乐。

讲一下大概的实现思想吧:

.:其中用一个MAX_WIDE * MAX_HIGH大的数组来虚拟化snake的躯干,数组中的项保存该snake的坐标值,并且该值用一个short(16byte)类型的值表示,高8byte表示它的Y坐   标,低8byte表示它的X坐标,然后就可以遍历该数组画出各个坐标点。

.:至于它的移动就是通过数组的前一个项的值复制给后一个项,以此达到它的移动。

当然也可以用链表代替数组实现该snake躯干,而且不会像数组一样浪费内存,但是用链表的话,就增加了代码行^_^

加载全部内容

相关教程
猜你喜欢
用户评论