贪吃蛇简易代码
Python实现的贪吃蛇小游戏代码
以下是Python实现的贪吃蛇小游戏代码:```pythonimport pygameimport random# 初始化Pygamepygame.init()# 设置游戏窗口大小和标题screen_width = 480screen_height = 480game_display = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption('贪吃蛇游戏')# 定义颜色white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)green = (0, 255, 0)# 定义蛇的初始位置和尺寸snake_block_size = 20snake_speed = 10initial_snake_pos = {'x': screen_width/2, 'y': screen_height/2}snake_list = [initial_snake_pos]# 定义食物的尺寸和位置food_block_size = 20food_pos = {'x': round(random.randrange(0, screen_width - food_block_size) / 20.0) * 20.0, 'y': round(random.randrange(0, screen_height - food_block_size) / 20.0) * 20.0}# 定义分数、字体和大小score = 0font_style = pygame.font.SysFont(None, 30)# 刷新分数def refresh_score(score):score_text = font_style.render("Score: " + str(score), True, black)game_display.blit(score_text, [0, 0])# 绘制蛇def draw_snake(snake_block_size, snake_list):for pos in snake_list:pygame.draw.rect(game_display, green, [pos['x'], pos['y'], snake_block_size, snake_block_size])# 显示消息def message(msg, color):message_text = font_style.render(msg, True, color)game_display.blit(message_text, [screen_width/6, screen_height/3])# 主函数循环def game_loop():game_over = Falsegame_close = False# 设置蛇头的初始移动方向x_change = 0y_change = 0# 处理事件while not game_over:while game_close:game_display.fill(white)message("You lost! Press Q-Quit or C-Play Again", red)refresh_score(score)pygame.display.update()# 处理重新开始和退出事件for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseelif event.key == pygame.K_c:game_loop()# 处理按键事件for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x_change = -snake_block_sizey_change = 0elif event.key == pygame.K_RIGHT:x_change = snake_block_sizey_change = 0elif event.key == pygame.K_UP:y_change = -snake_block_sizex_change = 0elif event.key == pygame.K_DOWN:y_change = snake_block_sizex_change = 0# 处理蛇的移动位置if snake_list[-1]['x'] >= screen_width or snake_list[-1]['x'] < 0 or snake_list[-1]['y'] >= screen_height or snake_list[-1]['y'] < 0:game_close = Truesnake_list[-1]['x'] += x_changesnake_list[-1]['y'] += y_change# 处理食物被吃掉的情况if snake_list[-1]['x'] == food_pos['x'] and snake_list[-1]['y'] == food_pos['y']:score += 10food_pos = {'x': round(random.randrange(0, screen_width -food_block_size) / 20.0) * 20.0,'y': round(random.randrange(0, screen_height -food_block_size) / 20.0) * 20.0}else:snake_list.pop(0)# 处理蛇撞到自身的情况for pos in snake_list[:-1]:if pos == snake_list[-1]:game_close = True# 刷新游戏窗口game_display.fill(white)draw_snake(snake_block_size, snake_list)pygame.draw.rect(game_display, red, [food_pos['x'], food_pos['y'], food_block_size, food_block_size])refresh_score(score)pygame.display.update()# 设置蛇移动的速度clock = pygame.time.Clock()clock.tick(snake_speed)pygame.quit()quit()game_loop()```当您运行此代码时,将会启动一个贪吃蛇小游戏。
超简单贪吃蛇c语言代码编写
超简单贪吃蛇c语言代码编写贪吃蛇其实就是实现以下几步——1:蛇的运动(通过“画头擦尾”来达到蛇移动的视觉效果)2:生成食物3:蛇吃食物(实现“画头不擦尾”)4:游戏结束判断(也就是蛇除了食物,其余东西都不能碰)#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>#include<time.h>#define width 60#define hight 25#define SNAKESIZE 200//蛇身的最长长度int key=72;//初始化蛇的运动方向,向上int changeflag=1;//用来标识是否生成食物,1表示蛇还没吃到食物,0表示吃到食物int speed=0;//时间延迟struct {int len;//用来记录蛇身每个方块的坐标int x[SNAKESIZE];int y[SNAKESIZE];int speed;}snake;struct{int x;int y;}food;void gotoxy(int x,int y)//调用Windows的API函数,可以在控制台的指定位置直接操作,这里可暂时不用深究{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }//■○void drawmap(){//打印图框for (int _y = 0; _y < hight; _y++){for (int x = 0; x < width; x+=2){if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2){gotoxy(x, _y);printf("■");}}}//打印蛇头snake.len=3;snake.x[0]=width/2;snake.y[0]=hight/2;gotoxy(snake.x[0],snake.y[0]);printf("■");//打印蛇身for(int i=1;i<snake.len;i++){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1]+1;gotoxy(snake.x[i],snake.y[i]);printf("■");}//初始化食物的位置food.x=20;food.y=20;gotoxy(food.x,food.y);printf("○");}/**控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*/void snake_move()//按键处理函数{int history_key=key;if (_kbhit()){fflush(stdin);key = _getch();key = _getch();}if(changeflag==1)//还没吃到食物,把尾巴擦掉{gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);printf(" ");}for(int i=snake.len-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}if(history_key==72&&key==80)key=72;if(history_key==80&&key==72)key=80;if(history_key==75&&key==77)key=75;if(history_key==77&&key==75)key=77;switch(key){case 72:snake.y[0]--;break;case 75:snake.x[0]-= 2;break;case 77:snake.x[0]+= 2;break;case 80:snake.y[0]++;break;}gotoxy(snake.x[0],snake.y[0]);printf("■");gotoxy(0,0);changeflag=1;}void creatfood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//只有蛇吃到食物,才能生成新食物{changeflag=0;snake.len++;if(speed<=100)speed+=10;while(1){srand((unsigned int) time(NULL));food.x=rand()%(width-6)+2;//限定食物的x范围不超出围墙,但不能保证food.x 为偶数food.y=rand()%(hight-2)+1;for(int i=0;i<snake.len;i++){if(food.x==snake.x[i]&&food.y==snake.y[i])//如果产生的食物与蛇身重合则退出break;}if(food.x%2==0)break;//符合要求,退出循环}gotoxy(food.x,food.y);printf("○");}}bool Gameover(){//碰到围墙,OVERif(snake.x[0]==0||snake.x[0]==width-2)return false;if(snake.y[0]==0||snake.y[0]==hight-1) return false;//蛇身达到最长,被迫OVERif(snake.len==SNAKESIZE)return false;//头碰到蛇身,OVERfor(int i=1;i<snake.len;i++){if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i])return false;}return true;}int main(){system("mode con cols=60 lines=27");drawmap();while(Gameover()){snake_move();creatfood();Sleep(350-speed);//蛇的移动速度}return 0;}。
(完整word版)C语言最简洁的贪吃蛇源代码
C语言最简洁的贪吃蛇源代码.txt每天早上起床都要看一遍“福布斯”富翁排行榜,如果上面没有我的名字,我就去上班。
谈钱不伤感情,谈感情最他妈伤钱。
我诅咒你一辈子买方便面没有调料包。
#include〈graphics.h>#include<conio。
h〉#include〈dos.h〉#include<bios。
h>#include<stdlib。
h〉#define STATIC 0#define TRUE 1#define FALSE 0#define UP 1#define RIGHT 2#define DOWN 3#define LEFT 4#define VK_LEFT 0x4b00 /*上下左右键的值*/#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_ESC 0x011bint board[22][22];int snakelength=0;struct snake{public:int x=0;int y=0;int direction;}body[20];snake food;void makefood();/*产生一个食物*/int eatfood(); /*蛇吃掉食物*/void right(); /*上下左右的函数了*/void down();void left();void up();void getdirection(); /*判断蛇的方向*/move(snake *body)/*让蛇动起来*/{int x=body[0].x,y=body[0].y;if(body—>direction==RIGHT&&board[y][x+1]!=1)right();else if(body—>direction==DOWN&&board[y+1][x]!=1)down(); else if(body->direction==LEFT&&board[y][x—1]!=1)left(); else if(body—>direction==UP&&board[y-1][x]!=1)up();return 0;}void print() /*在屏幕上显示蛇*/{int i,j,x=0,y=0;for(i=1;i〈21;i++)for(j=1;j<21;j++)board[i][j]=0;for(i=0;i〈20;i++){x=body[i]。
游戏贪吃蛇python编程代码
游戏贪吃蛇python编程代码基本准备首先,我们需要安装pygame库,小编通过pip install pygame,很快就安装好了。
在完成贪吃蛇小游戏的时候,我们需要知道整个游戏分为四部分:游戏显示:游戏界面、结束界面贪吃蛇:头部、身体、食物判断、死亡判断树莓:随机生成按键控制:上、下、左、右游戏显示首先,我们来初始化pygame,定义颜色、游戏界面的窗口大小、标题和图标等。
1# 初始化pygame2pygame.init()3fpsClock = pygame.time.Clock()4# 创建pygame显示层5playSurface = pygame.display.set_mode((600,460))#窗口大小6pygame.display.set_caption('Snake Game')#窗口名称7# 定义颜色变量8redColour = pygame.Color(255,0,0)9blackColour = pygame.Color(0,0,0)10whiteColour = pygame.Color(255,255,255)11greyColour = pygame.Color(150,150,150)游戏结束界面,我们会显示“Game Over!”和该局游戏所得分数,相关代码如下:1# 定义gameOver函数2def gameOver(playSurface,score):3 gameOverFont = pygame.font.SysFont('arial.ttf',54) #游戏结束字体和大小4 gameOverSurf = gameOverFont.render('Game Over!', True, greyColour) #游戏结束内容显示5 gameOverRect = gameOverSurf.get_rect()6 gameOverRect.midtop = (300, 10) #显示位置7 playSurface.blit(gameOverSurf, gameOverRect)8 scoreFont = pygame.font.SysFont('arial.ttf',54) #得分情况显示9 scoreSurf = scoreFont.render('Score:'+str(score), True, greyColour)10 scoreRect = scoreSurf.get_rect()11 scoreRect.midtop = (300, 50)12 playSurface.blit(scoreSurf, scoreRect)13 pygame.display.flip() #刷新显示界面14 time.sleep(5) #休眠五秒钟自动退出界面15 pygame.quit()16 sys.exit()贪吃蛇和树莓我们需要将整个界面看成许多20*20的小方块,每个方块代表一个单位,蛇的长度用单位来表示,同时我们采用列表的形式存储蛇的身体。
java贪吃蛇 代码
代码:一:::::::public class Cell {// 格子:食物或者蛇的节点private int x;private int y;private Color color;// 颜色public Cell() {}public Cell(int x, int y) {this.x = x;this.y = y;}public Cell(int x, int y, Color color) { this.color = color;this.x = x;this.y = y;}public Color getColor() {return color;}public int getX() {return x;}public int getY() {return y;}public String toString() {return"[" + x + "]" + "[" + y + "]";}}二::::::::::public class Worm {private int currentDirection;// 蛇包含的格子private Cell[] cells;private Color color;public static final int UP = 1;public static final int DOWN = -1;public static final int RIGHT = 2;public static final int LEFT = -2;// 创建对象创建默认的蛇:(0,0)(1,0)(2,0)······(11,0)public Worm() {// 构造器初始化对象color = Color.pink;// 蛇的颜色cells = new Cell[12];// 创建数组对象for (int x = 0, y = 0, i = 0; x < 12; x++) { // for(int y=0;;){}cells[i++] = new Cell(x, y, color);// 添加数组元素}currentDirection = DOWN;}public boolean contains(int x, int y) {// 数组迭代for (int i = 0; i < cells.length; i++) {Cell cell = cells[i];if (cell.getX() == x && cell.getY() == y) {return true;}}return false;}public String toString() {return Arrays.toString(cells);}public void creep() {for (int i = this.cells.length - 1; i >= 1; i--) {cells[i] = cells[i - 1];}cells[0] = createHead(currentDirection);}// 按照默认方法爬一步private Cell createHead(int direction) {// 根据方向,和当前(this)的头结点,创建新的头结点int x = cells[0].getX();int y = cells[0].getY();switch (direction) {case DOWN:y++;break;case UP:y--;break;case RIGHT:x++;break;case LEFT:x--;break;}return new Cell(x, y);}/*** food 食物**/public boolean creep(Cell food) {Cell head = createHead(currentDirection);boolean eat = head.getX() == food.getX() && head.getY() == food.getY();if (eat) {Cell[] ary = Arrays.copyOf(cells, cells.length + 1);cells = ary;// 丢弃原数组}for (int i = cells.length - 1; i >= 1; i--) { cells[i] = cells[i - 1];}cells[0] = head;return eat;}// 吃到东西就变长一格public boolean creep(int direction, Cell food) {if (currentDirection + direction == 0) {return false;}this.currentDirection = direction;Cell head = createHead(currentDirection);boolean eat = head.getX() == food.getX() && head.getY() == food.getY();if (eat) {Cell[] ary = Arrays.copyOf(cells, cells.length + 1);cells = ary;// 丢弃原数组}for (int i = cells.length - 1; i >= 1; i--) { cells[i] = cells[i - 1];}cells[0] = head;return eat;}// 检测在新的运动方向上是否能够碰到边界和自己(this 蛇)public boolean hit(int direction) {// 生成下个新头节点位置// 如果新头节点出界返回true,表示碰撞边界// ···············if (currentDirection + direction == 0) {return false;}Cell head = createHead(direction);if(head.getX() < 0 || head.getX() >= WormStage.COLS || head.getY() < 0|| head.getY() >= WormStage.ROWS) {return true;}for (int i = 0; i < cells.length - 1; i++) { if (cells[i].getX() == head.getX()&& cells[i].getY() == head.getY()) {return true;}}return false;}public boolean hit() {return hit(currentDirection);}// 为蛇添加会制方法// 利用来自舞台面板的画笔绘制蛇public void paint(Graphics g) {g.setColor(this.color);for (int i = 0; i < cells.length; i++) {Cell cell = cells[i];g.fill3DRect(cell.getX() * WormStage.CELL_SIZE, cell.getY()* WormStage.CELL_SIZE, WormStage.CELL_SIZE,WormStage.CELL_SIZE, true);}}}三:::::::::public class WormStage extends JPanel {/** 舞台的列数 */public static final int COLS = 35;/** 舞台的行数 */public static final int ROWS = 35;/** 舞台格子的大小 */public static final int CELL_SIZE = 10;private Worm worm;private Cell food;public WormStage() {worm = new Worm();food = createFood();}/*** 随机生成食物,要避开蛇的身体 1 生成随机数 x, y 2 检查蛇是否包含(x,y)* 3 如果包含(x,y) 返回 1 4 创建食物节点* */private Cell createFood() {Random random = new Random();int x, y;do {x = random.nextInt(COLS);// COLS列数y = random.nextInt(ROWS);// WOWS行数} while (worm.contains(x, y));return new Cell(x, y, Color.green);// 食物颜色/** 初始化的舞台单元测试 */public static void test() {WormStage stage = new WormStage();System.out.println(stage.worm);System.out.println(stage.food);}/*** 重写JPanel绘制方法paint:绘制,绘画,涂抹Graphics 绘图,* 理解为:绑定到当前面板的画笔*/public void paint(Graphics g) {// 添加自定义绘制!// 绘制背景g.setColor(Color.darkGray);// 背景色g.fillRect(0, 0, getWidth(), getHeight());g.setColor(Color.cyan);// 边框上的颜色// draw 绘制 Rect矩形g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);// 绘制食物g.setColor(food.getColor());// fill 填充 3D 3维 Rect矩形突起的立体按钮形状g.fill3DRect(food.getX() * CELL_SIZE, food.getY() * CELL_SIZE,CELL_SIZE, CELL_SIZE, true);// 绘制蛇worm.paint(g);// 让蛇自己去利用画笔绘制private Timer timer;/*** 启动定时器驱动蛇的运行 1 检查碰撞是否将要发生* 2 如果发生碰撞:创建新的蛇和食物,重写开始* 3 如果没有碰撞就爬行,并检查是否能够吃到食物* 4如果吃到食物:重新创建新的食物* 5 启动重新绘制界面功能 repaint() 更新界面显示效果! repaint()* 方法会尽快调用paint(g) 更新界面!*/private void go() {if (timer == null)timer = new Timer();timer.schedule(new TimerTask() {public void run() {if (worm.hit()) {// 如果蛇碰到边界或自己worm = new Worm();// 创建新的蛇food = createFood();// 创建新食物} else {// 如果没有碰到自己boolean eat = worm.creep(food);// 蛇向前(当前方向)爬行,返回结果表示是否吃到食物if(eat) {// 如果吃到食物,就生成新食物food = createFood();}}repaint();}}, 0, 1000 / 5);this.requestFocus();this.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch (key) {case KeyEvent.VK_UP:creepForFood(Worm.UP);break;case KeyEvent.VK_DOWN:creepForFood(Worm.DOWN);break;case KeyEvent.VK_LEFT:creepForFood(Worm.LEFT);break;case KeyEvent.VK_RIGHT:creepForFood(Worm.RIGHT);break;}}});}private void creepForFood(int direction) { if (worm.hit(direction)) {worm = new Worm();food = createFood();} else {boolean eat = worm.creep(direction, food);if (eat) {food = createFood();}}}/** 软件启动的入口方法 */public static void main(String[] args) {// 启动软件....JFrame frame = new JFrame("贪吃蛇");// 一个画框对象frame.setSize(450, 480);// size 大小,setSize 设置大小// frame.setLocation(100,50);//Locationq位置frame.setLocationRelativeTo(null);// 居中// 设置默认的关闭操作为在关闭时候离开软件frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);// Visible可见的设置可见性frame.setLayout(null);// 关闭默认布局管理,避免面板充满窗口WormStage stage = new WormStage();// System.out.println("CELL_SIZE * COLS:"+CELL_SIZE * COLS);stage.setSize(CELL_SIZE* COLS, CELL_SIZE* ROWS);stage.setLocation(40, 50);stage.setBorder(new LineBorder(Color.BLACK));frame.add(stage);// 在窗口添加舞台stage.go();// 启动定时器驱动蛇自动运行}}。
贪吃蛇代码(C 实现)
for(i=T.tail;i!=T.head;) {
; }
if(kbhit()&&(order=getch(),order=='w'||order=='s'||order=='a'|| order=='d'))
{
sum=T.body[(T.head-1+ML)%ML]; system("CLS"); for(i=T.tail;i!=T.head;) {
jud=order; //printf("-->a\n"); if(map[sum/100][sum%100-1]!=-1) { for(i=T.tail;i!=T.head;) { temp=T.body[i]; map[temp/100][temp%100]=0; i++; i%=ML; }
aaa(); } else {
sum=T.body[i]; map[sum/100][sum%100]=-1; i++; i%=ML; } while(1) { sum=getnum(); if(map[sum/100][sum%100]==0) {
map[sum/100][sum%100]=1; break; } } for(i=T.tail;i!=T.head;) { sum=T.body[i]; map[sum/100][sum%100]=0; i++; i%=ML; } } else { T.body[T.head++]=sum; T.head%=ML; T.tail=(++T.tail)%ML; } } void sss() { int sum,i; sum=T.body[(T.head-1+ML)%ML]+100; if(map[sum/100][sum%100]==1) { T.length++; T.body[T.head++]=sum; T.head%=ML; map[sum/100][sum%100]=0; for(i=T.tail;i!=T.head;) { sum=T.body[i]; map[sum/100][sum%100]=-1; i++;
贪吃蛇c语言代码
#include<stdio.h>#include<stdlib.h>#include<Windows.h>#include<conio.h>#include<time.h>char gamemap[20][40];//游戏地图大小20*40 int score=0;//当前分数//记录蛇的结点int x[800];//每个结点的行编号int y[800];//每个结点的列编号int len = 0;//蛇的长度//记录水果信息int fx=;//食物的横坐标int fy=00;//食物的纵坐标int fcount=0;//食物的数目//主要函数操作void createfood();//生成食物void PrintgameMap(int x[],int y[]);//画游戏地图void move(int x[],int y[]);//移动蛇int main(){srand(time(NULL));//初始化蛇头和身体的位置,默认刚开始蛇长为2 x[len] = 9;y[len] = 9;len++;x[len] = 9;y[len] = 8;len++;createfood();PrintgameMap(x,y);move(x,y);return 0;}void createfood(){if(0==fcount){int tfx=rand()%18+1;int tfy=rand()%38+1;int i,j;int have=0;//为0表示食物不是食物的一部分for(i=0;i<len;i++){for(j=0;j<len;j++){if(x[i]==fx&&y[j]==fy){have=1;break;}else{have=0;}}if(1==have)//若为蛇的一部分,执行下一次循环{continue;}else//否则生成新的水果{fcount++;fx=tfx;fy=tfy;break;}}}}//游戏地图void PrintgameMap(int x[],int y[]){int snake = 0,food=0;int i, j;//画游戏地图,并画出蛇的初始位置for (i = 0; i < 20; i++){for (j = 0; j < 40; j++){if (i == 0 && j >= 1 && j <= 38){gamemap[i][j] = '=';}else if (i == 19 && j >= 1 && j <= 38){gamemap[i][j] = '=';}else if (j == 0 || j == 39){gamemap[i][j] = '#';}else{gamemap[i][j] = ' ';}//判断蛇是否在当前位置int k;for ( k = 0; k < len; k++){if (i == x[k]&&j == y[k]){snake = 1;break;}else{snake = 0;}}{if(fcount&&fx==i&&fy==j){food=1;}else{food=0;}}//若蛇在当前位置if (1==snake ){printf("*");}else if(1==food){printf("f");}//若蛇不在当前位置并且当前位置没有水果else{printf("%c", gamemap[i][j]);}}printf("\n");}printf("score:%d",score);}//移动void move(int x[],int y[]){char s;s=getch();int move=0,beat=0;while (1){int cx[800];int cy[800];memcpy(cx, x, sizeof(int)*len); memcpy(cy, y, sizeof(int)*len); //头if (s=='w'){x[0]--;move=1;if(x[0]<=0){printf("Game over\n"); break;}}else if (s=='s'){x[0]++;move=1;if(x[0]>=19){printf("Game over\n"); break;}}else if (s=='a'){y[0] --;move=1;if(y[0]<=0){printf("Game over\n");break;}}else if (s=='d'){y[0]++;move=1;if(y[0]>=39){printf("Game over\n");break;}}//身体int i;for ( i = 1; i < len; i++){x[i] = cx[i - 1];y[i] = cy[i - 1];}for(i=1;i<len;i++)//要是咬到了自己{if(x[0]==x[i]&&y[0]==y[i]){beat=1;}else{beat=0;}}if(1==beat){printf("Game over\n");break;}if(1==move){if(fcount&&x[0]==fx&&y[0]==fy)//如果吃到了果子{//拷贝当前蛇头地址到第二个结点memcpy(x+1,cx,sizeof(int)*len); memcpy(y+1,cy,sizeof(int)*len); len++;fcount--;fx=0;fy=0;score++;createfood();}Sleep(70);system("cls");PrintgameMap( x, y);}elsecontinue;if(kbhit())//判断是否按下按键{s=getch();}}}。
贪吃蛇代码
#include<stdio.h>#include<conio.h>#include<time.h>#include<windows.h>int length=1;//蛇的当前长度,初始值为1int line[100][2];//蛇的走的路线int head[2]={40,12};//蛇头int food[2];//食物的位置char direction;//蛇运动方向int x_min=1,x_max=77,y_min=2,y_max=23;//设置蛇的运动区域int tail_before[2]={40,12};//上一个状态的蛇尾char direction_before='s';//上一个状态蛇的运动方向int live_death=1;//死活状态,0死,1活int eat_flag=0;//吃食物与否的状态。
0没吃1吃了int max=0;int delay;//移动延迟时间void gotoxy(int x, int y)//x为列坐标,y为行坐标{COORD pos = {x,y};HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOut, pos);}void hidden()//隐藏光标{HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);CONSOLE_CURSOR_INFO cci;GetConsoleCursorInfo(hOut,&cci);cci.bVisible=0;//赋1为显示,赋0为隐藏SetConsoleCursorInfo(hOut,&cci);}void update_score()//更新分数{gotoxy(2,1);printf("我的分数:%d",length);gotoxy(42,1);printf("最高记录:%d",max);}void create_window(){gotoxy(0,0);printf("╔══════════════════╦═══════════════════╗");prin tf("║ ║ ║");printf("╠══════════════════╩═══════════════════╣");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("╚══════════════════════════════════════╝");}void update_line()//更新蛇的线路{int i;if(eat_flag==0)//吃了食物就不用记住上一个状态的蛇尾,否则会被消掉{tail_before[0]=line[0][0];//记住上一个状态的蛇尾tail_before[1]=line[0][1];for(i=0;i<length-1;i++)//更新蛇头以后部分{line[i][0]=line[i+1][0];line[i][1]=line[i+1][1];}line[length-1][0]=head[0];//更新蛇头line[length-1][1]=head[1];}}void initial()//初始化{FILE *fp;gotoxy(head[0],head[1]);printf("蛇");line[0][0]=head[0];//把蛇头装入路线line[0][1]=head[1];if((fp=fopen("highest","r"))==NULL){fp=fopen("highest","w");fprintf(fp,"%d",0);max=0;fclose(fp);}//第一次使用时,初始化奖最高分为0else{fp=fopen("highest","r");fscanf(fp,"%d",&max);}update_score();}void createfood()//产生食物{int flag,i;srand((unsigned)time(NULL));for(;;){for(;;){food[0]=rand()%(x_max+1);if(food[0]%2==0 && food[0]>x_min)break;}//产生一个偶数横坐标for(;;){food[1]=rand()%(y_max);if(food[1]>y_min)break;}for(i=0,flag=0;i<length;i++)//判断产生的食物是否在蛇身上,在flag=1,否则为0 if(food[0]==line[i][0] && food[1]==line[i][1]){ flag=1; break; }if(flag==0)// 食物不在蛇身上结束循环break;}gotoxy(food[0],food[1]);printf("蛇");}void show_snake(){gotoxy(head[0],head[1]);printf("蛇");if(eat_flag==0)//没吃食物时消去蛇尾{gotoxy(tail_before[0],tail_before[1]);printf(" ");//消除蛇尾}elseeat_flag=0;//吃了食物就回到没吃状态}char different_direction(char dir)//方向{switch(dir){case 'a': return 'd';case 'd': return 'a';case 'w': return 's';case 's': return 'w';}}void get_direction(){direction_before=direction;//记住蛇上一个状态的运动方向while(kbhit()!=0) //调试direction=getch();if( direction_before == different_direction(direction) || (direction!='a' && direction!='s' && direction!='d' && direction!='w') ) //新方向和原方向相反,或获得的方向不是wasd时,保持原方向direction=direction_before;switch(direction){case 'a': head[0]-=2; break;case 'd': head[0]+=2; break;case 'w': head[1]--; break;case 's': head[1]++; break;}}void live_state()//判断蛇的生存状态{FILE *fp;int i,flag;for(i=0,flag=0;i<length-1;i++)//判断是否自己咬到自己if( head[0]==line[i][0] && head[1]==line[i][1]){flag=1;break;}if(head[0]<=x_min || head[0]>=x_max || head[1]<=y_min || head[1]>=y_max || flag==1) {system("cls");//游戏结束create_window();update_score();gotoxy(35,12);printf("游戏结束!\n");Sleep(500);live_death=0;fp=fopen("highest","w");fprintf(fp,"%d",max);//保存最高分}}void eat(){if(head[0]==food[0]&&head[1]==food[1]){length++;line[length-1][0]=head[0];//更新蛇头line[length-1][1]=head[1];eat_flag=1;createfood();if(length>max)max=length;update_score();//if(delay>100)delay-=30;//加速}}main(){int x=0,y=0;int i;hidden();//隐藏光标create_window();initial();createfood();for(direction='s',delay=600;;){get_direction();//得到键盘控制方向eat();//吃食物update_line();//更新路线live_state();//判断生死状态if(live_death==1){show_snake();}elsebreak;Sleep(delay);//暂停}}。
贪吃蛇c语言代码
贪吃蛇c语言代码#include <graphics.h>#include <conio.h>#include <stdlib.h>#include <dos.h>#define NULL 0#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181struct snake{int centerx;int centery;int newx;int newy;struct snake *next;};struct snake *head;int grade=60; /*控制速度的*******/int a,b; /* 背静遮的位置*/void *far1,*far2,*far3,*far4; /* 蛇身指针背静遮的指针虫子*/int size1,size2,size3,size4; /* **全局变量**/int ch=RIGHT; /**************存按键开始蛇的方向为RIGHT***********/int chy=RIGHT;int flag=0; /*********判断是否退出游戏**************/int control=4; /***********判断上次方向和下次方向不冲突***/int nextshow=1; /*******控制下次蛇身是否显示***************/int scenterx; /***************随即矩形中心坐标***************/int scentery;int sx; /*******在a b 未改变前得到他们的值保证随机矩形也不在此出现*******/int sy;/************************蛇身初始化**************************/void snakede(){struct snake *p1,*p2;head=p1=p2=(struct snake *)malloc(sizeof(struct snake));p1->centerx=80;p1->newx=80;p1->centery=58;p1->newy=58;p1=(struct snake *)malloc(sizeof(struct snake));p2->next=p1;p1->centerx=58;p1->newx=58;p1->centery=58;p1->newy=58;p1->next=NULL;}/*******************end*******************/void welcome() /*************游戏开始界面,可以选择速度**********/ {int key;int size;int x=240;int y=300;int f;void *buf;setfillstyle(SOLID_FILL,BLUE);bar(98,100,112,125);setfillstyle(SOLID_FILL,RED);bar(98,112,112,114);setfillstyle(SOLID_FILL,GREEN);bar(100,100,110,125);size=imagesize(98,100,112,125);buf=malloc(size);getimage(98,100,112,125,buf);cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(240,300,390,325);outtextxy(193,310,"speed:");setfillstyle(SOLID_FILL,RED);bar(240,312,390,314);setcolor(YELLOW);outtextxy(240,330,"DOWN");outtextxy(390,330,"UP");outtextxy(240,360,"ENTER to start..." );outtextxy(270,200,"SNAKE");fei(220,220);feiyang(280,220);yang(340,220);putimage(x,y,buf,COPY_PUT);setcolor(RED);rectangle(170,190,410,410);while(1){ if(bioskey(1)) /********8选择速度部分************/ key=bioskey(0);switch(key){case ENTER:f=1;break;case DOWN:if(x>=240){ putimage(x-=2,y,buf,COPY_PUT);grade++;key=0;}case UP:if(x<=375){ putimage(x+=2,y,buf,COPY_PUT);grade--;key=0;break;}}if (f==1)break;} /********** end ****************/ free(buf);}/*************************随即矩形*****************//***********当nextshow 为1的时候才调用此函数**********/void ran(){ int nx;int ny;int show; /**********控制是否显示***********/int jump=0;struct snake *p;p=head;if(nextshow==1) /***********是否开始随机产生***************/{show=1;randomize();nx=random(14);ny=random(14);scenterx=nx*22+58;scentery=ny*22+58;while(p!=NULL){if(scenterx==p->centerx&&scentery==p->centery||scenterx==sx&&scentery==sy) {show=0;jump=1;break;}elsep=p->next;if(jump==1)break;}if(show==1){putimage(scenterx-11,scentery-11,far3,COPY_PUT);nextshow=0;break;}}}/***********过关动画**************/ void donghua(){ int i;cleardevice();setbkcolor(BLACK);randomize();while(1){for(i=0;i<=5;i++){putpixel(random(640),random(80),13); putpixel(random(640),random(80)+80,2); putpixel(random(640),random(80)+160,3); putpixel(random(640),random(80)+240,4); putpixel(random(640),random(80)+320,1); putpixel(random(640),random(80)+400,14); }setcolor(YELLOW);settextstyle(0,0,4);outtextxy(130,200,"Wonderful!!"); setfillstyle(SOLID_FILL,10);bar(240,398,375,420);feiyang(300,400);fei(250,400);yang(350,400);if(bioskey(1))if(bioskey(0)==ESC){flag=1;break;}}}/*************************end************************//***********************初始化图形系统*********************/ void init(){int a=DETECT,b;int i,j;initgraph(&a,&b,"");}/***************************end****************************/ /***画立体边框效果函数******/void tline(int x1,int y1,int x2,int y2,int white,int black){ setcolor(white);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(black);line(x2,y1,x2,y2);line(x1,y2,x2,y2);}/****end*********//*************飞洋标志**********/int feiyang(int x,int y){int feiyang[18][18]={ {0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0}, {0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0},{0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0},{0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,0},{0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0},{0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (feiyang[i][j]==1)putpixel(j+x,i+y,RED);}}/********"飞"字*************/int fei(int x,int y){int fei[18][18]={{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (fei[i][j]==1)putpixel(j+x,i+y,BLUE);}}/*********"洋"字**************/int yang(int x,int y){int yang[18][18]={{0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0},{0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0},{0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0},{0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0},{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (yang[i][j]==1)putpixel(j+x,i+y,BLUE);}}/******************主场景**********************/ int bort(){ int a;setfillstyle(SOLID_FILL,15);bar(49,49,71,71);setfillstyle(SOLID_FILL,BLUE);bar(50,50,70,70);size1=imagesize(49,49,71,71);far1=(void *)malloc(size1);getimage(49,49,71,71,far1);cleardevice();setfillstyle(SOLID_FILL,12);bar(49,49,71,71);size2=imagesize(49,49,71,71);far2=(void *)malloc(size2);getimage(49,49,71,71,far2);setfillstyle(SOLID_FILL,12);bar(49,49,71,71);setfillstyle(SOLID_FILL,GREEN);bar(50,50,70,70);size3=imagesize(49,49,71,71);far3=(void *)malloc(size3);getimage(49,49,71,71,far3);cleardevice(); /*取蛇身节点背景节点虫子节点end*/ setbkcolor(8);setfillstyle(SOLID_FILL,GREEN);bar(21,23,600,450);tline(21,23,600,450,15,8); /***开始游戏场景边框立体效果*******/ tline(23,25,598,448,15,8);tline(45,45,379,379,8,15);tline(43,43,381,381,8,15);tline(390,43,580,430,8,15);tline(392,45,578,428,8,15);tline(412,65,462,85,15,8);tline(410,63,464,87,15,8);tline(410,92,555,390,15,8);tline(412,94,553,388,15,8);tline(431,397,540,420,15,8);tline(429,395,542,422,15,8);tline(46,386,377,428,8,15);tline(44,384,379,430,8,15);setcolor(8);outtextxy(429,109,"press ENTER ");outtextxy(429,129,"---to start"); /*键盘控制说明*/outtextxy(429,169,"press ESC ");outtextxy(429,189,"---to quiet");outtextxy(469,249,"UP");outtextxy(429,289,"LEFT");outtextxy(465,329,"DOWN");outtextxy(509,289,"RIGHT");setcolor(15);outtextxy(425,105,"press ENTER ");outtextxy(425,125,"---to start");outtextxy(425,165,"press ESC ");outtextxy(425,185,"---to quiet");outtextxy(465,245,"UP");outtextxy(425,285,"LEFT");outtextxy(461,325,"DOWN");outtextxy(505,285,"RIGHT"); /*******end*************/ setcolor(8);outtextxy(411,52,"score");outtextxy(514,52,"left");setcolor(15);outtextxy(407,48,"score");outtextxy(510,48,"left");size4=imagesize(409,62,465,88); /****分数框放到内存********/ far4=(void *)malloc(size4);getimage(409,62,465,88,far4);putimage(500,62,far4,COPY_PUT); /*******输出生命框***********/setfillstyle(SOLID_FILL,12);setcolor(RED);outtextxy(415,70,"0"); /***************输入分数为零**********/outtextxy(512,70,"20"); /*************显示还要吃的虫子的数目*********/ bar(46,46,378,378);feiyang(475,400);fei(450,400);yang(500,400);outtextxy(58,390,"mailto:");outtextxy(58,410,"snake game");outtextxy(200,410,"made by yefeng");while(1){ if(bioskey(1))a=bioskey(0);if(a==ENTER)break;}}/******************gameover()******************/void gameover(){ char *p="GAME OVER";int cha;setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,p);while(1){if(bioskey(1))cha=bioskey(0);if(cha==ESC){flag=1;break;}}}/***********显示蛇身**********************/void snakepaint(){struct snake *p1;p1=head;putimage(a-11,b-11,far2,COPY_PUT);while(p1!=NULL){putimage(p1->newx-11,p1->newy-11,far1,COPY_PUT);p1=p1->next;}}/****************end**********************//*********************蛇身刷新变化游戏关键部分*******************/ void snakechange(){struct snake *p1,*p2,*p3,*p4,*p5;int i,j;static int n=0;static int score;static int left=20;char sscore[5];char sleft[1];p2=p1=head;while(p1!=NULL){ p1=p1->next;if(p1->next==NULL){a=p1->newx;b=p1->newy; /************记录最后节点的坐标************/ sx=a;sy=b;}p1->newx=p2->centerx;p1->newy=p2->centery;p2=p1;}p1=head;while(p1!=NULL){p1->centerx=p1->newx;p1->centery=p1->newy;p1=p1->next;}/********判断按键方向*******/if(bioskey(1)){ ch=bioskey(0);if(ch!=RIGHT&&ch!=LEFT&&ch!=UP&&ch!=DOWN&&ch!=ESC) /********chy为上一次的方向*********/ch=chy;}switch(ch){case LEFT: if(control!=4){head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}else{ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}chy=ch;break;case DOWN:if(control!=1){ head->newy=head->newy+22;head->centery=head->newy; control=3;if(head->newy>377)gameover();}else{ head->newy=head->newy-22; head->centery=head->newy;control=1;if(head->newy<47)gameover();}chy=ch;break;case RIGHT: if(control!=2){ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}else{ head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}chy=ch;break;case UP: if(control!=3){ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}else{ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();}chy=ch;break;case ESC:flag=1;break;}/* if 判断是否吃蛇*/if(flag!=1){ if(head->newx==scenterx&&head->newy==scentery){ p3=head;while(p3!=NULL){ p4=p3;p3=p3->next;}p3=(struct snake *)malloc(sizeof(struct snake));p4->next=p3;p3->centerx=a;p3->newx=a;p3->centery=b;p3->newy=b;p3->next=NULL;a=500;b=500;putimage(409,62,far4,COPY_PUT); /********** 分数框挡住**************/ putimage(500,62,far4,COPY_PUT); /*********把以前的剩下虫子的框挡住********/ score=(++n)*100;left--;itoa(score,sscore,10);itoa(left,sleft,10);setcolor(RED);outtextxy(415,70,sscore);outtextxy(512,70,sleft);nextshow=1;if(left==0) /************判断是否过关**********/donghua(); /*******如果过关,播放过关动画*********************/}p5=head; /*********************判断是否自杀***************************/ p5=p5->next;p5=p5->next;p5=p5->next;p5=p5->next; /****从第五个节点判断是否自杀************/while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->centery){ gameover();break;}elsep5=p5->next;}}}/************snakechange()函数结束*******************//*****************************主函数******************************************/ int main(){ int i;init(); /**********初始化图形系统**********/ welcome(); /*********8欢迎界面**************/ bort(); /*********主场景***************/ snakede(); /**********连表初始化**********/ while(1){ snakechange();if(flag==1)break;snakepaint();ran();for(i=0;i<=grade;i++)delay(3000);}free(far1);free(far2);free(far3);free(far4);closegraph();return 0;}。
贪吃蛇源代码
#include <graphics.h>#include <stdlib.h>#include <conio.h>#include <time.h>#include <stdio.h>#define LEFT 'a'#define RIGHT 'd'#define DOWN 's'#define UP 'w'#define ESC 27#define N 200 /*蛇的最大长度*/int i;char key;int score=0; /*得分*/int gamespeed=100; /*游戏速度自己调整*/struct Food{int x; /*食物的横坐标*/int y; /*食物的纵坐标*/int yes; /*判断是否要出现食物的变量*/ }food; /*食物的结构体*/struct Snake{int x[N];int y[N];int node; /*蛇的节数*/int direction; /*蛇移动方向*/int life; /* 蛇的生命,0活着,1死亡*/ }snake;void Init(void); /*图形驱动*/void Close(void); /*图形结束*/void DrawK(void); /*开始画面*/void GameOver(void); /*结束游戏*/void GamePlay(void); /*玩游戏具体过程*/void PrScore(void); /*输出成绩*//*主函数*/void main(void){Init(); /*图形驱动*/DrawK(); /*开始画面*/GamePlay(); /*玩游戏具体过程*/Close(); /*图形结束*/}/*图形驱动*/void Init(void){int gd=9,gm=2;initgraph(&gd,&gm," ");cleardevice();}/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/void DrawK(void){/*setbkcolor(LIGHTGREEN);*/setcolor(LIGHTCYAN);setlinestyle(PS_SOLID,0,1); /*设置线型*/for(i=50;i<=600;i+=10) /*画围墙*/{rectangle(i,40,i+10,49); /*上边*/rectangle(i,451,i+10,460); /*下边*/}for(i=40;i<=450;i+=10){rectangle(50,i,59,i+10); /*左边*/rectangle(601,i,610,i+10); /*右边*/}}/*玩游戏具体过程*/void GamePlay(void){srand(time(NULL)); /*随机数发生器*/food.yes=1; /*1表示需要出现新食物,0表*/ snake.life=0; /*活着*/snake.direction=1; /*方向往右*/snake.x[0]=100;snake.y[0]=100; /*蛇头*/snake.x[1]=110;snake.y[1]=100;snake.node=2; /*节数*/PrScore(); /*输出得分*/while(1) /*可以重复玩游戏,压ESC键*/ {while(!kbhit()) /*在没有按键的情况下,蛇自*/ {if(food.yes==1) /*需要出现新食物*/{food.x=rand()%400+60;food.y=rand()%350+60;while(food.x%10!=0) /*食物随机出现后必须让食物*/ food.x++;while(food.y%10!=0)food.y++;food.yes=0; /*画面上有食物了*/}if(food.yes==0) /*画面上有食物了就要显示*/ {setcolor(GREEN);rectangle(food.x,food.y,food.x+10,food.y-10);}for(i=snake.node-1;i>0;i--) /*蛇的每个环节往前移动,也法/ {snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}/*1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头*/switch(snake.direction){case 1: snake.x[0]+=10;break;case 2: snake.x[0]-=10;break;case 3: snake.y[0]-=10;break;case 4: snake.y[0]+=10;break;}/*从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可*/ for(i=3;i<snake.node;i++){if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){GameOver(); /*显示失败*/snake.life=1;break;}}if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455) /*蛇是否撞到墙壁*/{ GameOver(); /*本次游戏结束*/snake.life=1; /*蛇死*/}if(snake.life==1) /*以上两种判断以后,如果蛇*/ break;if(snake.x[0]==food.x&&snake.y[0]==food.y)/*吃到食物以后*/{setcolor(BLACK); /*把画面上的食物东西去*/ rectangle(food.x,food.y,food.x+10,food.y-10);snake.x[snake.node]=-20;snake.y[snake.node]=-20;/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.node++; /*蛇的身体长一节*/food.yes=1; /*画面上需要出现新的食物*/ score+=10;PrScore(); /*输出新得分*/}setcolor(RED); /*画出蛇*/for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10); Sleep(gamespeed);setcolor(BLACK); /*用黑色去除蛇的的最后*/ rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);} /*endwhile(!kbhit)*/if(snake.life==1) /*如果蛇死就跳出循环*/break;key=getch(); /*接收按键*/if (key == ESC) break; /*按ESC键退出*/switch(key){case UP:if(snake.direction!=4) /*判断是否往相反的方向移动*/ snake.direction=3;break;case RIGHT:if(snake.direction!=2) snake.direction=1; break;case LEFT:if(snake.direction!=1) snake.direction=2; break;case DOWN:if(snake.direction!=3) snake.direction=4; break;}}/*endwhile(1)*/}/*游戏结束*/void GameOver(void){cleardevice();PrScore();setcolor(RED);setfont(56,0,"黑体");outtextxy(200,200,"GAME OVER");getch();}/*输出成绩*/void PrScore(void){char str[10];setfillstyle(YELLOW);bar(50,15,220,35);setcolor(BROWN);setfont(16,0,"宋体");sprintf(str,"score:%d",score);outtextxy(55,16,str);}/*图形结束*/void Close(void){closegraph();}。
C语言贪吃蛇源代码
C语言贪吃蛇源代码 TTA standardization office【TTA 5AB- TTAK 08- TTA 2C】#include<stdio.h>#include<process.h>#include<windows.h>#include<conio.h>#include<time.h>#include<stdlib.h>#define WIDTH 40#define HEIGH 12enum direction{//方向LEFT,RIGHT,UP,DOWN};struct Food{//食物int x;int y;};struct Node{//画蛇身int x;int y;struct Node *next;};struct Snake{//蛇属性int lenth;//长度enum direction dir;//方向};struct Food *food; //食物struct Snake *snake;//蛇属性struct Node *snode,*tail;//蛇身int SPEECH=200;int score=0;//分数int smark=0;//吃食物标记int times=0;int STOP=0;void Initfood();//产生食物void Initsnake();//构造snakevoid Eatfood();//头部前进void Addnode(int x, int y);//增加蛇身void display(struct Node *shead);//显示蛇身坐标void move();//蛇移动void draw();//画蛇void Homepage();//主页void keybordhit();//监控键盘按键void Addtail();//吃到食物void gotoxy(int x, int y)//定位光标{COORD pos;pos.X = x - 1;pos.Y = y - 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void Initsnake()//构造snake{int i;snake=(struct Snake*)malloc(sizeof(struct Snake));tail=(struct Node*)malloc(sizeof(struct Node));food = (struct Food*)malloc(sizeof(struct Food));snake->lenth=5;//初始长度 5snake->dir=RIGHT;//初始蛇头方向右for(i=2;i<=snake->lenth 2;i )//增加 5 个结点{Addnode(i,2);}}void Initfood()//产生食物{struct Node *p=snode;int mark=1;srand((unsigned)time(NULL));//以时间为种子产生随机数while(1){food->x=rand()%(WIDTH-2) 2;//食物X坐标food->y=rand()%(HEIGH-2) 2;//食物Y坐标while(p!=NULL){if((food->x==p->x)&&(food->y==p->y))//如果食物产生在蛇身上{//则重新生成食物mark=0;//食物生成无效break;}p=p->next;if(mark==1)//如果食物不在蛇身上,生成食物,否则重新生成食物{gotoxy(food->x,food->y);printf("%c",3);break;}mark=1;p=snode;}}void move()//移动{struct Node *q, *p=snode;if(snake->dir==RIGHT){Addnode(p->x 1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==LEFT){Addnode(p->x-1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}if(snake->dir==UP){Addnode(p->x,p->y-1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==DOWN){Addnode(p->x,p->y 1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}}void Addnode(int x, int y)//增加蛇身{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;newnode->next=snode;newnode->x=x;newnode->y=y;snode=newnode;//结点加到蛇头if(x<2||x>=WIDTH||y<2||y>=HEIGH)//碰到边界{STOP=1;gotoxy(10,19);printf("撞墙,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}while(p!=NULL)//碰到自身{if(p->next!=NULL)if((p->x==x)&&(p->y==y)){STOP=1;gotoxy(10,19);printf("撞到自身,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}p=p->next;}}void Eatfood()//吃到食物{Addtail();score ;}void Addtail()//增加蛇尾{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;tail->next=newnode;newnode->x=50;newnode->y=20;newnode->next=NULL;//结点加到蛇头tail=newnode;//新的蛇尾}void draw()//画蛇{struct Node *p=snode;int i,j;while(p!=NULL){gotoxy(p->x,p->y);printf("%c",2);tail=p;p=p->next;}if(snode->x==food->x&&snode->y==food->y)//蛇头坐标等于食物坐标{smark=1;Eatfood();//增加结点Initfood();//产生食物}if(smark==0){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点}else{times=1;}if((smark==1)&&(times==1)){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点smark=0;}gotoxy(50,12);printf("食物: %d,%d",food->x,food->y);gotoxy(50,5);printf("分数: %d",score);gotoxy(50,7);printf("速度: %d",SPEECH);gotoxy(15,14);printf("按o键加速");gotoxy(15,15);printf("按p键减速");gotoxy(15,16);printf("按空格键暂停");}void HideCursor()//隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }void Homepage()//绘主页{int x,y;HideCursor();//隐藏光标printf("----------------------------------------\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("----------------------------------------\n");gotoxy(5,13);printf("任意键开始游戏!按W.A.S.D控制方向");_getch();Initsnake();Initfood();gotoxy(5,13);printf(" ");}void keybordhit()//监控键盘{char ch;if(_kbhit()){ch=getch();switch(ch){case 'W':case 'w':if(snake->dir==DOWN)//如果本来方向是下,而按相反方向无效{break;}elsesnake->dir=UP;break;case 'A':case 'a':if(snake->dir==RIGHT)//如果本来方向是右,而按相反方向无效{break;}elsesnake->dir=LEFT;break;case 'S':case 's':if(snake->dir==UP)//如果本来方向是上,而按相反方向无效{break;}elsesnake->dir=DOWN;break;case 'D':case 'd':if(snake->dir==LEFT)//如果本来方向是左,而按相反方向无效{break;}elsesnake->dir=RIGHT;break;case 'O':case 'o':if(SPEECH>=150)//速度加快{SPEECH=SPEECH-50;}break;case 'P':case 'p':if(SPEECH<=400)//速度减慢{SPEECH=SPEECH 50;}break;case ' '://暂停gotoxy(15,18);printf("游戏已暂停,按任意键恢复游戏"); system("pause>nul");gotoxy(15,18);printf(" "); break;default:break;}}}int main(void)//程序入口{Homepage();while(!STOP){keybordhit();//监控键盘按键move();//蛇的坐标变化draw();//蛇的重绘Sleep(SPEECH);//暂时挂起线程}return 0;}。
贪吃蛇游戏代码(C语言编写)
贪吃蛇游戏代码(C语言编写)#include "graphics.h"#include "stdio.h"#define MAX 200#define MAXX 30#define MAXY 30#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181#define PAGEUP 18688#define PAGEDOWN 20736#define KEY_U 5749#define KEY_K 9579#define CTRL_P 6512#define TRUE 1#define FALSE 0#define GAMEINIT 1#define GAMESTART 2#define GAMEHAPPY 3#define GAMEOVER 4struct SPlace{int x;int y;int st;} place[MAX];int speed;int count;int score;int control;int head;int tear;int x,y;int babyx,babyy;int class;int eat;int game;int gamedelay[]={5000,4000,3000,2000,1000,500,250,100}; int gamedelay2[]={1000,1};static int hitme=TRUE,hit = TRUE; void init(void);void nextstatus(void);void draw(void);void init(void){int i;for(i=0;i<max;i++)< p="">{place[i].x = 0;place[i].y = 0;place[i].st = FALSE;}place[0].st = TRUE;place[1].st = TRUE;place[1].x = 1;speed = 9;count = 0;score = 0;control = 4;head = 1;tear = 0;x = 1;y = 0;babyx = rand()%MAXX;babyy = rand()%MAXY;eat = FALSE;game = GAMESTART;}void nextstatus(void){int i;int exit;int xx,yy;xx = x;yy = y;switch(control){case 1: y--; yy = y-1; break;case 2: y++; yy = y+1; break;case 3: x--; xx = x-1; break;case 4: x++; xx = x+1; break;}hit = TRUE;if ( ((control == 1) || (control ==2 )) && ( (y < 1) ||(y >= MAXY-1)) || (((control == 3) || (control == 4)) && ((x < 1) ||(x >= MAXX-1) ) ) ){}if ( (y < 0) ||(y >= MAXY) ||(x < 0) ||(x >= MAXX) ){game = GAMEOVER;control = 0;return;}for (i = 0; i < MAX; i++){if ((place[i].st) &&(x == place[i].x) &&(y == place[i].y) ){game = GAMEOVER;control = 0;return;}if ((place[i].st) &&(xx == place[i].x) &&(yy == place[i].y) ){hit = FALSE;goto OUT;}}OUT:if ( (x == babyx) && (y == babyy) ) {count ++;score += (1+class) * 10;}head ++;if (head >= MAX) head = 0;place[head].x = x;place[head].y = y;place[head].st= TRUE;if (eat == FALSE){place[tear].st = FALSE;tear ++;if (tear >= MAX) tear = 0;}else{eat = FALSE;exit = TRUE;while(exit){babyx = rand()%MAXX;babyy = rand()%MAXY;exit = FALSE;for( i = 0; i< MAX; i++ )if( (place[i].st)&&( place[i].x == babyx) && (place[i].y == babyy))exit ++;}}if (head == tear) game = GAMEHAPPY;}void draw(void){char temp[50];int i,j;for (i = 0; i < MAX; i++ ){setfillstyle(1,9);if (place[i].st)bar(place[i].x*15+1,place[i].y*10+1,place[i].x*15+14,place[i]. y*10+9);}setfillstyle(1,4);bar(babyx*15+1,babyy*10+1,babyx*15+14,babyy*10+9);setcolor(8);setfillstyle(1,8);bar(place[head].x*15+1,place[head].y*10+1,place[head].x*1 5+14,place[head].y*10+9); /* for( i = 0; i <= MAXX; i++ ) line( i*15,0, i*15, 10*MAXY);for( j = 0; j <= MAXY; j++ )line( 0, j*10, 15*MAXX, j*10); */rectangle(0,0,15*MAXX,10*MAXY);sprintf(temp,"Count: %d",count);settextstyle(1,0,2);setcolor(8);outtextxy(512,142,temp);setcolor(11);outtextxy(510,140,temp);sprintf(temp,"1P: %d",score);settextstyle(1,0,2);setcolor(8);outtextxy(512,102,temp); setcolor(12);outtextxy(510,100,temp); sprintf(temp,"Class: %d",class); setcolor(8);outtextxy(512,182,temp); setcolor(11);outtextxy(510,180,temp);}main(){int pause = 0;char temp[50];int d,m;int key;int p;static int keydown = FALSE; int exit = FALSE;int stchange = 0;d = VGA;m = VGAMED;initgraph( &d, &m, "" ); setbkcolor(3);class = 3;init();p = 1;while(!exit){if (kbhit()){key = bioskey(0);switch(key){case UP: if( (control != 2)&& !keydown)control = 1;keydown = TRUE;break;case DOWN: if( (control != 1)&& !keydown)control = 2;keydown = TRUE;break;case LEFT: if( (control != 4)&& !keydown)control = 3;keydown = TRUE;break;case RIGHT: if( (control != 3)&& !keydown)control = 4;keydown = TRUE;break;case ESC: exit = TRUE;break;case ENTER: init();break;case PAGEUP: class --; if (class<0) class = 0; break;case PAGEDOWN: class ++;if (class>7) class = 7; break;case KEY_U: if( ( (control ==1) ||(control ==2))&& !keydown) control = 3;else if(( (control == 3) || (control == 4))&& !keydown)control = 1;keydown = TRUE;break;case KEY_K: if( ( (control ==1) ||(control ==2))&& !keydown) control = 4;else if(( (control == 3) || (control == 4))&& !keydown)control = 2;keydown = TRUE;break;case CTRL_P:pause = 1 - pause; break;}}stchange ++ ;putpixel(0,0,0);if (stchange > gamedelay[class] + gamedelay2[hit]){stchange = 0;keydown = FALSE;p = 1 - p;setactivepage(p);cleardevice();if (!pause)nextstatus();else{settextstyle(1,0,4);setcolor(12);outtextxy(250,100,"PAUSE");}draw();if(game==GAMEOVER){settextstyle(0,0,6);setcolor(8);outtextxy(101,101,"GAME OVER"); setcolor(15);outtextxy(99,99,"GAME OVER"); setcolor(12);outtextxy(100,100,"GAME OVER"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}if(game==GAMEHAPPY){settextstyle(0,0,6);setcolor(12);outtextxy(100,300,"YOU WIN"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}setvisualpage(p);}}closegraph();}</max;i++)<>。
贪吃蛇源代码
#include<stdio.h>#include <stdlib.h>#include <windows.h>#include<time.h>#include <conio.h>struct snake{int x, y;snake *next;};snake *head;static int direction=1;//1,2,3,4分别代表左上右下int food_x, food_y;int foodflag = false;int count = 0;int manu();void init();int gamerun();//游戏开始void move();//移动void printframe();//画界面void paint();//打印蛇身int check();//检测int food();//产生实物int setposition(int x, int y);//设置光标位置int check(){if (head->x == 2 || head->x == 63 || head->y == 1 || head->y == 25) return 0;elsereturn 1;}int food(){srand(unsigned int(time(0)));if (!foodflag){food_x = rand() % 60 + 3;food_y = rand() % 23 + 2;foodflag = true;}setposition(food_x, food_y);printf("*");return 0;}int setposition(int x,int y){HANDLE hOut;hOut = GetStdHandle(STD_OUTPUT_HANDLE);COORD pos = { x-1, y-1 }; /* 光标的起始位(第1列,第3行)0是第1列2是第3行*/SetConsoleCursorPosition(hOut, pos);return 0;}void printframe(){HANDLE consolehwnd;//创建句柄consolehwnd =GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄SetConsoleTextAttribute(consolehwnd, BACKGROUND_GREEN );//设置字体颜色for (int i = 1; i <40;i++){printf(" ");}setposition(1, 25);for (int i = 1; i < 41; i++){printf(" ");}for (int i = 1; i < 25; i++){setposition(1, i);printf(" ");}for (int i = 1; i < 25; i++){setposition(79, i);printf(" ");}for (int i = 1; i < 25;i++){setposition(63, i);printf(" ");}setposition(67, 5);SetConsoleTextAttribute(consolehwnd, 0x07);//设置字体颜色printf("你的分数:%d\n",count);setposition(66, 8);printf("暂停请按回车");}void init(){snake *temp1, *temp2;head = new snake;temp1 = new snake;temp2 = new snake;head->x = 26;head->y = 12;head->next = temp1;temp1->x = 27;temp1->y = 12;temp1->next = temp2;temp2->x = 28;temp2->y = 12;temp2->next = NULL;}void paint(){snake *p;p = head;while (p){setposition(p->x, p->y);printf("*");p = p->next;}}void move(){snake * newHead;newHead = new snake;newHead->next = head;if (direction==1){newHead->x = head->x - 1;newHead->y = head->y;}if (direction == 2){newHead->x = head->x ;newHead->y = head->y-1;}if (direction == 3){newHead->x = head->x +1;newHead->y = head->y;}if (direction == 4){newHead->x = head->x;newHead->y = head->y+1;}head = newHead;}int gamerun(){char c;setposition(30, 13);printf("按任意键开始");_getch();system("cls");printframe();init();while (1){food();paint();if (_kbhit()){c = _getch();if (c ==-32){c = _getch();if (c ==75 && direction != 3){direction = 1;}if (c == 72 && direction != 4){direction = 2;}if (c == 77 && direction != 1){direction = 3;}if (c == 80 && direction != 2){direction = 4;}}if (c==' '){c = _getch();}if ((c == 'a' || c == 'A')&&direction !=3){direction = 1;}if ((c == 'w' || c == 'W')&&direction != 4){direction = 2;}if ((c == 'd' || c == 'D')&&direction != 1){direction = 3;}if ((c == 's' || c == 'S')&&direction != 2){direction = 4;}}move();paint();if (head->x!=food_x||head->y!=food_y) {snake *t;t = head;while (t->next->next){t = t->next;}setposition(t->next->x, t->next->y);printf(" ");delete t->next;t->next = NULL;}else{foodflag = false;count++;HANDLE consolehwnd;//创建句柄consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄setposition(67, 5);SetConsoleTextAttribute(consolehwnd, 0x07);//设置字体颜色printf("你的分数:%d\n", count);}if (!check()){system("cls");setposition(20, 10);printf("你的最终分数为:%d", count);break;}Sleep(200);}return 1;}int main(){gamerun();_getch();return 0;}。
经典游戏贪吃蛇代码(c++编写)
经典游戏贪吃蛇代码(c++编写)/* 头文件 */#include#includeusing namespace std;#ifndef SNAKE_H#define SNAKE_Hclass Cmp{friend class Csnake;int rSign; //横坐标int lSign; //竖坐标public://friend bool isDead(const Cmp& cmp); Cmp(int r,int l){setPoint(r,l);}Cmp(){}void setPoint(int r,int l){rSign=r;lSign=l;}Cmp operator-(const Cmp &m)const{return Cmp(rSign - m.rSign,lSign - m.lSign);}Cmp operator+(const Cmp &m)const{return Cmp(rSign + m.rSign,lSign + m.lSign);}};const int maxSize = 5; //初始蛇身长度class Csnake{Cmp firstSign; //蛇头坐标Cmp secondSign;//蛇颈坐标Cmp lastSign; //蛇尾坐标Cmp nextSign; //预备蛇头int row; //列数int line; //行数int count; //蛇身长度vector<vector > snakeMap;//整个游戏界面queue snakeBody; //蛇身public:int GetDirections()const;char getSymbol(const Cmp& c)const //获取指定坐标点上的字符{return snakeMap[c.lSign][c.rSign];}Csnake(int n) //初始化游戏界面大小{if(n<20)line=20+2;else if(n>30)line = 30 + 2;else line=n+2;row=line*3+2;}bool isDead(const Cmp& cmp){return ( getSymbol(cmp)=='c' || cmp.rSign == row-1 || cmp.rSign== 0 || cmp.lSign == line-1 || cmp.lSign == 0 );}void InitInstance(); //初始化游戏界面bool UpdataGame(); //更新游戏界面void ShowGame(); //显示游戏界面};#endif // SNAKE_H====================================== ==============================/* 类的实现及应用*/#include#include#include#include "snake.h"using namespace std;//测试成功void Csnake::InitInstance(){snakeMap.resize(line); // snakeMap[竖坐标][横坐标]for(int i=0;i{snakeMap[i].resize(row);for(int j=0;j{snakeMap[i][j]=' ';}}for(int m=1;m{//初始蛇身snakeMap[line/2][m]='c';//将蛇身坐标压入队列snakeBody.push(Cmp(m,(line/2)));//snakeBody[横坐标][竖坐标]}//链表头尾firstSign=snakeBody.back();secondSign.setPoint(maxSize-1,line/2);}//测试成功int Csnake::GetDirections()const{if(GetKeyState(VK_UP)<0) return 1; //1表示按下上键if(GetKeyState(VK_DOWN)<0) return 2; //2表示按下下键if(GetKeyState(VK_LEFT)<0) return 3; //3表示按下左键if(GetKeyState(VK_RIGHT)<0)return 4; //4表示按下右键return 0;}bool Csnake::UpdataGame(){//-----------------------------------------------//初始化得分0static int score=0;//获取用户按键信息int choice;choice=GetDirections();cout<<"Total score: "<<score</</score<</vector/随机产生食物所在坐标int r,l;//开始初始已经吃食,产生一个食物static bool eatFood=true;//如果吃了一个,才再出现第2个食物if(eatFood){do{//坐标范围限制在(1,1)到(line-2,row-2)对点矩型之间srand(time(0));r=(rand()%(row-2))+1; //横坐标l=(rand()%(line-2))+1;//竖坐标//如果随机产生的坐标不是蛇身,则可行//否则重新产生坐标if(snakeMap[l][r]!='c'){snakeMap[l][r]='*';}}while (snakeMap[l][r]=='c');}switch (choice){case 1://向上//如果蛇头和社颈的横坐标不相同,执行下面操作if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign-1);//否则,如下在原本方向上继续移动else nextSign=firstSign+(firstSign-secondSign); break;case 2://向下if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign+1);else nextSign=firstSign+(firstSign-secondSign); break;case 3://向左if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign-1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;case 4://向右if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign+1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;default:nextSign=firstSign+(firstSign-secondSign);}//----------------------------------------------------------if(getSymbol(nextSign)!='*' && !isDead(nextSign)) //如果没有碰到食物(且没有死亡的情况下),删除蛇尾,压入新的蛇头{//删除蛇尾lastSign=snakeBody.front();snakeMap[lastSign.lSign][lastSign.rSign]=' ';snakeBody.pop();//更新蛇头secondSign=firstSign;//压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();snakeMap[firstSign.lSign][firstSign.rSign]='c';//没有吃食eatFood=false;return true;}//-----吃食-----else if(getSymbol(nextSign)=='*' && !isDead(nextSign)){secondSign=firstSign;snakeMap[nextSign.lSign][nextSign.rSign]='c';//只压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();eatFood=true;//加分score+=20;return true;}//-----死亡-----else {cout<<"Dead"<<endl;cout<<"your "<<score<}void Csnake::ShowGame(){for(int i=0;i{for(int j=0;jcout<cout<}Sleep(1);system("cls");}======================================================================/*主函数部分 */#include#include "snake.h"#includeusing namespace std;int main(){Csnake s(20);s.InitInstance();//s.ShowGame();int noDead;do{s.ShowGame();noDead=s.UpdataGame();}while (noDead</endl;cout<<"your>);system("pause");return 0;}。
贪吃蛇游戏代码
贪吃蛇游戏代码贪吃蛇是一个经典的小游戏,可以在很多平台和设备上找到。
如果你想自己开发一个贪吃蛇游戏,这里有一个简单的Python版本,使用pygame库。
首先,确保你已经安装了pygame库。
如果没有,可以通过pip来安装:bash复制代码pip install pygame然后,你可以使用以下代码来创建一个简单的贪吃蛇游戏:python复制代码import pygameimport random# 初始化pygamepygame.init()# 颜色定义WHITE = (255, 255, 255)RED = (213, 50, 80)GREEN = (0, 255, 0)BLACK = (0, 0, 0)# 游戏屏幕大小WIDTH, HEIGHT = 640, 480screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("贪吃蛇")# 时钟对象来控制帧速度clock = pygame.time.Clock()# 蛇的初始位置和大小snake = [(5, 5), (6, 5), (7, 5)]snake_dir = (1, 0)# 食物的初始位置food = (10, 10)food_spawn = True# 游戏主循环running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_UP:snake_dir = (0, -1)elif event.key == pygame.K_DOWN:snake_dir = (0, 1)elif event.key == pygame.K_LEFT:snake_dir = (-1, 0)elif event.key == pygame.K_RIGHT:snake_dir = (1, 0)# 检查蛇是否吃到了食物if snake[0] == food:food_spawn = Falseelse:del snake[-1]if food_spawn is False:food = (random.randint(1, (WIDTH // 20)) * 20, random.randint(1, (HEIGHT // 20)) * 20)food_spawn = Truenew_head = ((snake[0][0] + snake_dir[0]) % (WIDTH // 20), (snake[0][1] + snake_dir[1]) % (HEIGHT // 20))snake.insert(0, new_head)# 检查游戏结束条件if snake[0] in snake[1:]:running = False# 清屏screen.fill(BLACK)# 绘制蛇for segment in snake:pygame.draw.rect(screen, GREEN, (segment[0], segment[1], 20, 20))# 绘制食物pygame.draw.rect(screen, RED, (food[0], food[1], 20, 20))# 更新屏幕显示pygame.display.flip()# 控制帧速度clock.tick(10)pygame.quit()这个代码实现了一个基本的贪吃蛇游戏。
贪吃蛇游戏代码
贪吃蛇游戏可以使用Python的pygame库来实现。
以下是一份完整的贪吃蛇游戏代码:```pythonimport pygameimport sysimport random#初始化pygamepygame.init()#设置屏幕尺寸和标题screen_size=(800,600)screen=pygame.display.set_mode(screen_size)pygame.display.set_caption('贪吃蛇')#设置颜色white=(255,255,255)black=(0,0,0)#设置蛇和食物的大小snake_size=20food_size=20#设置速度clock=pygame.time.Clock()speed=10snake_pos=[[100,100],[120,100],[140,100]]snake_speed=[snake_size,0]food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size]food_spawn=True#游戏主循环while True:for event in pygame.event.get():if event.type==pygame.QUIT:pygame.quit()sys.exit()keys=pygame.key.get_pressed()for key in keys:if keys[pygame.K_UP]and snake_speed[1]!=snake_size:snake_speed=[0,-snake_size]if keys[pygame.K_DOWN]and snake_speed[1]!=-snake_size:snake_speed=[0,snake_size]if keys[pygame.K_LEFT]and snake_speed[0]!=snake_size:snake_speed=[-snake_size,0]if keys[pygame.K_RIGHT]and snake_speed[0]!=-snake_size:snake_speed=[snake_size,0]snake_pos[0][0]+=snake_speed[0]snake_pos[0][1]+=snake_speed[1]#碰撞检测if snake_pos[0][0]<0or snake_pos[0][0]>=screen_size[0]or\snake_pos[0][1]<0or snake_pos[0][1]>=screen_size[1]or\snake_pos[0]in snake_pos[1:]:pygame.quit()sys.exit()#蛇吃食物if snake_pos[0]==food_pos:food_spawn=Falseelse:snake_pos.pop()if not food_spawn:food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size] food_spawn=True#绘制screen.fill(black)for pos in snake_pos:pygame.draw.rect(screen,white,pygame.Rect(pos[0],pos[1],snake_size,snake_size)) pygame.draw.rect(screen,white,pygame.Rect(food_pos[0],food_pos[1],food_size, food_size))pygame.display.flip()clock.tick(speed)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。
简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc
简单贪吃蛇c语⾔代码,⼀个C语⾔写简单贪吃蛇源代码.doc ⼀个C语⾔写简单贪吃蛇源代码#include#include#include#include#include#includeint grade=5,point=0,life=3;voidset(),menu(),move_head(),move_body(),move(),init_insect(),left(),upon(),right(),down(),init_graph(),food_f(),ahead(),crate(); struct bug{int x;int y;struct bug *last;struct bug *next;};struct fd{int x;int y;int judge;}food={0,0,0};struct bug *head_f=NULL,*head_l,*p1=NULL,*p2=NULL;void main(){char ch;initgraph(800,600);set();init_insect();while(1){food_f();Sleep(grade*10);setcolor(BLACK);circle(head_l->x,head_l->y,2);setcolor(WHITE);move_body();if(kbhit()){ch=getch();if(ch==27){ahead();set();}else if(ch==-32){switch(getch()){case 72:upon();break;case 80:down();break;case 75:left();break;case 77:right();break;}}else ahead();}else{ahead();}if(head_f->x==food.x&&head_f->y==food.y) {Sleep(100);crate();food.judge=0;point=point+(6-grade)*10;if(food.x<30||food.y<30||food.x>570||food.y>570)life++;menu();}if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) {Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();}for(p1=head_f->next;p1!=NULL;p1=p1->next){if(head_f->x==p1->x&&head_f->y==p1->y){Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();break;}}if(life==0){outtextxy(280,300,"游戏结束!");getch();return;}move();};}void init_graph(){clearviewport();setlinestyle(PS_SOLID,1,5);rectangle(2,2,600,598);setlinestyle(PS_SOLID,1,1);}void set(){init_graph();outtextxy(640,50,"1、开始 / 返回");outtextxy(640,70,"2、退出");outtextxy(640,90,"3、难度");outtextxy(640,110,"4、重新开始");switch(getch()){case '1': menu();setcolor(GREEN);circle(food.x,food.y,2);setcolor(WHITE);return; case '2': exit(0);break;。
C语言简单贪吃蛇游戏代码
#include <stdio.h>#include <stdlib.h>#include <time.h>#include <CONIO.H>#include <AFX.H>intx[10]={0},y[10]={0},xx[20]={0},yy[20]={0},xxx[20],yyy[20],actx=0,acty=1,eggx[10] ={13,2,11},eggy[10]={5,4,4};time_t time1,time2;void eogame(){int i;system("cls");for(i=0;i<10;i++)printf("\n");printf("game over !!");getch();system("exit");}void show(){int i,j,tempx,tempy,max=0,ifget=0;time(&time1);system("cls");for(i=0;i<10;i++){xx[i]=x[i];yy[i]=y[i];}for(i=0;i<10;i++){xx[10+i]=eggx[i];yy[10+i]=eggy[i];}for (j=0;j<19;j++)for (i=0;i<19-j;i++){if (yy[i]>yy[i+1]){tempy=yy[i];yy[i+1]=tempy;tempx=xx[i];xx[i]=xx[i+1];xx[i+1]=tempx;}else if(yy[i]==yy[i+1]&&xx[i]>xx[i+1]){tempx=xx[i];xx[i]=xx[i+1];xx[i+1]=tempx;}}yyy[0]=yy[0];xxx[0]=xx[0];for (i=0;i<19;i++){yyy[i+1]=yy[i+1]-yy[i];if(yy[i+1]==yy[i])xxx[i+1]=xx[i+1]-xx[i];else xxx[i+1]=xx[i+1];}for(i=0;i<20;i++){for(j=0;j<yyy[i];j++)printf("\n");for (j=1;j<xxx[i];j++)printf("");if(xxx[i]>0||yyy[i]>0)printf("@ ");}time(&time2);while(time2-time1<1)time(&time2);for(i=0;i<10;i++)if(x[0]+actx==eggx[i]&&y[0]+acty==eggy[i]){ifget++;eggx[i]=0;eggy[i]=0;} for(i=0;i<9;i++){if(x[i+1]!=0||y[i+1]!=0||ifget!=0){xx[i+1]=x[i];yy[i+1]=y[i];}else {xx[i+1]=0;if(ifget>0)ifget--;x[0]=x[0]+actx;y[0]=y[0]+acty;for(i=1;i<10;i++){x[i]=xx[i];y[i]=yy[i];}if(x[0]==0||x[0]>20||y[0]==0||y[0]>20)eogame();for(i=1;i<10;i++)if(x[0]==x[i]&&y[0]==y[i])eogame();}DWORD WINAPI KEYBOARD(LPVOID IpParam){char key,guard=2,ch; insert:key=getch();if(key==-32)guard=0;else guard++;if(guard==1)switch(key){case 72: actx=0;acty=-1;break;case 80: actx=0;acty=1;break;case 75: actx=-1;acty=0;break;case 77: actx=1;acty=0;break;default:break;}goto insert;}void main(){}x[0]=1;y[0]=1;system("mode con:cols=40 lines=20");CreateThread(NULL,0,KEYBOARD,NULL,0,NULL); while(1)show();。
贪吃蛇游戏小代码
if(i==19) cout << "\tC/C++语言作业:"; if(i==20) cout << "\tzjlj,2015.03.16 "; } }
int main(int argc, char *argv[]){
int tcsQipan[22][22]; // 贪吃蛇棋盘是一个二维数组(如 22*22,包括墙壁)
for(i=1;i<=20;i++)
for(j=1;j<=20;j++)
tcsQipan[i][j]=0; //贪吃蛇棋盘相应坐标标上中间空白部分的标志 0
for(i=0;i<=21;i++)
tcsQipan[0][i] = tcsQipan[21][i] = 1;
//贪吃蛇棋盘相应坐标标上上下墙壁的标志 1
srand(time(0));//设置随机种子
do
{
x1=rand()%20+1;
y1=rand()%20+1;
}
while(tcsQipan[x1][y1]!=0);//如果不是在空白处重新出果子
tcsQipan[x1][y1]=5;//贪吃蛇棋盘相应坐标标上果子的标志 5
color(12);
cout<<"\n\n\t\t\t\t 贪吃蛇游戏即将开始 !"<<endl;//准备开始
if(q[i][j]==5)//输出果子 {
gotoxy(i,j); color(12); cout<<"●"; } } if(i==0) cout << "\t***********************"; if(i==1) cout << "\t 等级为:" << grade;//显示等级 if(i==3) cout << "\t 自动前进时间"; if(i==4) cout << "\t 间隔为:" << gamespeed << "ms";//显示时间
贪吃蛇简易代码
#include<windows.h>#include "resource1.h"#include <stdio.h>#include <stdlib.h>#include <time.h>//蛇的结构体typedef struct SNAKE{int x;int y;struct SNAKE *pNext;}Snake;//豆的结构体typedef struct BEAN{int x;int y;struct BEAN *pNext;}Bean;//函数原型void CreateSnake(Snake **pSnake);void deleteAll(Snake **pSnake);void ShowSnake(Snake *pSnake);void CreateBean(Bean **pBean,Snake *pSnake);void ShowBean(Bean *pBean);void DeleteBean(Bean **pBean);void SnakeRun(Snake **pSnake);void SnakeGrowUp(Snake *pSnake);int CanEatBean(Snake *pSnake,Bean *pBean);int CanDie(Snake *pSnake);/////////////////////////////////////////////////////////////////////////////////////char g_ClassName[20] = "ClassName";LRESULT CALLBACK WndProc(HWND hwnd,UINT nMsg,WPARAM wParam,LPARAM lParam); HBITMAP hBitMap;int CALLBACK WinMain(HINSTANCE hInstance,HINSTANCE hPreInstance,LPSTR pCmdLine,int nCmdShow){HBRUSH hBrush = CreateSolidBrush(RGB(100,100,410));HICON hIcon = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_icon));HICON hIconsm = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_iconsm));hBitMap = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_wdnbitmap));//设计类WNDCLASSEX wndClass;wndClass.cbClsExtra = NULL;wndClass.cbSize = sizeof(wndClass);wndClass.cbWndExtra = NULL;wndClass.hbrBackground = hBrush;wndClass.hCursor = LoadCursor(hInstance,IDC_ARROW);wndClass.hIcon = hIcon;wndClass.hIconSm = hIconsm;wndClass.hInstance = hInstance;wndClass.lpfnWndProc = WndProc;wndClass.lpszClassName = g_ClassName;wndClass.style = CS_HREDRAW|CS_VREDRAW;wndClass.lpszMenuName = NULL;//注册if (!RegisterClassEx(&wndClass)){MessageBox(NULL,"注册失败","消息",MB_OK);}//创建HWND hwnd = CreateWindow(g_ClassName,"贪吃蛇",WS_OVERLAPPEDWINDOW,200,50,600+16,600+38,NULL,NULL,hInstance,NULL);if (!hwnd){MessageBox(NULL,"创建失败!","消息",MB_OK);}//显示ShowWindow(hwnd,nCmdShow);//消息循环MSG msg;while (GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg); //翻译DispatchMessage(&msg); //回调函数}return 0;}HDC dc = NULL;Bean *pBean = NULL;Snake *pSnake = NULL;int VK = VK_RIGHT;LRESULT CALLBACK WndProc(HWND hwnd,UINT nMsg,WPARAM wParam,LPARAM lParam) {switch (nMsg){case WM_CREATE:{CreateSnake(&pSnake); //创建蛇CreateBean(&pBean,pSnake);dc = GetDC(hwnd);}break;case WM_KEYDOWN:{switch (wParam){case VK_RETURN://按下后就开始SetTimer(hwnd,1,150,NULL);break;case VK_UP:VK = VK_UP;break;case VK_DOWN:VK = VK_DOWN;break;case VK_LEFT:VK = VK_LEFT;break;case VK_RIGHT:VK = VK_RIGHT;break;case ' ':KillTimer(hwnd,1);break;}break;}case WM_TIMER:{/*创建背景*/RECT rect;GetWindowRect(hwnd,&rect);HDC hmeDc = CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);DeleteDC(hmeDc);/*背景创建结束*///各种函数if (CanDie(pSnake)){KillTimer(hwnd,1);MessageBox(NULL,"笨蛋,撞到自己身上,我死啦!","消息",MB_OK);}if ( CanEatBean(pSnake,pBean) ){SnakeGrowUp(pSnake);DeleteBean(&pBean);CreateBean(&pBean,pSnake);SnakeRun(&pSnake);}else{SnakeRun(&pSnake);}ShowSnake(pSnake);ShowBean(pBean);}case WM_PAINT:{/*创建背景*/RECT rect;GetWindowRect(hwnd,&rect);HDC hmeDc = CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);/*背景创建结束*/ShowSnake(pSnake); //显示蛇ShowBean(pBean); //显示豆DeleteDC(hmeDc);break;}case WM_CLOSE:deleteAll(&pSnake);DeleteBean(&pBean);DestroyWindow(hwnd);break;case WM_DESTROY:ReleaseDC(hwnd,dc);PostQuitMessage(0);break;case WM_QUIT:break;}return DefWindowProc(hwnd,nMsg,wParam,lParam);}/////////////////////////////////函数/////////////////////////////////////////////////////////////创建蛇Create Snake()void CreateSnake(Snake **pSnake){Snake *u = NULL,*w = NULL;int i = 3; //开始的蛇有三截int x = 0; //蛇头的初始位置int y = 0; //蛇尾的初始位置while (i--){u = (Snake *)malloc(sizeof(Snake));u->pNext = NULL;u->x = x;u->y = y;x +=20;if (NULL == *pSnake){*pSnake = u;}else{w->pNext = u;}w = u;}/*蛇的三届创建完毕*/}//创建豆void CreateBean(Bean **pBean,Snake *pSnake){Snake *ji;int x = 0; //随机的位置x坐标int y = 0; //随机的位置y坐标srand(time(NULL));x = ((unsigned)rand()%29)*20;y = ((unsigned)rand()%29)*20;ji = pSnake;while(pSnake){if ((x == pSnake->x) && (y == pSnake->y) ){x = ((unsigned)rand()%29)*20;y = ((unsigned)rand()%29)*20;pSnake = ji;}pSnake = pSnake->pNext;}Bean *u;u = (Bean *)malloc(sizeof(Bean));u->pNext = NULL;u->x = x;u->y = y;*pBean = u;}//删掉全部蛇void deleteAll(Snake **pSnake){Snake *del;while(*pSnake){del = *pSnake;(*pSnake) = (*pSnake)->pNext;free(del);}}//删掉豆void DeleteBean(Bean **pBean){free(*pBean);*pBean = NULL;}//显示蛇void ShowSnake(Snake *pSnake){while (pSnake){Rectangle(dc,pSnake->x,pSnake->y,pSnake->x+20,pSnake->y+20);pSnake = pSnake->pNext;}}//显示豆void ShowBean(Bean *pBean){Rectangle(dc,pBean->x,pBean->y,pBean->x+20,pBean->y+20);}//贪吃蛇移动void SnakeRun(Snake **pSnake){Snake *ji, //记录变化的蛇头*round; //循环遍历int x, //蛇头的当前位置x坐标y; //蛇头的当前位置y坐标ji = *pSnake;round = *pSnake;while (round->pNext){round = round->pNext;}x = round->x;y = round->y;switch(VK){case VK_UP:if (y == 0){y = 600;}y -=20;break;case VK_DOWN:if (y==600){y = 0;}y +=20;break;case VK_LEFT:if (x == 0){x = 600;}x -= 20;break;case VK_RIGHT:if (x == 600){x = 0;}x +=20;break;}*pSnake = (*pSnake)->pNext;ji->x = x;ji->y = y;ji->pNext = NULL;round->pNext = ji;}//下一步能吃到豆吗? 返回1吃到int CanEatBean(Snake *pSnake,Bean *pBean){while (pSnake->pNext){pSnake = pSnake->pNext;}if ((pSnake->x==pBean->x)&&(pSnake->y==pBean->y)) {return 1;}return 0;}//长大void SnakeGrowUp(Snake *pSnake){Snake *u;u = (Snake *)malloc(sizeof(Snake));u->pNext = NULL;u->x = pBean->x;u->y = pBean->y;while(pSnake->pNext){pSnake = pSnake->pNext;}pSnake->pNext = u;}//蛇会死吗返回1会死int CanDie(Snake *pSnake){Snake *ji = NULL;int x = 0,y = 0;ji = pSnake;while (pSnake->pNext){pSnake = pSnake->pNext;}x = pSnake->x;y = pSnake->y;switch(VK){case VK_UP:y -=20;break;case VK_DOWN:y +=20;break;case VK_LEFT:x -= 20;break;case VK_RIGHT:x +=20;break;}while(ji->pNext){if ((x == ji->x) && (y == ji->y)){return 1;}ji = ji->pNext;}return 0;}(范文素材和资料部分来自网络,供参考。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
贪吃蛇简易代码文件编码(GHTU-UITID-GGBKT-POIU-WUUI-8968)#include<windows.h>#include"resource1.h"#include<stdio.h>#include<stdlib.h>#include<time.h>//蛇的结构体typedefstructSNAKE{intx;inty;structSNAKE*pNext;}Snake;//豆的结构体typedefstructBEAN{intx;inty;structBEAN*pNext;}Bean;//函数原型voidCreateSnake(Snake**pSnake); voiddeleteAll(Snake**pSnake);voidShowSnake(Snake*pSnake);voidCreateBean(Bean**pBean,Snake*pSnake);voidShowBean(Bean*pBean);voidDeleteBean(Bean**pBean);voidSnakeRun(Snake**pSnake);voidSnakeGrowUp(Snake*pSnake);intCanEatBean(Snake*pSnake,Bean*pBean);intCanDie(Snake*pSnake);////////////////////////////////////////////////////////////////////////////// ///////charg_ClassName[20]="ClassName";LRESULTCALLBACKWndProc(HWNDhwnd,UINTnMsg,WPARAMwParam,LPARAMlParam); HBITMAPhBitMap;intCALLBACKWinMain(HINSTANCEhInstance,HINSTANCEhPreInstance,LPSTRpCmdLine,intnCmdShow){HBRUSHhBrush=CreateSolidBrush(RGB(100,100,410));HICONhIcon=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_icon));HICONhIconsm=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_iconsm));hBitMap=LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_wdnbitmap));//设计类WNDCLASSEXwndClass;wndClass.cbClsExtra=NULL;wndClass.cbSize=sizeof(wndClass);wndClass.cbWndExtra=NULL;wndClass.hbrBackground=hBrush;wndClass.hCursor=LoadCursor(hInstance,IDC_ARROW); wndClass.hIcon=hIcon;wndClass.hIconSm=hIconsm;wndClass.hInstance=hInstance;wndClass.lpfnWndProc=WndProc;wndClass.lpszClassName=g_ClassName;wndClass.style=CS_HREDRAW|CS_VREDRAW;wndClass.lpszMenuName=NULL;//注册if(!RegisterClassEx(&wndClass)){MessageBox(NULL,"注册失败","消息",MB_OK);}//创建HWNDhwnd=CreateWindow(g_ClassName,"贪吃蛇",WS_OVERLAPPEDWINDOW,200,50,600+16,600+38,NULL,NULL,hInstance,NULL);if(!hwnd){MessageBox(NULL,"创建失败!","消息",MB_OK);}//显示ShowWindow(hwnd,nCmdShow);//消息循环MSGmsg;while(GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg); //翻译DispatchMessage(&msg); //回调函数}return0;}HDCdc=NULL;Bean*pBean=NULL;Snake*pSnake=NULL;intVK=VK_RIGHT;LRESULTCALLBACKWndProc(HWNDhwnd,UINTnMsg,WPARAMwParam,LPARAMlParam) {switch(nMsg){caseWM_CREATE:{CreateSnake(&pSnake); //创建蛇CreateBean(&pBean,pSnake);dc=GetDC(hwnd);}break;caseWM_KEYDOWN:{switch(wParam){caseVK_RETURN://按下后就开始SetTimer(hwnd,1,150,NULL);break;caseVK_UP:VK=VK_UP;break;caseVK_DOWN:VK=VK_DOWN;break;caseVK_LEFT:VK=VK_LEFT;break;caseVK_RIGHT:VK=VK_RIGHT;break;case'':KillTimer(hwnd,1);break;}break;}caseWM_TIMER:{/*创建背景*/RECTrect;GetWindowRect(hwnd,&rect);HDChmeDc=CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);DeleteDC(hmeDc);/*背景创建结束*///各种函数if(CanDie(pSnake)){KillTimer(hwnd,1);MessageBox(NULL,"笨蛋,撞到自己身上,我死啦!","消息",MB_OK);}if(CanEatBean(pSnake,pBean)){SnakeGrowUp(pSnake);DeleteBean(&pBean);CreateBean(&pBean,pSnake);SnakeRun(&pSnake);}else{SnakeRun(&pSnake);}ShowSnake(pSnake);ShowBean(pBean);}caseWM_PAINT:{/*创建背景*/RECTrect;GetWindowRect(hwnd,&rect);HDChmeDc=CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);/*背景创建结束*/ShowSnake(pSnake); //显示蛇ShowBean(pBean); //显示豆DeleteDC(hmeDc);break;}caseWM_CLOSE:deleteAll(&pSnake);DeleteBean(&pBean);DestroyWindow(hwnd);break;caseWM_DESTROY:ReleaseDC(hwnd,dc);PostQuitMessage(0);break;caseWM_QUIT:break;}returnDefWindowProc(hwnd,nMsg,wParam,lParam);}/////////////////////////////////函数/////////////////////////////////////////////////////////// //创建蛇CreateSnake()voidCreateSnake(Snake**pSnake){Snake*u=NULL,*w=NULL;inti=3; //开始的蛇有三截intx=0; //蛇头的初始位置inty=0; //蛇尾的初始位置while(i--){u=(Snake*)malloc(sizeof(Snake));u->pNext=NULL;u->x=x;u->y=y;x+=20;if(NULL==*pSnake){*pSnake=u;}else{w->pNext=u;}w=u;}/*蛇的三届创建完毕*/}//创建豆voidCreateBean(Bean**pBean,Snake*pSnake) {Snake*ji;intx=0; //随机的位置x坐标inty=0; //随机的位置y坐标srand(time(NULL));x=((unsigned)rand()%29)*20;y=((unsigned)rand()%29)*20;ji=pSnake;while(pSnake){if((x==pSnake->x)&&(y==pSnake->y)){x=((unsigned)rand()%29)*20;y=((unsigned)rand()%29)*20;pSnake=ji;}pSnake=pSnake->pNext;}Bean*u;u=(Bean*)malloc(sizeof(Bean));u->pNext=NULL;u->x=x;u->y=y;*pBean=u;}//删掉全部蛇voiddeleteAll(Snake**pSnake){Snake*del;while(*pSnake){del=*pSnake;(*pSnake)=(*pSnake)->pNext;free(del);}}//删掉豆voidDeleteBean(Bean**pBean){free(*pBean);*pBean=NULL;}//显示蛇voidShowSnake(Snake*pSnake){while(pSnake){Rectangle(dc,pSnake->x,pSnake->y,pSnake->x+20,pSnake->y+20);pSnake=pSnake->pNext;}}//显示豆voidShowBean(Bean*pBean){Rectangle(dc,pBean->x,pBean->y,pBean->x+20,pBean->y+20); }//贪吃蛇移动voidSnakeRun(Snake**pSnake){Snake*ji, //记录变化的蛇头*round; //循环遍历intx, //蛇头的当前位置x坐标y; //蛇头的当前位置y坐标ji=*pSnake;round=*pSnake;while(round->pNext){round=round->pNext;}x=round->x;y=round->y;switch(VK){caseVK_UP:if(y==0)y=600;}y-=20;break; caseVK_DOWN:if(y==600){y=0;}y+=20;break; caseVK_LEFT:if(x==0){x=600;}x-=20;break; caseVK_RIGHT:if(x==600){x=0;x+=20;break;}*pSnake=(*pSnake)->pNext;ji->x=x;ji->y=y;ji->pNext=NULL;round->pNext=ji;}//下一步能吃到豆吗?返回1吃到intCanEatBean(Snake*pSnake,Bean*pBean){while(pSnake->pNext){pSnake=pSnake->pNext;}if((pSnake->x==pBean->x)&&(pSnake->y==pBean->y)){return1;}return0;}//长大voidSnakeGrowUp(Snake*pSnake){Snake*u;u=(Snake*)malloc(sizeof(Snake));u->pNext=NULL;u->x=pBean->x;u->y=pBean->y;while(pSnake->pNext){pSnake=pSnake->pNext;}pSnake->pNext=u;}//蛇会死吗返回1会死intCanDie(Snake*pSnake){Snake*ji=NULL;intx=0,y=0;ji=pSnake;while(pSnake->pNext){pSnake=pSnake->pNext;}x=pSnake->x;y=pSnake->y;switch(VK){caseVK_UP:y-=20;break;caseVK_DOWN:y+=20;break;caseVK_LEFT:x-=20;break;caseVK_RIGHT:x+=20;break;}while(ji->pNext){if((x==ji->x)&&(y==ji->y)){return1;}ji=ji->pNext;}return0;}。