贪吃蛇代码详解

合集下载

贪吃蛇大作战单人版完整代码以及详细解释

贪吃蛇大作战单人版完整代码以及详细解释

贪吃蛇⼤作战单⼈版完整代码以及详细解释贪吃蛇总结:1. 创建WPF应⽤程序2. 添加Canvas标签。

Name=back;3. 添加loaded事件4. 在loaded事件中创建蛇(设置蛇的位置,⼤⼩,颜⾊)this.Left = 0;this.Top = 0;this.Width = 800;this.Height = 600;for (int i = 0; i < 5; i++){bd = new Border();bd.Width = bd.Height = 10;bd.CornerRadius = new CornerRadius(5);if (i == 0)bd.Background = Brushes.Red;elsebd.Background = Brushes.Black;Canvas.SetTop(bd,200+i*bd.Height);Canvas.SetLeft(bd,200);back.Children.Add(bd);snake.Add(bd);5. 添加⼀个timer,(问题:添加timer和winform程序中不⼀样Winform 程序中直接添加。

WPF应⽤程序中不能直接添加,需要引⼊命名空间:Using System.Thearing)DispatcherTimer tm1 = new DispatcherTimer();tm1.Interval =TimeSpan.FromMilliseconds(200);tm1.Tick += Tm1_Tick;tm1.Start();this.KeyDown += MainWindow_KeyDown;6. 添加键盘事件,读取键盘敲下的字符if (e.Key==Key.Up&&str!="d" ){str = "up";}if (e.Key==Key.Down&&str!="up"){str = "d";[csharp]1.{str = "l";}if (e.Key == Key.Right&&str!="l"){str = "r";}7.在timer事件中实现蛇的移动(问题:在实现向左移动时出现错误解决:添加⼀个集合,来存储蛇的位置信息,与此同时添加⼀个border储存位置信息border)//创建蛇的位置集合List<Border> snakeback =new List<Border>();//创建蛇的位置borderBorder bdback = new Border();bdback.Height = bdback.Width = 10;Canvas.SetTop(bdback, 200 + i * bd.Height);Canvas.SetLeft(bdback, 200);snakeback.Add(bdback);if (str == "up"){Canvas.SetTop(snake[0],Canvas.GetTop(snake[0]) - snake[0].Height);run();}if (str=="d"){Canvas.SetTop(snake[0],Canvas.GetTop(snake[0])+ snake[0].Height);run();}if (str == "l"){Canvas.SetLeft(snake[0],Canvas.GetLeft(snake[0]) - snake[0].Height);run();}if (str == "r"){Canvas.SetLeft(snake[0],Canvas.GetLeft(snake[0]) + snake[0].Height);run();}private void run(){for (int i = 1; i < snake.Count; i++){Canvas.SetTop(snake[i],Canvas.GetTop(snakeback[i - 1]));Canvas.SetLeft(snake[i],Canvas.GetLeft(snakeback[i - 1]));}for (int i = 0; i < snake.Count; i++){Canvas.SetTop(snakeback[i],Canvas.GetTop(snake[i]));Canvas.SetLeft(snakeback[i],Canvas.GetLeft(snake[i]));}}8. 判断与⾷物相撞时,⾷物改变位置if (Canvas.GetTop(snake[0])==Canvas.GetTop(food)&&Canvas.GetLeft(snake[0])==Canvas.GetLeft(food)) {Canvas.SetTop(food, ra.Next(60) * 10);Canvas.SetLeft(food, ra.Next(80) * 10);}9. 在与⾷物相撞时添加⼀节蛇尾10. 添加⼀个border来作为蛇尾,添加到snake集合中11. 添加⼀个border存储所增加的蛇尾的位置信息if (Canvas.GetTop(snake[0])==Canvas.GetTop(food)&&Canvas.GetLeft(snake[0])==Canvas.GetLeft(food)) {Canvas.SetTop(food, ra.Next(60) * 10);Canvas.SetLeft(food, ra.Next(80) * 10);//定义⼀个增加的蛇尾的borderBorder bdfood = new Border();bdfood.Height = bdfood.Width = 10;bdfood.CornerRadius = new CornerRadius(5);bdfood.Background = Brushes.Azure;Canvas.SetTop(bdfood,Canvas.GetTop(snake[snake.Count-1]));Canvas.SetLeft(bdfood,Canvas.GetLeft(snake[snake.Count - 1]));back.Children.Add(bdfood);snake.Add(bdfood);//定义⼀个border存储增加的的集合Border br = new Border();br.Height = br.Width = 10;Canvas.SetTop(br, Canvas.GetTop(snakeback[snakeback.Count - 1]));Canvas.SetLeft(br, Canvas.GetLeft(snakeback[snakeback.Count - 1]));snakeback.Add(br);}12.判断蛇与⾯板四周相撞或者蛇撞到⾃⼰,游戏结束。

C语言小游戏源代码《贪吃蛇》

C语言小游戏源代码《贪吃蛇》
void main(void){/*主函数体,调用以下四个函数*/ init(); setbkcolor(7); drawk(); gameplay(); close(); }
void init(void){/*构建图形驱动函数*/ int gd=DETECT,gm; initgraph(&gd,&gm,""); cleardevice(); }
欢迎您阅读该资料希望该资料能给您的学习和生活带来帮助如果您还了解更多的相关知识也欢迎您分享出来让我们大家能共同进步共同成长
C 语言小游戏源代码《贪吃பைடு நூலகம்》
#define N 200/*定义全局常量*/ #define m 25 #include <graphics.h> #include <math.h> #include <stdlib.h> #include <dos.h> #define LEFT 0x4b00 #define RIGHT 0x4d00 #define DOWN 0x5000 #define UP 0x4800 #define Esc 0x011b int i,j,key,k; struct Food/*构造食物结构体*/ { int x; int y; int yes; }food; struct Goods/*构造宝贝结构体*/ { int x; int y; int yes; }goods; struct Block/*构造障碍物结构体*/ { int x[m]; int y[m]; int yes; }block; struct Snake{/*构造蛇结构体*/ int x[N]; int y[N]; int node; int direction; int life; }snake; struct Game/*构建游戏级别参数体*/ { int score; int level; int speed;

C语言贪吃蛇全部程序及说明Word版

C语言贪吃蛇全部程序及说明Word版

#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <string.h>#include <time.h>const int H = 8; //地图的高const int L = 16; //地图的长char GameMap[H][L]; //游戏地图int key; //按键保存int sum = 1, over = 0; //蛇的长度, 游戏结束(自吃或碰墙)int dx[4] = {0, 0, -1, 1}; //左、右、上、下的方向int dy[4] = {-1, 1, 0, 0};struct Snake //蛇的每个节点的数据类型{int x, y; //左边位置int now; //保存当前节点的方向, 0,1,2,3分别为左右上下}Snake[H*L];const char Shead = '@'; //蛇头const char Sbody = '#'; //蛇身const char Sfood = '*'; //食物const char Snode = '.'; //'.'在地图上标示为空void Initial(); //地图的初始化void Create_Food(); //在地图上随机产生食物void Show(); //刷新显示地图void Button(); //取出按键,并判断方向void Move(); //蛇的移动void Check_Border(); //检查蛇头是否越界void Check_Head(int x, int y); //检查蛇头移动后的位置情况int main(){Initial();Show();return 0;}void Initial() //地图的初始化{int i, j;int hx, hy;system("title 贪吃蛇"); //控制台的标题memset(GameMap, '.', sizeof(GameMap)); //初始化地图全部为空'.' system("cls");srand(time(0)); //随机种子hx = rand()%H; //产生蛇头hy = rand()%L;GameMap[hx][hy] = Shead;Snake[0].x = hx; Snake[0].y = hy;Snake[0].now = -1;Create_Food(); //随机产生食物for(i = 0; i < H; i++) //地图显示{for(j = 0; j < L; j++)printf("%c", GameMap[i][j]);printf("\n");}printf("\n小小C语言贪吃蛇\n");printf("按任意方向键开始游戏\n");getch(); //先接受一个按键,使蛇开始往该方向走Button(); //取出按键,并判断方向}void Create_Food() //在地图上随机产生食物{int fx, fy;while(1){fx = rand()%H;fy = rand()%L;if(GameMap[fx][fy] == '.') //不能出现在蛇所占有的位置{GameMap[fx][fy] = Sfood;break;}}}void Show() //刷新显示地图{int i, j;while(1){_sleep(500); //延迟半秒(1000为1s),即每半秒刷新一次地图Button(); //先判断按键在移动Move();if(over) //自吃或碰墙即游戏结束{printf("\n**游戏结束**\n");printf("你的得分:%d\n",sum=10*(sum-1));getchar();break;}system("cls"); //清空地图再显示刷新吼的地图for(i = 0; i < H; i++){for(j = 0; j < L; j++)printf("%c", GameMap[i][j]);printf("\n");}printf("\n小小C语言贪吃蛇\n");printf("按任意方向键开始游戏\n");}}void Button() //取出按键,并判断方向{if(kbhit() != 0) //检查当前是否有键盘输入,若有则返回一个非0值,否则返回0 {while(kbhit() != 0) //可能存在多个按键,要全部取完,以最后一个为主key = getch(); //将按键从控制台中取出并保存到key中switch(key){ //左case 75: Snake[0].now = 0;break;//右case 77: Snake[0].now = 1;break;//上case 72: Snake[0].now = 2;break;//下case 80: Snake[0].now = 3;break;}}}void Move() //蛇的移动{int i, x, y;int t = sum; //保存当前蛇的长度//记录当前蛇头的位置,并设置为空,蛇头先移动x = Snake[0].x; y = Snake[0].y; GameMap[x][y] = '.';Snake[0].x = Snake[0].x + dx[ Snake[0].now ];Snake[0].y = Snake[0].y + dy[ Snake[0].now ];Check_Border(); //蛇头是否越界Check_Head(x, y); //蛇头移动后的位置情况,参数为: 蛇头的开始位置if(sum == t) //未吃到食物即蛇身移动哦for(i = 1; i < sum; i++) //要从蛇尾节点向前移动哦,前一个节点作为参照{if(i == 1) //尾节点设置为空再移动GameMap[ Snake[i].x ][ Snake[i].y ] = '.';if(i == sum-1) //为蛇头后面的蛇身节点,特殊处理{Snake[i].x = x;Snake[i].y = y;Snake[i].now = Snake[0].now;}else //其他蛇身即走到前一个蛇身位置{Snake[i].x = Snake[i+1].x;Snake[i].y = Snake[i+1].y;Snake[i].now = Snake[i+1].now;}GameMap[ Snake[i].x ][ Snake[i].y ] = '#'; //移动后要置为'#'蛇身}}void Check_Border() //检查蛇头是否越界{if(Snake[0].x < 0 || Snake[0].x >= H|| Snake[0].y < 0 || Snake[0].y >= L)over = 1;}void Check_Head(int x, int y) //检查蛇头移动后的位置情况{if(GameMap[ Snake[0].x ][ Snake[0].y ] == '.') //为空GameMap[ Snake[0].x ][ Snake[0].y ] = '@';elseif(GameMap[ Snake[0].x ][ Snake[0].y ] == '*') //为食物{GameMap[ Snake[0].x ][ Snake[0].y ] = '@';Snake[sum].x = x; //新增加的蛇身为蛇头后面的那个Snake[sum].y = y;Snake[sum].now = Snake[0].now;GameMap[ Snake[sum].x ][ Snake[sum].y ] = '#';sum++;Create_Food(); //食物吃完了马上再产生一个食物}elseover = 1;}。

贪吃蛇(HTML小游戏使用JavaScript开发)

贪吃蛇(HTML小游戏使用JavaScript开发)

贪吃蛇(HTML小游戏使用JavaScript开发)贪吃蛇:HTML小游戏使用JavaScript开发在游戏界,贪吃蛇是非常经典和受欢迎的一款小游戏。

它的简单和上瘾性使得无数玩家沉迷其中。

今天,我们将学习如何使用HTML和JavaScript来开发一个贪吃蛇的小游戏。

一、游戏的基本思路贪吃蛇的游戏规则非常简单明了。

玩家控制蛇的移动,通过吃食物来不断增长蛇的长度。

当蛇碰到墙壁或者自己的身体时,游戏结束。

游戏的目标是使蛇长得尽可能长,挑战自己的最高得分。

二、HTML布局首先,我们需要在HTML文件中创建游戏画布。

这个画布将用于显示游戏的界面。

我们可以通过HTML的"canvas"元素来实现。

```html<!DOCTYPE html><html><head><title>贪吃蛇</title><style>#gameCanvas {border: 1px solid black;}</style></head><body><canvas id="gameCanvas" width="400" height="400"></canvas><script>// 在这里编写JavaScript代码</script></body></html>```上面的代码中,我们创建了一个宽高为400像素的画布,并给它设置了一个边框。

三、JavaScript逻辑接下来,我们需要使用JavaScript来实现游戏的逻辑。

我们将使用一个JavaScript类来表示贪吃蛇,并在其中实现移动、吃食物等功能。

```javascript<script>class SnakeGame {constructor(canvasId) {this.canvas = document.getElementById(canvasId);this.context = this.canvas.getContext("2d");this.snake = new Snake();this.food = new Food();// 在这里添加事件监听器,监听用户的方向键输入this.gameLoop();}// 游戏主循环gameLoop() {// 清空画布this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); // 更新蛇的位置this.snake.update();// 绘制蛇和食物this.snake.draw(this.context);this.food.draw(this.context);// 在下一帧时再次调用游戏主循环requestAnimationFrame(() => this.gameLoop()); }}class Snake {constructor() {// 在这里初始化蛇的位置和长度等信息}update() {// 在这里更新蛇的位置和长度等信息}draw(context) {// 在这里使用context绘制蛇的形状}}class Food {constructor() {// 在这里初始化食物的位置等信息}draw(context) {// 在这里使用context绘制食物的形状}}// 创建一个名为"game"的SnakeGame实例const game = new SnakeGame("gameCanvas");</script>```在上面的代码中,我们创建了一个`SnakeGame`类来表示游戏,`Snake`类来表示蛇,和`Food`类来表示食物。

Python实现的贪吃蛇小游戏代码

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语言代码编写

超简单贪吃蛇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;}。

贪吃蛇游戏代码+备注解释

贪吃蛇游戏代码+备注解释
#define N 200
#include "graphics.h"
#include "stdio.h"
#include "stdlib.h"
#include "dos.h"
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
if(snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])
{
GameOver();/*显示失败*/
snake.life = 1;
rectangle(food.x, food.y, food.x+10, food.y-10);
}
for( i=snake.node-1; i>0; i--)
/*蛇的每个环节往前移动,也就是贪食蛇的关键算法*/
case 3: cor=8;break;
default: break;
}
}
/*图形驱动*/
void Init()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "c\\tc");
cleardevice();
}food;/*食物的结构体*/
struct Snake
{
int x[N], y[N];
int node, direction, life;/*蛇的节数 蛇的移动方向 蛇的生命,0 活着,1 死亡*/
}snake;

c语言贪吃蛇

c语言贪吃蛇

c语言贪吃蛇本文实例为大家分享了C语言实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下:用指针数组来表示蛇,p[0]表示蛇头控制方向:w,s,a,d-->上下左右 j,k-->加速、减速键盘控制需要用到线程代码:#include <stdio.h>#include <pthread.h>#include <stdlib.h>#include <time.h>#include <unistd.h>#define X 20#define Y 40char head='@';//蛇头的形状char body='O';//蛇身的形状char a[X][Y]={'O','O','O','@'};char *p[X*Y]={&a[0][3],&a[0][2],&a[0][1],&a[0][0]};//p[0]表示蛇头int n=3; //蛇身的长度(不带蛇头)int i,j;int f=1; //标志位:1.右;2.上;3.左;4.下;-1.退出int us=200000;//用于usleep,延时0.2秒void right(){*p[n]=0;for(i=n;i>0;i--){p[i]=p[i-1];}*p[0]=body;p[0]=p[0]+1;//蛇头向右移*p[0]=head;}void left(){*p[n]=0;for(i=n;i>0;i--) {p[i]=p[i-1];}*p[0]=body;p[0]=p[0]-1;*p[0]=head;}void down(){*p[n]=0;for(i=n;i>0;i--) {p[i]=p[i-1];}*p[0]=body;p[0]=p[0]+Y;*p[0]=head;}void up(){*p[n]=0;for(i=n;i>0;i--) {p[i]=p[i-1];}*p[0]=body;p[0]=p[0]-Y;*p[0]=head;}void show(){system("clear"); for(i=0;i<Y;i++) printf("-"); printf("\n");for(i=0;i<X;i++){for(j=0;j<Y;j++){if(a[i][j]==0)printf(" ");elseprintf("%c",a[i][j]);}printf("\n");}for(i=0;i<Y;i++)printf("-");printf("\nw,s,a,d->上下左右;j,k->加减速;ESC退出\n"); }int ran()//随机数生成*{srand(time(NULL));lb:i=rand()%X;j=rand()%Y;//随机位置的值为0,则产生*;否则继续找随机位置if(a[i][j]==0)a[i][j]='*';elsegoto lb;}void eat(){if(f==1)//右{if(*(p[0]+1)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}if(f==2)//上{if(*(p[0]-Y)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}if(f==3)//左{if(*(p[0]-1)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}if(f==4)//下{if(*(p[0]+Y)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}}void fail(){if(p[0]<&a[0][0]||p[0]>&a[X-1][Y-1])//蛇头不在矩阵内{printf("fail!\n");f=-1;}if(f==1)//右{for(i=n;i>0;i--){if((p[0]+1)==p[i])//右边是自己的身体{printf("fail!\n");f=-1;}}}if(f==2)//上{for(i=n;i>0;i--){if((p[0]-Y)==p[i])//上边是自己的身体{printf("fail!\n");f=-1;}}}if(f==3)//左{for(i=n;i>0;i--){if((p[0]-1)==p[i])//左边是自己的身体{printf("fail!\n");f=-1;}}}if(f==4)//下{for(i=n;i>0;i--){if((p[0]+Y)==p[i])//下边是自己的身体{printf("fail!\n");f=-1;}}}}void *key(void *arg)//控制方向:w,s,a,d-->上下左右{char k;while(1){k=getchar();if(k=='w')//上f=2;if(k=='s')//下f=4;if(k=='a')//左f=3;if(k=='d')//右f=1;if(k=='j')//加速us=us*4/5;if(k=='k')//减速us=us*5/4;if(k==27)//ESC{printf("退出!\n");f=-1;}usleep(100);}}int main(){system("stty -icanon");//关闭缓冲区,输入字符无需回车直接接受pthread_t pid;pthread_create(&pid , NULL , key , NULL);//创建线程,键盘控制ran();while(1){show(); //显示usleep(us);fail(); //判断是否会咬到自己eat(); //判断是否能吃到*if(f==1)//右right();if(f==2)//上up();if(f==3)//左left();if(f==4)//下down();if(f==-1)//退出{pthread_cancel(pid);//关闭线程return -1;}}return 0; }。

贪吃蛇代码详解

贪吃蛇代码详解

//蛇类packa‎ge TanCh‎iShe;impor‎t java.awt.Color‎;impor‎t java.awt.Graph‎ics;impor‎t java.util.HashS‎e t;impor‎t java.util.Linke‎d List‎;impor‎t java.util.Rando‎m;impor‎t java.util.Set;publi‎c class‎Snake‎{//因为常量与‎蛇有关,所以定义在‎蛇的类里面‎publi‎c stati‎c final‎ int UP=1;publi‎c stati‎c final‎ int DOWN=-1;publi‎c stati‎c final‎ int LEFT=2;publi‎c stati‎c final‎ int RIGHT‎=-2;priva‎t e int oldDi‎r ecti‎o n,newDi‎r ecti‎o n;priva‎t e Point‎oldTa‎il;publi‎c stati‎c boole‎an life;//Linke‎d List‎有getF‎irst(),getLa‎s t()和remo‎v eLas‎t()的方法priva‎t e Linke‎d List‎<Point‎> body=new Linke‎d List‎<Point‎>();priva‎t e Set<Snake‎Liste‎n er> liste‎n ers=new HashS‎e t<Snake‎L iste‎n er>();publi‎c Snake‎(){init();}publi‎c void init(){int x=Globa‎l.WIDTH‎/2;int y=Globa‎l.HIGHT‎/2;for(int i=0;i<3;i++){body.addLa‎s t(new Point‎(x--,y));}life=true;oldDi‎r e cti‎o n=newDi‎r ecti‎o n=RIGHT‎;}publi‎c void move(){Syste‎m.out.print‎ln("Snake‎'s move");//如果老方向‎与新方向方‎向相反,则把新方向‎赋值给老方‎向if(!(newDi‎r ecti‎o n+oldDi‎r ecti‎o n==0)){oldDi‎r e cti‎o n=newDi‎r ecti‎o n;}//1.去尾巴oldTa‎il=body.remov‎e Last‎();//得到现在蛇‎头的坐标向上y-1,下y+1,左x-1,右x+1int x=body.getFi‎r st().x;int y=body.getFi‎r st().y;//用老方向判‎断switc‎h(oldDi‎r ecti‎o n){case UP:y--;if(y<0){y=Globa‎l.HIGHT‎-1;}break‎;case DOWN:if(y>Globa‎l.HIGHT‎){y=0;}y++;break‎;case LEFT:if(x<0){x=Globa‎l.WIDTH‎-1;}x--;break‎;case RIGHT‎:if(x>Globa‎l.HIGHT‎){x=0;}x++;break‎;}Point‎newHe‎a d=new Point‎(x,y);//2.加头body.addFi‎r st(newHe‎a d);}//获得蛇头的‎坐标publi‎c Point‎getHe‎a d(){retur‎n body.getFi‎r st();}//把按的方向‎赋值给ne‎w Dire‎c tion‎publi‎c void chang‎e Dire‎c tion‎(int direc‎t ion){Syste‎m.out.print‎ln("Snake‎'s chang‎e Dire‎c iton‎");newDi‎r ecti‎o n=direc‎t ion;}//蛇吃到食物‎,就是把老尾‎巴加上publi‎c void eatFo‎od(){Syste‎m.out.print‎ln("Snake‎'s eatFo‎od");body.addLa‎s t(oldTa‎il);}//蛇吃到自己‎,就是蛇头和‎身体坐标重‎复publi‎c boole‎a n isEat‎Body(){Syste‎m.out.print‎ln("Snake‎'s isEat‎Body");for(int i=1;i<body.size();i++){//i=1,是把蛇头的‎坐标去掉if(body.get(i).equal‎s(body.getFi‎r st())){retur‎n true;}}retur‎n false‎;}publi‎c void drawM‎e(Graph‎ics g){g.setCo‎lor(Color‎.RED);Syste‎m.out.print‎ln("Snaek‎'s drawM‎e");for(Point‎p:body){g.fill3‎DRect‎(p.x*Globa‎l.CELL_‎S IZE, p.y*Globa‎l.CELL_‎S IZE, Globa‎l.CELL_‎S IZE, Globa‎l.CELL_‎S IZE, true);}}priva‎t e class‎Snake‎Drive‎r imple‎m ents‎ Runna‎b le{/*线程*/// TODO Auto-gener‎a ted metho‎d stubwhile‎(life){move();//不停的调用‎m ove的‎方法/*循环所有的‎监听器*/for(Snake‎L iste‎n er l:liste‎n ers){//依次调用所‎有的元素l.snake‎Moved‎(Snake‎.this);//依次调用s‎n akeM‎o ved的‎方法}try {Threa‎d.sleep‎(300);//睡眠1秒既是1秒move一‎次} catch‎(Inter‎r upte‎d Exce‎p tion‎e) {// TODO Auto-gener‎a ted catch‎block‎e.print‎S tack‎T r ace‎();}}}}//蛇死的方法‎void die(){life=false‎;}priva‎t e int [][] rocks‎=new int[Globa‎l.WIDTH‎] [Globa‎l.HIGHT‎];//得到一个随‎机的食物坐‎标publi‎c Point‎getPo‎int(){for(int x=0;x<Globa‎l.WIDTH‎;x++){for(int y=0;y<Globa‎l.HIGHT‎;y++){rocks‎[x][0]=1;rocks‎[x][Globa‎l.HIGHT‎-1]=1;rocks‎[0][y]=1;rocks‎[Globa‎l.WIDTH‎-1][y]=1;}}Rando‎m rando‎m=new Rando‎m();int x=0; int y=0;for(int i=0;i<body.size();i++){do{x=rando‎m.nextI‎n t(Globa‎l.WIDTH‎);y=rando‎m.nextI‎n t(Globa‎l.HIGHT‎);}while‎(rocks‎[x][y]==1||(x==body.get(i).x&&y==body.get(i).y));}retur‎n new Point‎(x,y);//必须加ne‎w不然报错}//启动线程的‎方法new Threa‎d(new Snake‎Drive‎r()).start‎();}publi‎c void addSn‎a keLi‎s tene‎r(Snake‎L iste‎n er l){if(l!=null){this.liste‎n ers.add(l);}}}//食物类packa‎ge TanCh‎iShe;impor‎t java.awt.Color‎;impor‎t java.awt.Graph‎ics;impor‎t java.util.Rando‎m;publi‎c class‎Food exten‎ds Point‎{publi‎c void newFo‎od(Point‎p){this.setLo‎c atio‎n(p);}publi‎c boole‎a n isSna‎k eEat‎F ood(Snake‎snake‎){Syste‎m.out.print‎ln("Food's isSna‎k eEat‎F ood");retur‎n this.equal‎s(snake‎.getHe‎a d());}publi‎c void drawM‎e(Graph‎ics g){Rando‎m rando‎m= new Rando‎m();g.setCo‎lor(Color‎.BLUE);g.fill3‎DRect‎(x*Globa‎l.CELL_‎S IZE,y*Globa‎l.CELL_‎S IZE,Globa‎l.CELL_‎S IZE,Globa‎l.CELL_‎SIZE,true);}}//墙类packa‎ge TanCh‎iShe;impor‎t java.awt.Color‎;impor‎t java.awt.Graph‎ics;impor‎t java.util.Rando‎m;publi‎c class‎Groun‎d {priva‎t e int [][] rocks‎=new int[Globa‎l.WIDTH‎] [Globa‎l.HIGHT‎];publi‎c G roun‎d(){for(int x=0;x<Globa‎l.WIDTH‎;x++){for(int y=0;y<Globa‎l.HIGHT‎;y++){rocks‎[x][0]=1;rocks‎[x][Globa‎l.HIGHT‎-1]=1;rocks‎[0][y]=1;rocks‎[Globa‎l.WIDTH‎-1][y]=1;}}}publi‎c boole‎a n isSna‎k eEat‎Rock(Snake‎Snake‎){Syste‎m.out.print‎ln("Groun‎d's isSna‎k eEat‎R ock");for(int x=0;x<Globa‎l.WIDTH‎;x++){for(int y=0;y<Globa‎l.HIGHT‎;y++){if(rocks‎[x][y]==1&&x==Snake‎.getHe‎a d().x&&y==Snake‎.getHe‎a d().y){retur‎n true;}}}retur‎n false‎;}publi‎c void drawM‎e(Graph‎ics g){Syste‎m.out.print‎ln("Groun‎d's drawM‎e");for(int x=0;x<Globa‎l.WIDTH‎;x++){for(int y=0;y<Globa‎l.HIGHT‎;y++){if(rocks‎[x][y]==1){g.setCo‎lor(Color‎.DARK_‎G RAY);g.fill3‎DRect‎(x*Globa‎l.CELL_‎S IZE,y*Globa‎l.CELL_‎S IZE, 20, 20, true);}}}}}//格子类packa‎g e TanCh‎i She;publi‎c class‎ Globa‎l {publi‎c stati‎c final‎i nt CELL_‎SIZE=20;publi‎c stati‎c final‎i nt WIDTH‎=20;publi‎c stati‎c final‎i nt HIGHT‎=20;}//point‎类packa‎g e TanCh‎i She;publi‎c class‎ Point‎ {int x;int y;publi‎c Point‎() {}publi‎c Point‎(int x, int y) {this.x = x;this.y = y;}@Overr‎i depubli‎c Strin‎g toStr‎i ng() {retur‎n"Point‎ [x=" + x + ", y=" + y + "]";}@Overr‎i depubli‎c int hashC‎ode() {final‎i nt prime‎ = 31;int resul‎t = 1;resul‎t = prime‎ * resul‎t + x;resul‎t = prime‎ * resul‎t + y;retur‎n resul‎t;}@Overr‎i depubli‎c boole‎a n equal‎s(Objec‎t obj) { if(obj insta‎n ceof‎ Point‎){Point‎ p=(Point‎)obj;if(this.x==p.x&&this.y==p.y){retur‎n true;}}if(obj==null){retur‎n false‎;}if(obj==this){retur‎n true;}retur‎n false‎;}publi‎c Point‎ setLo‎c atio‎n(Point‎ p){ this.x=p.x;this.y=p.y;retur‎n p;}}//抽象类蛇的‎监听packa‎g e TanCh‎i She;publi‎c inter‎f ace Snake‎L iste‎ner {void snake‎Moved‎(Snake‎ snake‎);}//画板类packa‎ge TanCh‎iShe;impor‎t java.awt.Color‎;impor‎t java.awt.Graph‎ics;impor‎t javax‎.swing‎.JPane‎l;publi‎c class‎GameP‎a nel exten‎d s JPane‎l{priva‎t e Snake‎snake‎;priva‎t e Food food;priva‎t e Groun‎d groun‎d;publi‎c void displ‎a y(Snake‎snake‎,Food food,Groun‎d groun‎d){Syste‎m.out.print‎ln("GameP‎a nel's displ‎a y");this.snake‎=snake‎;this.food=food;this.groun‎d=groun‎d;this.repai‎n t();//调用下面的‎p a int‎C ompo‎n ent}@Overr‎ideprote‎c ted void paint‎C ompo‎n ent(Graph‎i c s g) {// TODO Auto-gener‎a ted metho‎d stub// super‎.paint‎C ompo‎n ent(g);//重新显示g.setCo‎lor(Color‎.light‎G ray);//擦除以前的‎图形g.fillR‎e ct(0, 0, Globa‎l.WIDTH‎*Globa‎l.CELL_‎S IZE, Globa‎l.HIGHT‎*Globa‎l.CELL_‎S IZE);if(groun‎d!=null&&snake‎!=null&&food!=null){this.groun‎d.drawM‎e(g);this.snake‎.drawM‎e(g);this.food.drawM‎e(g);}}}//中央处理器‎类packa‎ge TanCh‎iShe;impor‎t java.awt.event‎.Actio‎n Even‎t;impor‎t java.awt.event‎.Actio‎n List‎e ner;impor‎t java.awt.event‎.KeyAd‎a pter‎;impor‎t java.awt.event‎.KeyEv‎e nt;impor‎t java.util.Rando‎m;impor‎t javax‎.swing‎.JButt‎o n;publi‎c class‎Contr‎o ller‎exten‎d s KeyAd‎a pter‎imple‎m ents‎Snake‎L iste‎n er{priva‎t e Snake‎snake‎;priva‎t e Food food;priva‎t e Groun‎d groun‎d;priva‎t e GameP‎a nel gameP‎a nel;publi‎c Contr‎o ller‎(Snake‎snake‎, Food food, Groun‎d groun‎d, GameP‎a nel gameP‎anel) { super‎();this.snake‎= snake‎;this.food = food;this.groun‎d = groun‎d;this.gameP‎a nel = gameP‎a nel;}@Overr‎idepubli‎c void keyPr‎e ssed‎(KeyEv‎e nt e) {// TODO Auto-gener‎a ted metho‎d stubswitc‎h(e.getKe‎y Code‎()){case KeyEv‎e nt.VK_UP‎://向上snake‎.chang‎e Dire‎c tion‎(Snake‎.UP);break‎;case KeyEv‎e nt.VK_DO‎W N:snake‎.chang‎e Dire‎c tion‎(Snake‎.DOWN);break‎;case KeyEv‎e nt.VK_LE‎F T:snake‎.chang‎e Dire‎c tion‎(Snake‎.LEFT);break‎;case KeyEv‎e nt.VK_RI‎G H T:snake‎.chang‎e Dire‎c tion‎(Snake‎.RIGHT‎);break‎;}}@Overr‎idepubli‎c void snake‎Moved‎(Snake‎snake‎) {if(food!=null&&food.isSna‎k eEat‎F ood(snake‎)){snake‎.eatFo‎od();food.newFo‎o d(snake‎.getPo‎int());}if(groun‎d.isSna‎k eEat‎Rock(snake‎)){snake‎.die();}if(snake‎.isEat‎Body()){snake‎.die();}gameP‎anel.displ‎a y(snake‎,food,groun‎d);}//开始新游戏‎publi‎c void newGa‎m e(){snake‎.start‎();//让蛇开始走‎就是开始新‎游戏food.newFo‎o d(snake‎.getPo‎int());}}//main类‎packa‎ge TanCh‎iShe;impor‎t java.awt.Borde‎r Layo‎u t;impor‎t java.awt.Dimen‎s ion;impor‎t java.awt.event‎.Actio‎n Even‎t;impor‎t java.awt.event‎.Actio‎n List‎e ner;impor‎t javax‎.swing‎.JButt‎o n;impor‎t javax‎.swing‎.JFram‎e;/*** 贪吃蛇* @autho‎r Admin‎istra‎t or**/publi‎c class‎MyGam‎e {publi‎c stati‎c void main(Strin‎g[] args) {Snake‎snake‎=new Snake‎();Food food=new Food();Groun‎d groun‎d=new Groun‎d();GameP‎a nel gameP‎a nel=new GameP‎anel();Contr‎o ller‎contr‎o ller‎=new Contr‎o ller‎(snake‎,food,groun‎d,gameP‎anel);JFram‎e frame‎=new JFram‎e();frame‎.add(gameP‎a nel,Borde‎r Layo‎u t.CENTE‎R);gameP‎anel.addKe‎y List‎e ner(contr‎o ller‎);snake‎.addSn‎a keLi‎s tene‎r(contr‎o ller‎);frame‎.addKe‎y List‎e ner(contr‎o ller‎);gameP‎anel.setSi‎z e(Globa‎l.CELL_‎S IZE*Globa‎l.WIDTH‎,Globa‎l.CELL_‎S IZE*Globa‎l.WIDTH‎);frame‎.setSi‎ze(Globa‎l.CELL_‎S IZE*Globa‎l.WIDTH‎+16,Globa‎l.CELL_‎S IZE*Globa‎l.WIDTH‎+50);frame‎.setAl‎w a ysO‎n T op(true);frame‎.setDe‎f ault‎C lose‎O pera‎t ion(JFram‎e.EXIT_‎O N_CL‎O SE);frame‎.setVi‎s ible‎(true);frame‎.setLo‎c atio‎n Rela‎t iveT‎o(null);contr‎o ller‎.newGa‎m e();}}。

50行代码实现贪吃蛇(具体思路及代码)

50行代码实现贪吃蛇(具体思路及代码)

50⾏代码实现贪吃蛇(具体思路及代码)最近⼀直在准备⽤来⾯试的⼏个⼩demo,为了能展现⾃⼰,所以都是亲⾃设计并实现的,其中⼀个就是在50⾏代码内来实现⼀个贪吃蛇,为了说明鄙⼈⾃⼰练习编程的⼀种⽅式--把代码写短,为了理解语⾔细节。

复制代码代码如下:<SPAN style="FONT-SIZE: 14px">import sys, pygamefrom pygame.locals import *from random import randrangeup =lambda x:(x[0]-1,x[1])down = lambda x :(x[0]+1,x[1])left = lambda x : (x[0],x[1]-1)right = lambda x : (x[0],x[1]+1)tl = lambda x :x<3 and x+1 or 0tr = lambda x :x==0 and 3 or x-1dire = [up,left,down,right]move = lambda x,y:[y(x[0])]+x[:-1]grow = lambda x,y:[y(x[0])]+xs = [(5,5),(5,6),(5,7)]d = upfood = randrange(0,30),randrange(0,40)FPSCLOCK=pygame.time.Clock()pygame.init()pygame.display.set_mode((800,600))pygame.mouse.set_visible(0)screen = pygame.display.get_surface()screen.fill((0,0,0))times=0.0while True:time_passed = FPSCLOCK.tick(30)if times>=150:times =0.0s = move(s,d)else:times +=time_passedfor event in pygame.event.get():if event.type == QUIT:sys.exit()if event.type == KEYDOWN and event.key == K_UP:s = move(s,d)if event.type == KEYDOWN and event.key == K_LEFT:d=dire[tl(dire.index(d))]if event.type == KEYDOWN and event.key == K_RIGHT:d=dire[tr(dire.index(d))]if s[0]==food:s = grow(s,d)food =randrange(0,30),randrange(0,40)if s[0] in s[1:] or s[0][0]<0 or s[0][0] >= 30 or s[0][1]<0 or s[0][1]>=40:breakscreen.fill((0,0,0))for r,c in s:pygame.draw.rect(screen,(255,0,0),(c*20,r*20,20,20))pygame.draw.rect(screen,(0,255,0),(food[1]*20,food[0]*20,20,20))pygame.display.update()</SPAN>游戏截图:说明:1.其实不⽤pygame,在把⼀些条件判断改改,估计可以再短⼀半。

微信小程序之贪吃蛇小游戏开发(完整代码)

微信小程序之贪吃蛇小游戏开发(完整代码)

微信⼩程序之贪吃蛇⼩游戏开发(完整代码)1:⾸先是index.wxml⽂件代码:<!--index.wxml--><canvas canvas-id='snakeCanvas' style='width:100%;height:100%;background-color:#ccc;'bindtouchstart='canvasStart' bindtouchmove='canvasMove' bindtouchend='canvasEnd'></canvas>2:然后是index.js⽂件代码//index.js//⼿指按下时的坐标var startX = 0;var startY = 0;//⼿指在canvas上移动的坐标var moveX = 0;var moveY = 0;//移动位置跟开始位置差值var X =0;var Y = 0;//⼿指⽅向var direction = null;//蛇移动⽅向var snakeDirection = "right";//⾝体对象(数组)var snakeBodys = [];//⾷物对象(数组)var foods = [];//窗⼝的宽⾼var windowWidth = 0;var windowHeight = 0;//⽤来获取屏幕⼤⼩wx.getSystemInfo({success: function (res) {windowWidth = res.windowWidth;windowHeight = res.windowHeight;}});//蛇头对象var snakeHead = {x: parseInt(Math.random() * (windowWidth-20)),y: parseInt(Math.random() * (windowHeight-20)),color: '#ff0000', //这⾥只能接受16进制没法写red这样w: 20,h: 20,reset:function(){this.x = parseInt(Math.random() * (windowWidth - 20));this.y = parseInt(Math.random() * (windowHeight - 20));}}//⽤于确定是否删除var collideBol = true;Page({canvasStart:function(e){startX = e.touches[0].x;startY = e.touches[0].y;},canvasMove:function(e){moveX = e.touches[0].x;moveY = e.touches[0].y;X = moveX - startX;Y = moveY - startY;if(Math.abs(X) > Math.abs(Y) && X > 0){direction = "right";}else if(Math.abs(X) > Math.abs(Y) && X < 0){direction = "left";}else if (Math.abs(Y) > Math.abs(X) && Y > 0) {direction = "down"; //这⾥很奇怪,是我数学坐标系没学好吗?明明Y轴正坐标是向上才对啊 }else if (Math.abs(Y) > Math.abs(X) && Y < 0) {direction = "top";}},canvasEnd:function(){snakeDirection = direction;},onReady:function(){var context = wx.createContext();//帧数var frameNum = 0;function draw(obj){context.setFillStyle(obj.color);context.beginPath();context.rect(obj.x, obj.y, obj.w, obj.h);context.closePath();context.fill();}//蛇头与⾷物碰撞函数function collide(obj1,obj2){var l1 = obj1.x;var r1 = obj1.w + l1;var t1 = obj1.y;var b1 = obj1.h+t1;var l2 = obj2.x;var r2 = obj2.w + l2;var t2 = obj2.y;var b2 = obj2.h + t2;//这⾥1是蛇头⽅块的上下左右边框 2是⾷物,同样是上下左右//(当蛇头⼜边框撞到⾷物左边框也就是⼤于左边框时就是碰撞了)if(r1>l2 && l1<r2 && b1 > t2 && t1< b2){return true;}else{return false;}}//蛇头与墙壁碰撞函数function collide2(obj1){var l1 = obj1.x;var r1 = obj1.w + l1;var t1 = obj1.y;var b1 = obj1.h + t1;if (l1 <=snakeHead.w || r1 >=windowWidth || t1 <=snakeHead.h || b1 >= windowHeight){ return true;}else{return false;}}function directionSet(){switch (snakeDirection) {case"left":snakeHead.x -= snakeHead.w;break;case"right":snakeHead.x += snakeHead.w;break;case"down":snakeHead.y += snakeHead.h;break;case"top":snakeHead.y -= snakeHead.h;break;}}function animate(){frameNum++;if (frameNum % 20 == 0){//蛇⾝体数组添加⼀个上⼀个的位置(⾝体对象)snakeBodys.push({x: snakeHead.x,y: snakeHead.y,w: 20,h: 20,color: "#00ff00"});if (snakeBodys.length > 4) {//移除不⽤的⾝体位置if (collideBol){snakeBodys.shift();}else{collideBol = true;}}directionSet();}//绘制蛇头draw(snakeHead);if (collide2(snakeHead)) {collideBol = false;snakeHead.reset();snakeBodys=[];draw(snakeHead);}//绘制蛇⾝for(var i=0;i<snakeBodys.length;i++){var snakeBody = snakeBodys[i];draw(snakeBody);}//绘制⾷物for(var i=0;i<foods.length;i++){var foodObj = foods[i];draw(foodObj);if (collide(snakeHead,foodObj)){//console.log("撞上了");collideBol = false;foodObj.reset();}}wx.drawCanvas({canvasId:"snakeCanvas",actions:context.getActions()});requestAnimationFrame(animate);}function rand(min,max){return parseInt(Math.random()*(max-min))+min;}//构造⾷物对象function Food() {var w = rand(10,20);this.w = w;this.h = w;this.x = rand(this.w, windowWidth - this.w);this.y = rand(this.h, windowHeight - this.h);this.color = "rgb("+rand(0,255)+","+rand(0,255)+","+rand(0,255)+")";//内部⽅法(重置⾷物位置颜⾊)this.reset = function (){this.x = rand(0,windowWidth);this.y = rand(0,windowHeight);this.color = "rgb(" + rand(0, 255) + "," + rand(0, 255) + "," + rand(0, 255) + ")"; }}for (var i = 0; i < 20; i++) {var foodObj = new Food();foods.push(foodObj);}animate();}})。

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码

“贪吃蛇”游戏程序代码我个人是比较喜欢玩游戏的,所以学习编程二年多了,很想做个游戏程序,由于能力有限,一直没能做好,后来突然看同学在手机上玩“贪吃蛇”,故想做出来,其一是因为此游戏界而容易设计,算法也比较简单,今天我就把我程序的代码和算法介绍一下,顺便把程序界而皮肤设计说一下.....程序中一个关于游戏信息的类如下,由于类的说明在程序中写的很清楚了,就不再多解释了:#include"time,h"〃方向定义const CPoint UP(CPoint(0,-1));const CPoint DOVN(CPoint(0,1));const CPoint LEFT(CPoint(-1,0)):const CPoint RIGHT(CPoint(1,0)):〃速度快慢定义const int HIGH =75;const int NORMAL =180;const int SLOW =300;const int MAX =80;〃表示转向数const int LENGTH=10;class GamcMsgpublic:GamcMsg(void):m_icon(0)InitGame();void InitGame(int up=VK_UP,int down = VK_DOWN,int left= VK.LEFT,int right= VK.RIGHT?(srand((unsigned)time(NULL));m_gameSpeed= NORMAL;m_speedNum=2;m_snakeNum=4:for(int i=0;i<m_snakcNum;++i)m_snakePoint[i]=CPoint(5+LENGTH*2*5+LENGTH,LENGTH*2*(i+5));m_run=true:m_direction=RIGHT;turnUP=up;turnDOWN=down;turnLEFT =left:turnRIGHT=right;}public:int m_gamcSpeed;//游戏速度int m_speedNum;//游戏速度数CPoint m_foodPoint:〃食物定义bool m_run;〃游戏状态,运得态还是暂停(结束)态CPoint m_snakePoint[MAX]:〃蛇身定义CPoint m_direction://蛇运动方向int m_snakeNum;〃蛇身结点数int m.icon;//用来设定食物是那种图标的int turnUP://用来表示玩家“上”键设的键int turnDOWN;〃用来表示玩家“下”键设的键int turnLEFT;//用来表示玩家“左”键设的键int turnRIGHT;//用来表示玩家“右”键设的键int m_num;//用来记录所选水果的编号);再让读者看一下程序主干类的设计,其中以下只列出由我们自己添加的一些变量的说明,其他的是由程序向导自动生成的,我就不说了:public:afx_msg void OnTimer(UINT_PTR nIDEvent);//程序中运行函数,即是一个定时器,时间就是上而类中的m_gameSpecd来控制的CStatic*m_staticArray;//这是一个蛇定义,是用来显示蛇的,上面只告诉蛇身结点的中心点位置坐标,然后在此中心画一个控件就类似于蛇身了afx.msg void OnCloseO://结束,主要是在其中销毁定时器的void GamcOver(void);//游戏结束函数afx_msg void OnRButtonDown(UINT nFlags,CPoint point);//当点击鼠标右键出现菜单afx_msg void OnNewGameO;//菜单选项,新游戏afx_msg void OnPauseOrStart();〃菜单选项,暂停/开始游戏afxjnsg void OnUpdatcQuick(CCmdUI*pCmdUI);//这3个函数本来是来标记速度的,和上面类中的m_speedNum对应,但是没有标记成功afx.msg void OnUpdateNormal(CCmdUI*pCmdUI);afx_msg void OnUpdateSlow(CCmdUI*pCmdUI):afx_msg void OnNormal0;//菜单选项,设定为普通速度afx_msg void OnSlowO;〃菜单选项,设定为慢速度afx_msg void OnQuickO;//菜单选项,设定为快速度afx_msg void OnlntroduceO://游戏介绍,就是弹出一个对话框而以afx_msg void OnMoreprogram();〃进入我的博客的函数afx_msg void OnAbout():〃关于"贪吃蛇”说明的对话框afx_msg void OnExit();//退出游戏CFont m.font;〃这就是上图中显示"空心字体”的亍体设置void ShowHo11o wFont(int ex,int cy,CString str)://显示空心字体函数,在(Cx,Cy)处显示字符串strafx_msg void OnBnClickedExit();//退出游戏private:int m_iconl;//表明蛇吃第1种水果的个数int m_icon2://表明蛇吃第2种水果的个数int m_icon3://表明蛇吃第3种水果的个数然后给读者写的是我程序运行很重要的一个函数,W3!_TIMER显示函数,里面有食物位置随机出现,判断蛇死,蛇移动等:void CSnakeDlg::OnTimer(UINT_PTR nIDEvent)(if(game.m_snakePoint[0].x<011game.m_snakePoint[0].y<LENGTH I|game.m_snakePoint[0].x>70011game.m_snakePoint[0].y>500)//当蛇跑出边算,游戏结束(GamcOver();}for(int j=game.m_snakeNum-l:j>0;—j)//蛇移动的量的变化,当重新设定这些控件的位置时也就是让蛇移动起来game.m_snakePoint[j]=game.m_snakePoint[j-1];game.m_snakePoint[0].x+= game.m_di recti on.x* LENGTH * 2;//蛇头移动game.m_snakePoint[0].y+= game.m_di recti on.y*LENGTH * 2;for(int i=0;i<game.m_snakcNum;++i){m_staticArray[i].SetWindowPos(NULL,game.m_snakePoint[i],x-LENGTH,game.m_snakePoint[i].y-LENGTH,game.m_snakePoint[i].x+ LENGTH,game.m_snakePoint[i].y+LENGTH,SW_SHOW);}for(int j=l;j<game.m_snakcNum;++j)//当蛇撞到自己也结束游戏if(game.m_snakcPoint[0]=game.m_snakePoint[j]){GamcOver();)m.staticArray[NIAX].ModifyStyle(OxF,SS_ICON|SS_CENTERIMAGE);〃显示水果m_stat icArray[MAX].Set Icon(AfxGetAppO->LoadIcon(game.m_icon));m_stat icArray[MAX].SetWi ndowPos(NULL,game.m_foodPoint.x,game.m_foodPoint.y,32,32,SW_SHOW);〃当蛇吃到水果if(game.m_snakePoint[0].x<game.m_foodPoint.x+20+LENGTH&& game.m_snakePoint[0].x>game.m_foodPoint.x-LENGTH&&game.m_snakePoint[0].y<game.m_foodPoint.y+20+LENGTH&&game.m_snakePoint[0].y>game.m_foodPoint.y-LENGTH)(game.m_foodPoint= CPoint(LENGTH*gamc.RandNum(2,37),LENGTH*game.RandNum(2,27));CString str:if(game.m_num =0){++m_iconl;str.Formatm_iconl);GetDlgItem(IDC_EDITl)->SetWindowTextA(str);else if(game.m_num =1)++m_icon2;str.Formatm_icon2);GetDlgItem(IDC_EDIT2)->SetWindowTextA(str):)else{++m_icon3:str.Format(飞d”,m_icon3);GetDlgItem(IDC_EDIT3)->SetWindowTextA(str);}game.m_num = game.RandNum(0,3);game.m_icon=IDI_ICON1+game.m_num;//重新加1个水果game.m_snakeNum++;〃蛇的长度加1str.Format(*%<!*,game.m_snakeNum);GetDlgItem(IDC_EDIT4)->Se t W i ndowTextA(str):)CDialog::OnTimer(nIDEvent);)如下再介绍应用在对话框中来响应键盘消息,我写的是一个键盘“钩子”,代码如下:HHOOK g_hKcyboard=NULL;HWND g_hWnd= NULL:LRESULT CALLBACK KeyboardProc(int code,//hook code WPARAM wParam,//virtual-key code LPARAM1Param //keystroke-message information)(if(wParam=game.turnUP){if(game.m_direction.y=0)game.m_direction=UP;}else if(wParam=game.turnDOWN)(if(game.m_direction.y=0)game.m_direction=DOWN:)else if(wParam=game.turnLEFT){if(game.m_direction.x=0)game.m_direction=LEFT:)else if(wParam=game.turnRIGHT){if(game.m_direction.x=0)game.m_direction=RIGHT;)elsereturn1;然后介绍一下,点击鼠标右键出现菜单:voidCSnakcDlg::OnRButtonDown(UINT nFlags,CPoint point){if(game.m_run)KillTimer(l);CMenu oMenu;if(oMenu.LoadMenu(IDR.MENU1))(CMenu*pPopup = oMenu.GetSubMcnu(O);ASSERT(pPopup!=NULL);CPoint oPoint:GetCursorPos(&oPoint);SetForegroundWindowO;pPopup->TrackPopupMenu(TPM_LEFTALIGN,oPoint.x,oPoint.y,this);}if(game.m_run)SetTimer(1,game.m_gameSpeed,NULL);CDialog::OnRBu11onDown(nF1ags,point);}然后来介绍一下程序中是怎样来改变按键的,首先说一下,我开始用EDIT控件来让用户输入,但是程序中我用的是键盘"钩子”来处理消息的,所以EDIT 控件在程序中是不可以输入信息的,所以我选的是下拉列表,代码如下,解释也在程序中相应给出:int keyNum[40]={〃定义玩家可以设的键,把所有的健信息存在这个数组中VK.UP,VK.DOWN,VK.LEFT,VK.RIGHT,VK.NUMPADO,VK_NUMPAD1,VK.NUMPAD2,VK.NUMPAD3,VK_NUMPAD4,VK_NUMPAD5, VK NUMPAD6,VK NUMPAD7,VK NUMPAD8,VK NUMPAD9);void CSnakeDlg::0nKeyset()//键盘设置响应消息函数//T0D0:在此添加命令处理程序代码if(game.m_run)KillTimer(l);CKcySetDlg dig:if(dig.DoModalO=IDOK)(if(dig.m_up =dig.m_down11dig.m_up =dig.m_left||dig.m_up =dig.m_right||dig.m_down=dig.m_left||dig.m_down ==dig.m_right||dig.m_left=dig.m_right)(MessageBox(w键位不能设置为重复的,设置失败!");if(game.m_run)SetTimcr(1,game.m_gamcSpeed,NULL);return;}game.turnUP =kcyNum[GetMarkNum(dlg.m_up)]://重新设置键game.turnDOWN=keyNum[GetMarkNum(dlg.m_down)]:game.turnLEFT =keyNum[GetMarkNum(dlg.m_left)];game.turnRIGHT =keyNum[GetMarkNum(dlg.m_right)];}if(game.m_run)SetTimcr(1,game.m_gamcSpeed,NULL);}int CSnakcDlg::GetMarkNum(CString str)//返回重新设置键对应数组的“索引”int backNum = 0;if(str="上")backNum = 0:else if(str=="下”) backNum =1:else if(str=="左") backNum=2;else if(str="右") backNum=3:else{CString ss;for(char i='A';i〈='Z';++i) {ss.Format(飞c”,i);if(ss―str.Right(l))(backNum=i-'A'+4;return backNum;})for(int i=0:i<=9:++i)ss.Format("%d",i);if(ss=str.Right(1))(backNum=i+30;return backNum;})}return backNum;)最后写一下程序更换皮肤的一段代码,本来觉得不算很难的,不过还是介绍一下吧,对了我用的是Skinmagic做的皮肤,不过这个软件你可以通过网上的说明进行注册,也可以自己把它破解,其实很简单,大家可以试试:void CSnakeDlg::0nChangSkin()(//T0D0:在此添加命令处理程序代码i f(game.m_run)KillTimer(l);CFileDialog dig(TRUE,NULL,NULL,OFN.HIDEREADONLY|OFN.OVERWRITEPROMPT,"Skin Files(*.smf7|*.smf|T,AfxGetMainWndO);CString strPath,strText="";if(dig.DoModalO=IDOK)(strPath=dig.GetPathNamcO:VERIFYd=LoadSkinFile(strPath));if(game.m_run)SetTimerd,game.m_gameSpeed,NULL);)还有很多小函数,由于都是比较简单的,就不多写了,程序介绍就到这里,呵呵,希望我能够帮你解决你写程序遇到的问题,如果大家想知道如何做程序的皮肤的话,网上有很多这样的博客,我就是在那样的博客里学到的,如果还是想我来介绍的话,那给我留言说下哦,呵呵,谢了,有问题请在下面留言.。

android游戏开发入门:贪吃蛇源代码分析

android游戏开发入门:贪吃蛇源代码分析

android游戏开发入门: 贪吃蛇 源代码分析贪吃蛇是一款足够经典的游戏。

它的经典,在于用户操作的简单,在于技术实现的简介,在于他的经久不衰。

这里的贪吃蛇的android实现,是SDK Samples中的开源例程。

可能各位都有看过~界面如下图啦~作为一个刚入门或者还没入门的新手,着实花了我一些力气来理解这段代码。

对于各种不懂的地方,慢慢查询资料,对于新的方法,通过修改代码尝试效果。

到现在终于能算个一知半解。

在代码中,对于自己有所收获的地方,我都做了相应的注释。

回过头来,觉得从这段代码中,能学到不少东西~~包括android应用的基本架构,他的面向对象的思想,以及代码的简洁明了。

于是,我想到,何不将这些东西分享出来,如果碰巧对感兴趣的朋友们有搜帮助,那就更好了~好了,闲话不说~代码和注释如下(处于对源码的敬意,原本的英文注释部分都没有删去~大家可以配合理解):PS:最近我正在写自己的“贪吃蛇”,说事贪吃蛇,其实完全颠覆了这个经典版本的设计理念和操作方式。

具体细节先卖一个关子,作品准备参加这次第二届大学生android应用开发大赛。

应该一个月内能完成,到时候也会开源出代码来~欢迎大家讨论指正·~*************************************************************************************************************************** *****Snake工程中,总共有三个文件: *TileView是基于Android的View类实现的方块图类,用来支撑上层类的调用,绘制方块图的显示界面。

通过这些代码,能打之了解如何 扩展View,实现特色的界面效果。

*SnakeView调用了TileView,实现了游戏逻辑 和 具体的显示。

*Snake为主Activity类。

建议大家按照上面的顺序看三个文件,可能逻辑上更舒服一点~~下面贴上代码和注释。

贪吃蛇JAVA源代码完整版

贪吃蛇JAVA源代码完整版

游戏贪吃蛇的JAVA源代码一.文档说明a)本代码主要功能为实现贪吃蛇游戏,GUI界面做到尽量简洁和原游戏相仿。

目前版本包含计分,统计最高分,长度自动缩短计时功能。

b)本代码受计算机系大神指点,经许可后发布如下,向Java_online网致敬c)运行时请把.java文件放入default package 即可运行。

二.运行截图a)文件位置b)进入游戏c)游戏进行中三.JAVA代码import java.awt.*;import java.awt.event.*;import static ng.String.format;import java.util.*;import java.util.List;import javax.swing.*;public class Snake extends JPanel implements Runnable { enum Dir {up(0, -1), right(1, 0), down(0, 1), left(-1, 0);Dir(int x, int y) {this.x = x; this.y = y;}final int x, y;}static final Random rand = new Random();static final int WALL = -1;static final int MAX_ENERGY = 1500;volatile boolean gameOver = true;Thread gameThread;int score, hiScore;int nRows = 44;int nCols = 64;Dir dir;int energy;int[][] grid;List<Point> snake, treats;Font smallFont;public Snake() {setPreferredSize(new Dimension(640, 440));setBackground(Color.white);setFont(new Font("SansSerif", Font.BOLD, 48));setFocusable(true);smallFont = getFont().deriveFont(Font.BOLD, 18);initGrid();addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent e) {if (gameOver) {startNewGame();repaint();}}});addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:if (dir != Dir.down)dir = Dir.up;break;case KeyEvent.VK_LEFT:if (dir != Dir.right)dir = Dir.left;break;case KeyEvent.VK_RIGHT:if (dir != Dir.left)dir = Dir.right;break;case KeyEvent.VK_DOWN:if (dir != Dir.up)dir = Dir.down;break;}repaint();}});}void startNewGame() {gameOver = false;stop();initGrid();treats = new LinkedList<>();dir = Dir.left;energy = MAX_ENERGY;if (score > hiScore)hiScore = score;score = 0;snake = new ArrayList<>();for (int x = 0; x < 7; x++)snake.add(new Point(nCols / 2 + x, nRows / 2));doaddTreat();while(treats.isEmpty());(gameThread = new Thread(this)).start();}void stop() {if (gameThread != null) {Thread tmp = gameThread;gameThread = null;tmp.interrupt();}}void initGrid() {grid = new int[nRows][nCols];for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)grid[r][c] = WALL;}}}@Overridepublic void run() {while (Thread.currentThread() == gameThread) {try {Thread.sleep(Math.max(75 - score, 25));} catch (InterruptedException e) {return;}if (energyUsed() || hitsWall() || hitsSnake()) {gameOver();} else {if (eatsTreat()) {score++;energy = MAX_ENERGY;growSnake();}moveSnake();addTreat();}repaint();}}boolean energyUsed() {energy -= 10;return energy <= 0;}boolean hitsWall() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;return grid[nextRow][nextCol] == WALL;}boolean hitsSnake() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : snake)if (p.x == nextCol && p.y == nextRow)return true;return false;}boolean eatsTreat() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : treats)if (p.x == nextCol && p.y == nextRow) {return treats.remove(p);}return false;}void gameOver() {gameOver = true;stop();}void moveSnake() {for (int i = snake.size() - 1; i > 0; i--) {Point p1 = snake.get(i - 1);Point p2 = snake.get(i);p2.x = p1.x;p2.y = p1.y;}Point head = snake.get(0);head.x += dir.x;head.y += dir.y;}void growSnake() {Point tail = snake.get(snake.size() - 1);int x = tail.x + dir.x;int y = tail.y + dir.y;snake.add(new Point(x, y));}void addTreat() {if (treats.size() < 3) {if (rand.nextInt(10) == 0) { // 1 in 10if (rand.nextInt(4) != 0) { // 3 in 4int x, y;while (true) {x = rand.nextInt(nCols);y = rand.nextInt(nRows);if (grid[y][x] != 0)continue;Point p = new Point(x, y);if (snake.contains(p) || treats.contains(p))continue;treats.add(p);break;}} else if (treats.size() > 1)treats.remove(0);}}}void drawGrid(Graphics2D g) {g.setColor(Color.lightGray);for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (grid[r][c] == WALL)g.fillRect(c * 10, r * 10, 10, 10);}}}void drawSnake(Graphics2D g) {g.setColor(Color.blue);for (Point p : snake)g.fillRect(p.x * 10, p.y * 10, 10, 10);g.setColor(energy < 500 ? Color.red : Color.orange);Point head = snake.get(0);g.fillRect(head.x * 10, head.y * 10, 10, 10);}void drawTreats(Graphics2D g) {g.setColor(Color.green);for (Point p : treats)g.fillRect(p.x * 10, p.y * 10, 10, 10);}void drawStartScreen(Graphics2D g) {g.setColor(Color.blue);g.setFont(getFont());g.drawString("Snake", 240, 190);g.setColor(Color.orange);g.setFont(smallFont);g.drawString("(click to start)", 250, 240);}void drawScore(Graphics2D g) {int h = getHeight();g.setFont(smallFont);g.setColor(getForeground());String s = format("hiscore %d score %d", hiScore, score);g.drawString(s, 30, h - 30);g.drawString(format("energy %d", energy), getWidth() - 150, h - 30); }@Overridepublic void paintComponent(Graphics gg) {super.paintComponent(gg);Graphics2D g = (Graphics2D) gg;g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);drawGrid(g);if (gameOver) {drawStartScreen(g);} else {drawSnake(g);drawTreats(g);drawScore(g);}}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setTitle("Snake");f.setResizable(false);f.add(new Snake(), BorderLayout.CENTER);f.pack();f.setLocationRelativeTo(null);f.setVisible(true);});}}。

贪吃蛇游戏详细代码与详细分析

贪吃蛇游戏详细代码与详细分析
就是就这个蛇什么能够以7字形来移动行走其实我们稍微仔细观察一下就知道了在这里面他们也是通过坐标的传递来实现的只要把头部的坐标点依次赋给下一个点后面的每一个点都走过了头部所走过的点而蛇的头部就是负责去获取坐标整个蛇的行走起来就很自然和连贯
开发过手机游戏的人就知道手机开发的三要素:画布(用来绘画游戏的画面)键盘事件,实时刷新。我们知道一般的游戏画面都是由地图,精灵(由游戏的主角,怪物组成),那我们现在就看看贪吃蛇是怎样他的地图的:
if (mDirection != WEST) {
mNextDirection = EAST;
}
return (true);
}
以上的代码大家一看就明白,就是通过判断那个键按下,然后再给要走的方向(mDirection)赋值。
以下的代码就是通
switch (mDirection) {
case EAST: {
最近我关注到,中国移动推出了OPhone手机,OPhone手机兼容Android的所有应用,你开发的Android软件和游戏,很容易的就可以移植到OPhone手机上来。目前中国移动用户已经超过6.8亿,中国移动如果在这6.8个亿的市场里,推广OPhone手机,赚钱的机会可想而知。
现在,国内手机上网的用户突破8000万,2007年,中国手机游戏市场运营收入达到1。5亿元,成为继互联网企业之后又一就业热点,2008年手机网游仍将高速增长。随着3G的发展,到2009年底手机游戏市场规模可以达到16亿元,而以往的手机游戏市场都被一些有经济实力的游戏公司或者SP来运营,对于我们技术人员只能是望洋兴叹了。Android和OPhone OS在开发游戏方面更加简单便捷。而中国移动推出mmarket手机软件商店平台,提供了一个全新的模式,未来很有可能代替SP的地位,不管你是个人和还是公司,人人都可以参与的。

经典游戏贪吃蛇代码(c++编写)

经典游戏贪吃蛇代码(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)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码1. 游戏初始化:设置游戏窗口、蛇的初始位置和长度、食物的初始位置等。

2. 蛇的移动:根据用户输入的方向键,更新蛇的位置。

确保蛇的移动不会超出游戏窗口的边界。

3. 食物的:在游戏窗口中随机食物的位置。

确保食物不会出现在蛇的身体上。

4. 碰撞检测:检测蛇头是否撞到食物或自己的身体。

如果撞到食物,蛇的长度增加;如果撞到自己的身体,游戏结束。

5. 游戏循环:不断更新游戏画面,直到游戏结束。

6. 游戏结束:显示游戏结束的提示,并询问用户是否重新开始游戏。

import random游戏窗口大小WIDTH, HEIGHT = 800, 600蛇的初始位置和长度snake = [(WIDTH // 2, HEIGHT // 2)]snake_length = 1食物的初始位置food = (random.randint(0, WIDTH // 10) 10,random.randint(0, HEIGHT // 10) 10)蛇的移动方向direction = 'RIGHT'游戏循环while True:更新蛇的位置if direction == 'UP':snake.insert(0, (snake[0][0], snake[0][1] 10)) elif direction == 'DOWN':snake.insert(0, (snake[0][0], snake[0][1] + 10)) elif direction == 'LEFT':snake.insert(0, (snake[0][0] 10, snake[0][1])) elif direction == 'RIGHT':snake.insert(0, (snake[0][0] + 10, snake[0][1]))检测碰撞if snake[0] == food:food = (random.randint(0, WIDTH // 10) 10, random.randint(0, HEIGHT // 10) 10)else:snake.pop()检测游戏结束条件if snake[0] in snake[1:] or snake[0][0] < 0 or snake[0][0] >= WIDTH or snake[0][1] < 0 or snake[0][1] >= HEIGHT:break游戏画面更新(这里使用print代替实际的游戏画面更新) print(snake)用户输入方向键direction = input("请输入方向键(WASD): ").upper() print("游戏结束!")。

贪吃蛇C语言代码实现(难度可选)

贪吃蛇C语言代码实现(难度可选)

贪吃蛇C语⾔代码实现(难度可选)本⽂实例为⼤家分享了C语⾔实现贪吃蛇的具体代码,供⼤家参考,具体内容如下/*****************************************************************************贪吃蛇(难度可选)**********************************制作者:Xu Lizi ⽇期:2012/12/31****************************部分函数有借鉴**********************************************************************************/#include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>#include<time.h>int snakey[100]={5,4,3,2,1}; /*定义蛇的横坐标*/int snakex[100]={1,1,1,1,1}; /*定义蛇的纵坐标,蛇头起始位置为(5,1)*/int life=0; /*定义蛇的⽣命,0表⽰存活,1表⽰死亡*/int lenght=5; /*定义蛇的长度,初始为5节*/char map[12][24]={"***********************", /*y*/"* *","* *","* *","* *","* *","* *","* *","* *","* *","* *",/*x*/ "***********************"};void put_money(int i,int j) /*放钱函数,使⽤随机数,随机出现⾷物*/{int x=0,y=0;srand(time(NULL));while ( (map[y][x]==003) || (map[y][x]==002) || (map[y][x]=='*') || ((x==i)&&(y==j)) ){x=rand()%21+1;y=rand()%10+1;}map[y][x]='$';return;}void output() /*输出*/{system("cls");int i,j;for(i=0; i<12; i++){for(j=0; j<23; j++) printf("%c", map[i][j]);printf("\n");}return;}void gameover() /*游戏结束*/{life=1;printf("笨蛋,输了吧\n");return;}void turn_up() /*向上移动*/{system("cls");int i;if ( (snakex[0]==1) || (map[snakex[0]-1][snakey[0]]==003) ) gameover(); else { if (map[snakex[0]-1][snakey[0]]=='$'){put_money( snakey[0], snakex[0]-1 );lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakex[0]--;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_down() /*向下*/{system("cls");int i;if ( (snakex[0]==10) || (map[snakex[0]+1][snakey[0]]==003) ) gameover();else { if (map[snakex[0]+1][snakey[0]]=='$'){put_money(snakey[0],snakex[0]+1);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}snakex[0]++;map[snakex[lenght]][snakey[lenght]]=' ';for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_left() /*向左*/{system("cls");int i;if ( (snakey[0]==1) || (map[snakex[0]][snakey[0]-1]==003) ) gameover();else { if (map[snakex[0]][snakey[0]-1]=='$'){put_money(snakey[0]-1,snakex[0]);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakey[0]--;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_right() /*向右*/{system("cls");int i;if ( (snakey[0]==21) || (map[snakex[0]][snakey[0]+1]==003) ) gameover();else {if (map[snakex[0]][snakey[0]+1]=='$'){put_money(snakey[0]+1,snakex[0]);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakey[0]++;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}int main(){int i,timeover,hard;long start;char name , direcation;printf("\n 向上移动:W ;向下移动:S ; 向左移动:A ;向右移动:D \n");printf("\t请选择难度(数字)\n\t分1~5级,分别代表\n\t1难,2中上,3中,4中下5,易:\n");scanf("%d",&hard);system("cls");for(i=1;i<5;i++) map[1][i]=003; /*输出蛇⾝*/map[1][5]=002; /*输出蛇头*/put_money(0,0);output();while(life!=1) /*当蛇死亡时结束循环*/{/*让蛇⾃动运⾏的函数******有借鉴*/timeover=1;start=clock();while((timeover=(clock()-start<=hard*100))&&!kbhit()); //难度设定if(timeover){direcation=getch();}/*让蛇⾃动运⾏的函数******有借鉴*/switch(direcation){case 'w':turn_up();break;case 's':turn_down();break;case 'a':turn_left();break;case 'd':turn_right();break;}}return 0;}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
}
private class SnakeDriver implements Runnable{
/*线程*/
public void run() {
// TODO Auto-generated method stub
while(life){
move();//不停的调用move的方法
/*循环所有的监听器*/
for(int x=0;x<Global.WIDTH;x++){
for(int y=0;y<Global.HIGHT;y++){
if(rocks[x][y]==1){
g.setColor(Color.DARK_GRAY);
g.fill3DRect(x*Global.CELL_SIZE,y*Global.CELL_SIZE, 20, 20, true);
public void newFood(Point p){
this.setLocation(p);
}
public boolean isSnakeEatFood(Snake snake){
System.out.println("Food's isSnakeEatFood");
return this.equals(snake.getHead());
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//蛇死的方法
void die(){
life=false;
}
private int [][] rocks=new int[Global.WIDTH] [Global.HIGHT];
//得到一个随机的食物坐标
}
}
}
public boolean isSnakeEatRock(Snake Snake){
System.out.println("Ground's isSnakeEatRock");
for(int x=0;x<Global.WIDTH;x++){
for(int y=0;y<Global.HIGHT;y++){
//如果老方向与新方向方向相反,则把新方向赋值给老方向
if(!(newDirection+oldDirection==0)){
oldDirection=newDirection;
}
//1.去尾巴
oldTail=body.removeLast();
//得到现在蛇头的坐标向上y-1,下y+1,左x-1,右x+1
}
}
//墙类
package TanChiShe;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class Ground {
private int [][] rocks=new int[Global.WIDTH] [Global.HIGHT];
}
//获得蛇头的坐标
public Point getHead(){
return body.getFirst();
}
//把按的方向赋值给newDirection
public void changeDirection(int direction){
System.out.println("Snake's changeDireciton");
if(l!=null){
this.listeners.add(l);
}
}
}
//食物类
package TanChiShe;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class Food extends Point{
}
}
}
}
}
//格子类
packageTanChiShe;
publicclassGlobal {
publicstaticfinalintCELL_SIZE=20;
publicstaticfinalintWIDTH=20;
publicstaticfinalintHIGHT=20;
}
//point类
packageTanChiShe;
if(rocks[x][y]==1&&x==Snake.getHead().x&&y==Snake.getHead().y){
return true;
}
}
}
return lse;
}
public void drawMe(Graphics g){
System.out.println("Ground's drawMe");
public Point getPoint(){
for(int x=0;x<Global.WIDTH;x++){
for(int y=0;y<Global.HIGHT;y++){
rocks[x][0]=1;
rocks[x][Global.HIGHT-1]=1;
rocks[0][y]=1;
rocks[Global.WIDTH-1][y]=1;
for(SnakeListener l:listeners){//依次调用所有的元素
l.snakeMoved(Snake.this);//依次调用snakeMoved的方法
}
try {
Thread.sleep(300);//睡眠1秒既是1秒move一次
} catch (InterruptedException e) {
public class Snake {
//因为常量与蛇有关,所以定义在蛇的类里面
public static final int UP=1;
public static final int DOWN=-1;
public static final int LEFT=2;
public static final int RIGHT=-2;
private int oldDirection,newDirection;
private Point oldTail;
public static boolean life;
//LinkedList有getFirst(),getLast()和removeLast()的方法
private LinkedList<Point> body=new LinkedList<Point>();
publicPoint setLocation(Point p){
//蛇类
package TanChiShe;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
int x=body.getFirst().x;
int y=body.getFirst().y;
//用老方向判断
switch(oldDirection){
case UP:
y--;
if(y<0){
y=Global.HIGHT-1;
}
break;
case DOWN:
if(y>Global.HIGHT){
}
return new Point(x,y);//必须加new不然报错
}
//启动线程的方法
public void start(){
new Thread(new SnakeDriver()).start();
}
public void addSnakeListener(SnakeListener l){
newDirection=direction;
}
//蛇吃到食物,就是把老尾巴加上
public void eatFood(){
System.out.println("Snake's eatFood");
body.addLast(oldTail);
}
//蛇吃到自己,就是蛇头和身体坐标重复
public boolean isEatBody(){
if(objinstanceofPoint){
Point p=(Point)obj;
if(this.x==p.x&&this.y==p.y){
returntrue;}
}
if(obj==null){
returnfalse;
}
if(obj==this){
returntrue;
}
returnfalse;
}
}
public void drawMe(Graphics g){
g.setColor(Color.RED);
System.out.println("Snaek's drawMe");
for(Point p:body){
g.fill3DRect(p.x*Global.CELL_SIZE, p.y*Global.CELL_SIZE, Global.CELL_SIZE, Global.CELL_SIZE, true);
相关文档
最新文档