本文实例为大家分享了C语言实现贪吃蛇的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
#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躯干,而且不会像数组一样浪费内存,但是用链表的话,就增加了代码行^_^
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://blog.csdn.net/LYH66/article/details/7367561