贪吃蛇游戏安卓源代码

合集下载

贪吃蛇小游戏源代码

贪吃蛇小游戏源代码
return 1;
}
tail=(tail+1)%80;
qipan[zuobiao[0][head]][zuobiao[1][head]]='*';
head=(head+1)%80;
zuobiao[0][head]=x;
zuobiao[1][head]=y;
qipan[zuobiao[0][head]][zuobiao[1][head]]='#';
/*处理棋盘*/
char qipan[20][80];//定义棋盘
for(i=0;i<20;i++)
for(j=0;j<80;j++)
qipan[i][j]=' ';//初始化棋盘
for(i=0;i<80;i++)
qipan[0][i]='_';
for(i=0;i<20;i++)
qipan[i][0]='|';
printf("Input your game speed,please.(e.g.300)\n");
scanf("%d",&gamespeed);
while(direction!='q')
{
system("cls");
for(i=0;i<20;i++)//打印出棋盘
for(j=0;j<80;j++)
direction='q';
system("cls");
printf("GAME OVER!\n");

简单的贪吃蛇游戏代码示例

简单的贪吃蛇游戏代码示例

《简单的贪吃蛇游戏代码示例,使用Python语言和pygame库实现:》import pygameimport random# 初始化pygamepygame.init()# 设置窗口大小和标题screen_width = 640screen_height = 480screen = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption("Snake Game")# 设置颜色white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)# 定义蛇的初始位置和长度snake_pos = [[100, 50], [90, 50], [80, 50]]snake_len = len(snake_pos)# 定义游戏结束标志和得分game_over = Falsescore = 0# 定义蛇的移动方向和速度direction = "right"speed = 10# 定义食物的初始位置和大小food_pos = [random.randint(1, screen_width-1), random.randint(1, screen_height-1)]food_size = 20# 定义边界和障碍物的大小和位置border = 10obstacle_size = 200obstacle_pos = [random.randint(border, screen_width-border), random.randint(border, screen_height-border)]obstacle_speed = 2# 游戏循环while not game_over:# 处理事件for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueelif event.type == pygame.KEYDOWN:if event.key == pygame.K_UP and direction != "down":direction = "up"elif event.key == pygame.K_DOWN and direction != "up":direction = "down"elif event.key == pygame.K_LEFT and direction != "right":direction = "left"elif event.key == pygame.K_RIGHT and direction != "left":direction = "right"elif event.type == pygame.KEYUP:if event.key == pygame.K_UP and direction == "up":direction = "right" if random.randint(0, 1) else "left"elif event.key == pygame.K_DOWN and direction == "down": direction = "right" if random.randint(0, 1) else "left"elif event.key == pygame.K_LEFT and direction == "left":direction = "up" if random.randint(0, 1) else "down"elif event.key == pygame.K_RIGHT and direction == "right": direction = "up" if random.randint(0, 1) else "down"。

贪吃蛇游戏源代码

贪吃蛇游戏源代码

贪吃蛇游戏源代码#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include<string.h>#define LEFT_MARGIN 140#define FRAME_UNIT_WIDTH 25#define FRAME_UNIT_HEIGHT 15#define BOX_SIZE 15#define WINDOW_WIDTH 640#define WINDOW_HEIGHT 480#define SNAK_DEFAULT_POS_X 10#define SNAK_DEFAULT_POS_Y 5#define SMD_UP 1#define SMD_DOWN 2#define SMD_RIGHT 3#define SMD_LEFT 4#define UP_MOVE 72#define DOWN_MOVE 80#define LEFT_MOVE 75#define RIGHT_MOVE 77#define STEP_MOVE 7#define GAME_STOP 57#define ESC_OUT 1#define GENERAT_EGG 8#define NO_EVENT 0#define Boolean int#define TRUTH 1#define FALS 0#define Type_GAMESTATUS int#define ON_PAL YING 2#define WINNER 1#define GAMEOVER 0#define TIMEINTERV AL 6typedef struct{int p_X;int p_Y;}POS_in_Fram;typedef struct SNode{POS_in_Fram cur_pos;int color;struct SNode *next;}SNode, *LSNode;typedef struct{int direction;int len;POS_in_Fram Head_pre_pos; POS_in_Fram Head_cur_pos;int Head_color;LSNode next;Boolean Dead;}SNAK;typedef struct{POS_in_Fram egg_pos;int egg_color;}EggType;SNAK obj_snake;EggType obj_egg;int Message_Event;int ScoreTotal;int SpeedLevel;Type_GAMESTATUS GameStat;void set_Message_Event(int T){Message_Event = T;}int get_Message_Event(){return(Message_Event);}void clear_ScoreTotal(){ScoreTotal = 0;}int get_ScoreTotal(){return(ScoreTotal);}void draw_ScoreTotal(){char text_buffer[20];int ul_X, ul_Y;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 4); setcolor(BLUE);sprintf(text_buffer, "Score Total: %d", get_ScoreTotal());moveto(ul_X, ul_Y);outtext(text_buffer);setcolor(YELLOW);ScoreTotal++;sprintf(text_buffer, "Score Total: %d", get_ScoreTotal());moveto(ul_X, ul_Y);outtext(text_buffer);}void init_SpeedLevel(){SpeedLevel = 1;}int get_SpeedLevel(){return(SpeedLevel);}void draw_SpeedLevel(int old_l, int new_l){char text_buffer[20];int ul_X, ul_Y;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 4); setcolor(BLUE);sprintf(text_buffer, "Speed Level: %d", old_l);moveto(ul_X, ul_Y + textheight("H") * 2);outtext(text_buffer);setcolor(YELLOW);sprintf(text_buffer, "Speed Level: %d", new_l);moveto(ul_X, ul_Y + textheight("H") * 2);outtext(text_buffer);}void setSpeedLevel(int score){if(score >= 0 && score < 20){draw_SpeedLevel(get_SpeedLevel(), 1);SpeedLevel = 1;}else if(score >= 20 && score < 50){draw_SpeedLevel(get_SpeedLevel(), 2);SpeedLevel = 2;}else if(score >= 50 && score < 100){draw_SpeedLevel(get_SpeedLevel(), 3);SpeedLevel = 3;}else{draw_SpeedLevel(get_SpeedLevel(), 4);SpeedLevel = 4;}}void set_GameStat(Type_GAMESTATUS state){GameStat = state;}Type_GAMESTATUS get_GameStat() {return(GameStat);}void set_SnakeDead(Boolean T){obj_snake.Dead = T;}Boolean Is_SnakeDead(){return(obj_snake.Dead);}int get_SHOD(int T){switch(T){case SMD_UP:return(SMD_DOWN);case SMD_DOWN:return(SMD_UP);case SMD_RIGHT:return(SMD_LEFT);case SMD_LEFT:return(SMD_RIGHT);}}int get_SHD(){return(obj_snake.direction);}Boolean findPointInSnake(int pX, int pY) {LSNode p;if((obj_snake.Head_cur_pos.p_X == pX) && (obj_snake.Head_cur_pos.p_Y == pY))return(TRUTH);for(p = obj_snake.next;p != NULL;p = p->next){if((p->cur_pos.p_X == pX) && (p->cur_pos.p_Y == pY))return(TRUTH);}return(FALS);}Boolean Is_SnakEating(){if((obj_snake.Head_pre_pos.p_X == obj_egg.egg_pos.p_X) && (obj_snake.Head_pre_pos.p_Y == obj_egg.egg_pos.p_Y))return(TRUTH);elsereturn(FALS);}void Init_obj_snake(){obj_snake.direction = SMD_RIGHT;obj_snake.len = 1;obj_snake.Head_cur_pos.p_X = SNAK_DEFAULT_POS_X;obj_snake.Head_cur_pos.p_Y = SNAK_DEFAULT_POS_Y;obj_snake.Head_pre_pos = obj_snake.Head_cur_pos;obj_snake.Head_color = RED;obj_snake.next = NULL;obj_snake.Dead = FALS;}void Init_obj_egg(){obj_egg.egg_pos.p_X = 0;obj_egg.egg_pos.p_Y = 0;obj_egg.egg_color = BLACK;}void RegistryGraphicMode(){int Driver, Mode;detectgraph(&Driver, &Mode);initgraph(&Driver, &Mode,"");}void Draw_FrameInWindow(int f_ul_X, int f_ul_Y, int f_dr_X, int f_dr_Y, int W, int H) {int i, x, y;rectangle(f_ul_X - 1, f_ul_Y - 1, f_dr_X + 1, f_dr_Y + 1);setfillstyle(SOLID_FILL, BLACK);bar(f_ul_X, f_ul_Y, f_dr_X, f_dr_Y);setcolor(DARKGRAY);for(i = 1;i < W;i++){x = f_ul_X + i * BOX_SIZE;line(x, f_ul_Y, x, f_dr_Y);}for(i = 1;i < H;i++){y = f_ul_Y + i * BOX_SIZE;line(f_ul_X, y, f_dr_X, y);}}void Draw_mainGraphWindow(){int ul_X, ul_Y, dr_X, dr_Y;setfillstyle(SOLID_FILL, BLUE);bar(0, 0, WINDOW_WIDTH - 1, WINDOW_HEIGHT - 1);ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT * 2 - 3);dr_X = LEFT_MARGIN + BOX_SIZE * FRAME_UNIT_WIDTH;dr_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 3);Draw_FrameInWindow(ul_X, ul_Y, dr_X, dr_Y, FRAME_UNIT_WIDTH, FRAME_UNIT_HEIGHT);ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 4);settextjustify(LEFT_TEXT, TOP_TEXT);settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);setcolor(YELLOW);sprintf(text_buffer, "Score Total: %d", get_ScoreTotal());moveto(ul_X, ul_Y);outtext(text_buffer);sprintf(text_buffer, "Speed Level: %d", get_SpeedLevel());moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "EXIT: ESC Button");moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "Created By: qiuyongfei");moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "Class: 04hulianwang29hao");moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "UP: Up Arrow");moveto(ul_X + textwidth("H") * 30, ul_Y);strcpy(text_buffer, "DOWN: Down Arrow");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "LEFT: Left Arrow");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "RIGHT: Right Arrow");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "STOP: Space Button");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);}void draw_egg(Boolean T){int ul_X, ul_Y;int color;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT * 2 - 3);if(T == FALS)color = BLACK;elsecolor = obj_egg.egg_color;setfillstyle(SOLID_FILL, color);bar(ul_X + BOX_SIZE * obj_egg.egg_pos.p_Y + 1, ul_Y + BOX_SIZE * obj_egg.egg_pos.p_X + 1, ul_X + BOX_SIZE * (obj_egg.egg_pos.p_Y + 1) - 1, ul_Y + BOX_SIZE * (obj_egg.egg_pos.p_X + 1) - 1);}void Mapped_Draw(Boolean T){int ul_X, ul_Y;int Ax, Ay, Bx, By;int color;LSNode p;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT * 2 - 3);if(T == FALS)color = BLACK;elsecolor = obj_snake.Head_color;setfillstyle(SOLID_FILL, color);Ax = ul_X + BOX_SIZE * obj_snake.Head_cur_pos.p_Y + 1;Ay = ul_Y + BOX_SIZE * obj_snake.Head_cur_pos.p_X + 1;Bx = ul_X + BOX_SIZE * (obj_snake.Head_cur_pos.p_Y + 1) - 1;By = ul_Y + BOX_SIZE * (obj_snake.Head_cur_pos.p_X + 1) - 1;bar(Ax, Ay, Bx, By);if(T == TRUTH){setfillstyle(SOLID_FILL, YELLOW);bar(Ax + 4, Ay + 4, Ax + 4 + 5, Ay + 4 + 5);}for(p = obj_snake.next;p != NULL;p = p->next){if(T == FALS)color = BLACK;elsecolor = p->color;setfillstyle(SOLID_FILL, color);Ax = ul_X + BOX_SIZE * p->cur_pos.p_Y + 1;Ay = ul_Y + BOX_SIZE * p->cur_pos.p_X + 1;Bx = ul_X + BOX_SIZE * (p->cur_pos.p_Y + 1) - 1;By = ul_Y + BOX_SIZE * (p->cur_pos.p_X + 1) - 1;bar(Ax, Ay, Bx, By);}}void draw_GS_GO_Surface(Type_GAMESTA TUS T){char text_buffer[40];settextjustify(LEFT_TEXT, TOP_TEXT);switch(T){case ON_PAL YING:settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 4);setcolor(LIGHTCY AN);strcpy(text_buffer, "ITEM - 2: Game.Greed Snake");moveto(100, 100);outtext(text_buffer);settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 1);setcolor(YELLOW);strcpy(text_buffer, "Please press any key to continue ...");moveto(150, 300);outtext(text_buffer);break;case GAMEOVER:settextstyle(GOTHIC_FONT, HORIZ_DIR, 8);setcolor(RED);strcpy(text_buffer, "GAME OVER");moveto(70, 80);outtext(text_buffer);settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 2);setcolor(YELLOW);strcpy(text_buffer, "Sorry!");moveto(160, 320);outtext(text_buffer);sprintf(text_buffer, "Total Score: %d", get_ScoreTotal());moveto(240, 320);outtext(text_buffer);sprintf(text_buffer, "Speed Level: %d", get_SpeedLevel());moveto(240, 350);outtext(text_buffer);break;case WINNER:settextstyle(GOTHIC_FONT, HORIZ_DIR, 8);setcolor(RED);strcpy(text_buffer, "YOU WIN !");moveto(80, 80);outtext(text_buffer);settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 2);setcolor(YELLOW);strcpy(text_buffer, "Congratulation!");moveto(120, 320);outtext(text_buffer);sprintf(text_buffer, "Total Score: %d", get_ScoreTotal());moveto(280, 320);outtext(text_buffer);sprintf(text_buffer, "Speed Level: %d", get_SpeedLevel());moveto(280, 350);outtext(text_buffer);break;default:break;}}void set_SH_Pre_Pos(int T){int H_pX, H_pY;H_pX = obj_snake.Head_cur_pos.p_X;H_pY = obj_snake.Head_cur_pos.p_Y;switch(T){case SMD_UP:if((H_pX - 1) < 0 || findPointInSnake(H_pX - 1, H_pY) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX - 1;obj_snake.Head_pre_pos.p_Y = H_pY;break;case SMD_DOWN:if((H_pX + 1) >= FRAME_UNIT_HEIGHT || findPointInSnake(H_pX + 1, H_pY) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX + 1;obj_snake.Head_pre_pos.p_Y = H_pY;break;case SMD_RIGHT:if((H_pY + 1) >= FRAME_UNIT_WIDTH || findPointInSnake(H_pX, H_pY + 1) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX;obj_snake.Head_pre_pos.p_Y = H_pY + 1;break;case SMD_LEFT:if((H_pY - 1) < 0 || findPointInSnake(H_pX, H_pY - 1) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX;obj_snake.Head_pre_pos.p_Y = H_pY - 1;break;}}Boolean set_SHD(int T){if(get_SHD() == T || get_SHOD(get_SHD()) == T) return(FALS);obj_snake.direction = T;return(TRUTH);}void process_SnakeNode(Boolean eated){int i;POS_in_Fram temp1_cur_pos, temp2_cur_pos; LSNode p, q;temp1_cur_pos = obj_snake.Head_cur_pos;obj_snake.Head_cur_pos = obj_snake.Head_pre_pos;p = obj_snake.next;for(i = 1;i < obj_snake.len;i++){temp2_cur_pos = p->cur_pos;p->cur_pos = temp1_cur_pos;temp1_cur_pos = temp2_cur_pos;p = p->next;}if(eated == TRUTH){q = (LSNode)malloc(sizeof(SNode));q->color = obj_egg.egg_color;q->cur_pos = temp1_cur_pos;if(obj_snake.len == 1){q->next = obj_snake.next;obj_snake.next = q;obj_snake.len++;return;}for(p = obj_snake.next;p->next != NULL;p = p->next);q->next = p->next;p->next = q;obj_snake.len++;}}void generate_Egg(){int temp_pX, temp_pY, temp_color;draw_egg(FALS);temp_pX = random(FRAME_UNIT_HEIGHT);temp_pY = random(FRAME_UNIT_WIDTH);while(findPointInSnake(temp_pX, temp_pY) == TRUTH){temp_pX = random(FRAME_UNIT_HEIGHT);temp_pY = random(FRAME_UNIT_WIDTH);}obj_egg.egg_pos.p_X = temp_pX;obj_egg.egg_pos.p_Y = temp_pY;for(temp_color = random(16);temp_color == BLACK;temp_color = random(16)); obj_egg.egg_color = temp_color;draw_egg(TRUTH);set_Message_Event(NO_EVENT);}void move_To(int T, Boolean step) {if(step == FALS){if(set_SHD(T) == FALS)goto Skip_1;}set_SH_Pre_Pos(T);if(Is_SnakeDead() == TRUTH) goto Skip_2;if(Is_SnakEating() == TRUTH) {Mapped_Draw(FALS);process_SnakeNode(TRUTH);Mapped_Draw(TRUTH);draw_ScoreTotal();setSpeedLevel(get_ScoreTotal());goto Skip_3;}else{Mapped_Draw(FALS);process_SnakeNode(FALS);Mapped_Draw(TRUTH);goto Skip_1;}Skip_1:set_Message_Event(NO_EVENT); return;Skip_2:set_Message_Event(ESC_OUT); return;Skip_3:set_Message_Event(GENERAT_EGG); return;}void pause_game(){while((bioskey(0) >> 8) != GAME_STOP);set_Message_Event(NO_EVENT);}void process_GameStat(Type_GAMESTATUS T) {LSNode p, q;switch(T){case ON_PAL YING:draw_GS_GO_Surface(ON_PAL YING);break;case WINNER:cleardevice();draw_GS_GO_Surface(WINNER);getch();break;case GAMEOVER:cleardevice();draw_GS_GO_Surface(GAMEOVER);getch();break;default:break;}p = obj_snake.next;while(p != NULL){q = p->next;free(p);}}Boolean IsWinner(){if(get_SpeedLevel() == 4)return(TRUTH);elsereturn(FALS);}Boolean IsGameOver(){if(get_Message_Event() == ESC_OUT)return(TRUTH);elsereturn(FALS);}Boolean IsTimeOut(){static long temp, sourc;temp = biostime(0, sourc);if((temp - sourc) < (TIMEINTERVAL - SpeedLevel))return FALS;else{sourc = temp;return TRUTH;}}void getMessageEvent(){if(get_Message_Event() == GENERAT_EGG || get_Message_Event() == ESC_OUT || get_Message_Event() == GAME_STOP)return;if(IsTimeOut() == TRUTH){set_Message_Event(STEP_MOVE);}if(bioskey(1)){set_Message_Event(bioskey(0) >> 8); return;}}void dispatchMessage_Event(){switch(get_Message_Event()){case UP_MOVE:move_To(SMD_UP, FALS);break;case DOWN_MOVE:move_To(SMD_DOWN, FALS);break;case LEFT_MOVE:move_To(SMD_LEFT, FALS);break;case RIGHT_MOVE:move_To(SMD_RIGHT, FALS);break;case STEP_MOVE:move_To(get_SHD(), TRUTH);break;case GENERA T_EGG:generate_Egg();break;case GAME_STOP:pause_game();break;case ESC_OUT:break;default:set_Message_Event(NO_EVENT); }}void main(){RegistryGraphicMode();set_GameStat(ON_PAL YING);process_GameStat(get_GameStat());clear_ScoreTotal();Init_obj_snake();Init_obj_egg();init_SpeedLevel();randomize();set_Message_Event(GENERAT_EGG);getch();cleardevice();Draw_mainGraphWindow();do{getMessageEvent(); dispatchMessage_Event();if(IsWinner() == TRUTH){set_GameStat(WINNER);break;}if(IsGameOver() == TRUTH){set_GameStat(GAMEOVER); break;}}while(1);process_GameStat(get_GameStat());closegraph(); }。

贪吃蛇源代码

贪吃蛇源代码

import java.awt.*;import java.awt.event.*;public class GreedSnake //主类{public static void main(String[] args) {// TODO Auto-generated method stubnew MyWindow();}}class MyPanel extends Panel implements KeyListener,Runnable//自定义面板类,继承了键盘和线程接口{Button snake[]; //定义蛇按钮int shu=0; //蛇的节数int food[]; //食物数组boolean result=true; //判定结果是输还是赢Thread thread; //定义线程static int weix,weiy; //食物位置boolean t=true; //判定游戏是否结束int fangxiang=0; //蛇移动方向int x=0,y=0; //蛇头位置MyPanel(){setLayout(null);snake=new Button[20];food=new int [20];thread=new Thread(this);for(int j=0;j<20;j++){food[j]=(int)(Math.random()*99);//定义20个随机食物}weix=(int)(food[0]*0.1)*60; //十位*60为横坐标weiy=(int)(food[0]%10)*40; //个位*40为纵坐标for(int i=0;i<20;i++){snake[i]=new Button();}add(snake[0]);snake[0].setBackground(Color.black);snake[0].addKeyListener(this); //为蛇头添加键盘监视器snake[0].setBounds(0,0,10,10);setBackground(Color.cyan);}public void run() //接收线程{while(t){if(fangxiang==0)//向右{try{x+=10;snake[0].setLocation(x, y);//设置蛇头位置if(x==weix&&y==weiy) //吃到食物{shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint(); //重绘下一个食物add(snake[shu]); //增加蛇节数和位置snake[shu].setBounds(snake[shu-1].getBounds()); }thread.sleep(100); //睡眠100ms}catch(Exception e){}}else if(fangxiang==1)//向左{try{x-=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds()); }thread.sleep(100);}catch(Exception e){}}else if(fangxiang==2)//向上{try{y-=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds());}thread.sleep(100);}catch(Exception e){}}else if(fangxiang==3)//向下{try{y+=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds());}thread.sleep(100);}catch(Exception e){}}int num1=shu;while(num1>1)//判断是否咬自己的尾巴{if(snake[num1].getBounds().x==snake[0].getBounds().x&&snake[num1].getBounds().y==snake[0]. getBounds().y){t=false;result=false;repaint();}num1--;}/*if(x<0||x>=this.getWidth()||y<0||y>=this.getHeight())//判断是否撞墙{t=false;result=false;repaint();}*/int num=shu;while(num>0) //设置蛇节位置{snake[num].setBounds(snake[num-1].getBounds());num--;}if(shu==5) //如果蛇节数等于15则胜利{t=false;result=true;repaint();}}}public void keyPressed(KeyEvent e) //按下键盘方向键{if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右键{if(fangxiang!=1)//如果先前方向不为左fangxiang=0;}else if(e.getKeyCode()==KeyEvent.VK_LEFT){ if(fangxiang!=0)fangxiang=1;}else if(e.getKeyCode()==KeyEvent.VK_UP){ if(fangxiang!=3)fangxiang=2;}else if(e.getKeyCode()==KeyEvent.VK_DOWN){ if(fangxiang!=2)fangxiang=3;}}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}public void paint(Graphics g) //在面板上绘图{int x1=this.getWidth()-1;int y1=this.getHeight()-1;g.setColor(Color.red);g.fillOval(weix, weiy, 10, 10);//食物g.drawRect(0, 0, x1, y1); //墙if(t==false&&result==false)g.drawString("游戏结束", 250, 200);//输出游戏失败else if(t==false&&result==true)g.drawString("你赢了", 250, 200);//输出游戏成功}}class MyWindow extends Frame implements ActionListener//自定义窗口类{MyPanel my;Button btn;Panel panel;MyWindow(){super("GreedSnake");my=new MyPanel();btn=new Button("begin");panel=new Panel();btn.addActionListener(this);panel.add(new Label("begin后请按Tab键选定蛇"));panel.add(btn);panel.add(new Label("按上下左右键控制蛇行动"));add(panel,BorderLayout.NORTH);add(my,BorderLayout.CENTER);setBounds(100,100,610,500);setVisible(true);validate();addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public void actionPerformed(ActionEvent e)//按下begin按钮{if(e.getSource()==btn){try{my.thread.start(); //开始线程my.validate();}catch(Exception ee){}}}}。

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码

#include <stdlib.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include <conio.h>#define Enter 7181#define ESC 283#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endifvoid interrupt (*oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS);void SetTimer(void interrupt (*IntProc)(__CPPARGS));void KillTimer(void);void Initgra(void);void TheFirstBlock(void);void DrawMap(void);void Initsnake(void);void Initfood(void);void Snake_Headmv(void);void Flag(int,int,int,int);void GameOver(void);void Snake_Bodymv(void);void Snake_Bodyadd(void);void PrntScore(void);void Timer(void);void Win(void);void TheSecondBlock(void);void Food(void);void Dsnkorfd(int,int,int);void Delay(int);struct Snake{int x;int y;int color;}Snk[12];struct Food{int x;int y;int color;}Fd;int flag1=1,flag2=0,flag3=0,flag4=0,flag5=0,flag6=0,checkx,checky,num,key=0,Times,Score,Hscore,Snkspeed,TimerCounter,TureorFalse; char Sco[2],Time[6];void main(){ Initgra();SetTimer(newhandler);TheFirstBlock();while(1){DrawMap();Snake_Headmv();GameOver();Snake_Bodymv();Snake_Bodyadd();PrntScore();Timer();Win();if(key==ESC)break;if(key==Enter){cleardevice();TheFirstBlock();}TheSecondBlock();Food();Delay(Snkspeed);}closegraph();KillTimer();}void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)) {oldhandler=getvect(0x1c);disable();setvect(0x1c,IntProc);enable();}void KillTimer(){disable();setvect(0x1c,oldhandler);enable();}void Initgra(){int gd=DETECT,gm;initgraph(&gd,&gm,"d:\\tc");}void TheFirstBlock(){setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The First Block");loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=10;num=2;Times=0;key=0;TureorFalse=1;TimerCounter=0;Time[0]='0';Time[1]='0';Time[2]=':';Time[3]='1';Time[4]='0';Time[5]='\0'; }else if(key==ESC) cleardevice();else goto loop;}void DrawMap(){line(10,10,470,10);line(470,10,470,470);line(470,470,10,470);line(10,470,10,10);line(480,20,620,20);line(620,20,620,460);line(620,460,480,460);line(480,460,480,20);}void Initsnake(){randomize();num=2;Snk[0].x=random(440);Snk[0].x=Snk[0].x-Snk[0].x%20+50;Snk[0].y=random(440);Snk[0].y=Snk[0].y-Snk[0].y%20+50;Snk[0].color=4;Snk[1].x=Snk[0].x;Snk[1].y=Snk[0].y+20;Snk[1].color=4;}void Initfood(){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;}void Snake_Headmv(){if(bioskey(1)){key=bioskey(0);switch(key){case UP:Flag(1,0,0,0);break;case DOWN:Flag(0,1,0,0);break;case LEFT:Flag(0,0,1,0);break;case RIGHT:Flag(0,0,0,1);break;default:break;}}if(flag1){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag2){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag3){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}if(flag4){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}}void Flag(int a,int b,int c,int d){flag1=a;flag2=b;flag3=c;flag4=d;}void GameOver(){int i;if(Snk[0].x<20||Snk[0].x>460||Snk[0].y<20||Snk[0].y>460) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop1:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();elsegoto loop1;}for(i=3;i<num;i++){if(Snk[0].x==Snk[i].x&&Snk[0].y==Snk[i].y) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop2:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();else goto loop2;}}}void Snake_Bodymv(){int i,s,t;for(i=1;i<num;i++){Dsnkorfd(checkx,checky,Snk[i].color); Dsnkorfd(Snk[i].x,Snk[i].y,0);s=Snk[i].x;t=Snk[i].y;Snk[i].x=checkx;Snk[i].y=checky;checkx=s;checky=t;}}void Food(){if(flag5){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;flag5=0;}Dsnkorfd(Fd.x,Fd.y,Fd.color);}void Snake_Bodyadd(){if(Snk[0].x==Fd.x&&Snk[0].y==Fd.y) {if(Snk[num-1].x>Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x+20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].x<Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x-20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y>Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y+20; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y<Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y-20; Snk[num-1].color=Fd.color;}flag5=1;Score++;}}void PrntScore(){if(Hscore!=Score){setcolor(11);settextstyle(0,0,3); outtextxy(490,100,"SCORE"); setcolor(2);setfillstyle(1,0);rectangle(520,140,580,180); floodfill(530,145,2);Sco[0]=(char)(Score+48);Sco[1]='\0';Hscore=Score;setcolor(4);settextstyle(0,0,3); outtextxy(540,150,Sco);}}void Timer(){if(TimerCounter>18){Time[4]=(char)(Time[4]-1); if(Time[4]<'0'){Time[4]='9';Time[3]=(char)(Time[3]-1);}if(Time[3]<'0'){Time[3]='5';Time[1]=(char)(Time[1]-1);}if(TureorFalse){setcolor(11);settextstyle(0,0,3);outtextxy(490,240,"TIMER");setcolor(2);setfillstyle(1,0);rectangle(490,280,610,320);floodfill(530,300,2);setcolor(11);settextstyle(0,0,3);outtextxy(495,290,Time);TureorFalse=0;}if(Time[1]=='0'&&Time[3]=='0'&&Time[4]=='0') {setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}else if(key==ESC) cleardevice();else goto loop;}TimerCounter=0;TureorFalse=1;}}void Win(){if(Score==3)Times++;if(Times==2){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"You Win");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();key=0;}else if(key==ESC) cleardevice();else goto loop;}}void TheSecondBlock(){if(Score==3){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The Second Block"); loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=8;num=2;key=0;}else if(key==ESC) cleardevice();else goto loop;}}void Dsnkorfd(int x,int y,int color) {setcolor(color);setfillstyle(1,color);circle(x,y,10);floodfill(x,y,color);}void Delay(int times){int i;for(i=1;i<=times;i++)delay(15000);}。

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()```当您运行此代码时,将会启动一个贪吃蛇小游戏。

贪吃蛇游戏源代码

贪吃蛇游戏源代码
mainFrame.setVisible(true);
begin();
}
//----------------------------------------------------------------------
//keyPressed():按键检测
//----------------------------------------------------------------------
void begin()
{
if(snakeModel==null||!snakeModel.running)
{
snakeModel=new SnakeModel(this,canvasWidth/nodeWidth,
this.canvasHeight/nodeHeight);
(new Thread(snakeModel)).start();
//GreedSnake():初始化游戏界面
//----------------------------------------------------------------------
public GreedSnake()
{
//设置界面元素
mainFrame=new JFrame("GreedSnake");
*要点分析:
*1)数据结构:matrix[][]用来存储地图上面的信息,如果什么也没有设置为false,
* 如果有食物或蛇,设置为true;nodeArray,一个LinkedList,用来保存蛇的每
* 一节;food用来保存食物的位置;而Node类是保存每个位置的信息。

贪吃蛇源代码

贪吃蛇源代码

// proj_test.cpp : Defines the entry point for the console application./*设计思路:1、首先开辟单链表,内有3个节点表示蛇身2、蛇每移动一次,开辟新节点,加入链表头结点作为蛇头,释放尾部节点,形成移动效果3、随机产生食物,若在移动中吃到食物,则本次周期无需释放尾部节点,蛇身加长按键指示:上:W下:S左:A右:D加速: 1减速:2*///头文件定义#include "stdafx.h"#include<stdio.h>#include <graphics.h>#include <malloc.h>#include <conio.h>#include <stdlib.h>#include <time.h>#include <math.h>#include <windows.h>#define Hori_Len 30 //水平格数struct node *FindSecTailNode(struct node *Pnode); //函数功能:找到尾部前一节点,以便清除尾节点struct node *MoveNextStep(struct node *headnode,int direction); //函数功能:开辟新节点,清除尾节点,形成移动效果struct node *InitNode(); //函数功能:初始化蛇身,开辟单链表,内含3个节点;void DrawSnake(struct node *headnod); //函数功能:绘制蛇身int CheckSnake(struct node *p); //函数功能:错误检测,如果到达边界,返回错误标志void delay(); //函数功能:延时-决定蛇移动速度int keydown(int *z); //函数功能:获取键盘输入void drawDot(int x,int y); //函数功能:绘图--绘点void ReMoveDot(int x,int y); //函数功能:黑色填充目标点void mkfood(struct node *p); //函数功能:产生食物void SpeedCtrl(struct node *TempNode,struct node *HeadNode);//速度控制函数void RecordDisp(); //打印游戏纪录void InitFill() ;//初始化填充struct node{int x;int y;struct node *next;};int cnt_X=100;int food[2]={2,15};int check_result=1;int timelenX=5000;int Dire=2;int speed=450;int fen=0;//积分int jilu;//最高分记录char jiluzhe[20];char ch1[10];char ch2[10];char ch3[10];int main(){FILE *fp;//从文件载入最高记录if((fp=fopen("Record.txt","r"))==NULL)jilu=0;else {fgets(jiluzhe,20,fp);fscanf(fp,"%d",&jilu);}// fclose (fp);struct node *MoveNode;MoveNode=InitNode();initgraph(600, 600); // 初始化图形空间mkfood(MoveNode);//产生食物InitFill();//初始化填充RecordDisp();for(;;){//delay();Sleep(600-speed);int temp_dir=Dire;Dire=keydown(&Dire);if(Dire==5) //新增暂停功能{outtextxy(300,300,"暂停");getch();Dire=temp_dir;outtextxy(300,300," ");}if(MoveNode!=NULL){MoveNode=MoveNextStep(MoveNode,Dire);if(check_result==0){//closegraph();break;//return 0;}DrawSnake(MoveNode);}//Sleep(timelenX/55);}setfont(50,0,"宋体");setcolor(YELLOW);outtextxy(175,250,"GAMEOVER!"); /*setcolor(WHITE);Sleep(1000);jilu=0;if (fen>=jilu){strcpy(jiluzhe,"daqing");fp=fopen("Record.txt","w");fprintf(fp,"%s\n%d",jiluzhe,fen);fclose (fp);Sleep(1000);}*/if (fen>=jilu){strcpy(jiluzhe,"Daqing56");fp=fopen("Record.txt","w");fprintf(fp,"%s\n%d",jiluzhe,fen);fclose (fp);}Sleep(1000);closegraph();return 0;}void DrawSnake(struct node *headnod){struct node *TempNode=headnod;while(TempNode&&(TempNode->next!=NULL)){drawDot(TempNode->x,TempNode->y);TempNode=TempNode->next;}drawDot(TempNode->x,TempNode->y);}struct node *MoveNextStep(struct node *headnode,int direction){struct node *TempNode=(struct node *) malloc(sizeof(struct node));if(TempNode!=NULL)TempNode->next=headnode;switch(direction){case 1: //TempNode->x=headnode->x-1;TempNode->y=headnode->y;break;case 2:TempNode->x=headnode->x+1;TempNode->y=headnode->y;break;case 3:TempNode->x=headnode->x;TempNode->y=headnode->y-1;break;case 4:TempNode->x=headnode->x;TempNode->y=headnode->y+1;break;default:break;}check_result=CheckSnake(TempNode);if(check_result==0)//一旦游戏失败,函数返回{return TempNode;}if(!(TempNode->x==food[0]&&TempNode->y==food[1])) //检测没有吃掉食物,则去尾巴{struct node *tailnode, *Sectailnode=FindSecTailNode(TempNode);tailnode=Sectailnode->next;ReMoveDot(tailnode->x,tailnode->y);//填充黑色以便清除尾巴free(tailnode);Sectailnode->next=NULL;}else{fen++;mkfood(TempNode);}SpeedCtrl(TempNode,headnode);return TempNode;}void SpeedCtrl(struct node *TempNode,struct node *HeadNode){//添加自动调速代码int DistToFood_X=abs(TempNode->x-food[0]);int DistToFood_Y=abs(TempNode->y-food[1]);int DistToEdge_X=abs(TempNode->x-1)<abs(TempNode->x-(Hori_Len-1))?abs(TempNode->x-1):abs(TempNode->x-(Hori_Len-1));int DistToEdge_Y=abs(TempNode->y-3)<abs(TempNode->y-(Hori_Len-1))?abs(TempNode ->y-3):abs(TempNode->y-(Hori_Len-1));int HoriSign=(Dire==1)||(Dire==2);/*if((DistToFood_X<7&&DistToFood_Y==0) || (DistToFood_Y<7&&DistToFood_X==0)) //与目标点距离过小timelenX=5000+(7-DistToFood_X-DistToFood_Y)*1000;else// if((DistToEdge_X<7&&HoriSign==1)||(DistToEdge_Y<7&&HoriSign==0)) //与边缘距离过小if((Dire==1&&TempNode->x<6)||(Dire==2&&TempNode->x>23)||(Dire==3&&TempNode->y<8)| |(Dire==4&&TempNode->y>23)){if(Dire==1&&TempNode->x<6) //水平移动// timelenX=5000+(6-TempNode->x)*2000;speed=speed-(6-TempNode->x)*20;if(Dire==2&&TempNode->x>23) //水平移动// timelenX=5000+(TempNode->x+8-Hori_Len)*2000;speed=speed-(TempNode->x+7-Hori_Len)*20;if(Dire==3&&TempNode->y<8) //水平移动// timelenX=5000+(9-TempNode->y)*2000;speed=speed-(8-TempNode->y)*20;if(Dire==4&&TempNode->y>23) //水平移动// timelenX=5000+(TempNode->y+8-Hori_Len)*2000;speed=speed-(TempNode->y+7-Hori_Len)*20;}else{speed=speed<500?(speed=450+5*fen):500; //正常情况}if(speed>500) speed=500;*/speed=speed<500?(speed=450+5*fen):500; //正常情况if(speed>500) speed=500;sprintf(ch1, "%d ", fen);sprintf(ch2, "%d ", speed);settextcolor(WHITE);outtextxy(55,20,ch1);outtextxy(185,20,ch2);/*struct node *p=HeadNode;if(p!=NULL)do{int diffX=abs(TempNode->x-p->x);int diffY=abs(TempNode->y-p->y);if(Dire==1&&TempNode->x>p->x&&diffX<4)timelenX=5000+(4-diffX)*2000;if(Dire==2&&TempNode->x<p->x&&diffX<4)timelenX=5000+(4-diffX)*2000;if(Dire==3&&TempNode->y>p->y&&diffY<4)timelenX=5000+(4-diffY)*2000;if(Dire==4&&TempNode->y<p->y&&diffY<4)timelenX=5000+(4-diffY)*1500;p=p->next;} while(p!=NULL);*/}struct node *FindSecTailNode(struct node *Pnode){struct node * TempNode=Pnode;while(TempNode&&(TempNode->next!=NULL)&&(TempNode->next->next!=NULL)) {TempNode=TempNode->next;}return TempNode;}struct node *InitNode(){struct node *head=(struct node *) malloc(sizeof(struct node));struct node *head_1=(struct node *) malloc(sizeof(struct node));struct node *head_2=(struct node *) malloc(sizeof(struct node));head->x=3;head->y=5;head_1->x=2;head_1->y=5;head_2->x=1;head_2->y=5;if(head!=NULL)head->next=head_1;if(head_1!=NULL)head_1->next=head_2;if(head_2!=NULL)head_2->next=NULL;return head;}int keydown(int *z)//获取输入{char ch;if(kbhit()){ch=getch();switch(ch){case 'A':case 'a':if((*z)!=2) *z=1;break; case 'D':case 'd':if((*z)!=1)*z=2;break; case 'W':case 'w':if((*z)!=4)*z=3;break; case 'S':case 's':if((*z)!=3)*z=4;break; case 'E':case 'e':(*z)=5;break; //暂停default :break;}if(ch==27) *z=27;}return *z;}void delay(){for(int i=0;i<timelenX;i++)for(int j=0;j<timelenX;j++){}}void drawDot(int x,int y){x=x*20;y=y*20;setfillcolor(GREEN);bar(x+1,y+1,x+19,y+19);}void ReMoveDot(int x,int y){x=x*20;y=y*20;setfillcolor(BLACK);bar(x+1,y+1,x+19,y+19);}void mkfood(struct node *p2){//MoveTo(20,20);// gotoxy(20,20);////goto_pos(20,20);// cleardevice();struct node *p1;struct node *p;p=p1=p2;srand((unsigned)clock());//设定随机数种子food[1]=rand()%26+3;//随机产生食物坐标food[0]=rand()%28+1;//检测食物的坐标是否与蛇身体重复,如果是,则重新生成食物if(p!=NULL){do{if (food[0]==p->x&&food[1]==p->y){mkfood(p1);}p=p->next;}while(p!=NULL);}drawDot(food[0],food[1]);}void InitFill() //初始化填充{int x=0,y=0;for(int i=0;i<30;i++){setfillcolor(GREEN);x=i*20;y=0;bar(x+1,y+1,x+19,y+19);y=40;bar(x+1,y+1,x+19,y+19);y=580;bar(x+1,y+1,x+19,y+19);}for(int j=0;j<30;j++){setfillcolor(GREEN);y=j*20;x=0;bar(x+1,y+1,x+19,y+19);x=580;bar(x+1,y+1,x+19,y+19);}}void RecordDisp(){ch1[10];ch2[10];ch3[10];sprintf(ch1, "%d ", fen);sprintf(ch2, "%d ", speed);sprintf(ch3, "%d ", jilu);settextcolor(YELLOW);outtextxy(20,20,"分数:");outtextxy(150,20,"速度:");outtextxy(280,20,"最高纪录:");outtextxy(410,20,"保持者:");settextcolor(WHITE);outtextxy(55,20,ch1);outtextxy(185,20,ch2);outtextxy(350,20,ch3);outtextxy(465,20,jiluzhe);}int CheckSnake(struct node *p){struct node *p2;p2=p;int pointX=p2->x;int pointY=p2->y;if(pointX==29||pointY==29||pointX==0||pointY==2) return 0;while(p2!=NULL){p2=p2->next;if(p2!=NULL){if(pointX==p2->x&&pointY==p2->y)return 0;}}return 1;}。

贪吃蛇源代码(需要easy x,vc6.0可以成功编译运行)

贪吃蛇源代码(需要easy x,vc6.0可以成功编译运行)

#include <graphics.h>#include <stdlib.h>#include <time.h>//#include <dos.h>#include <conio.h>#include <stdio.h>//#include <winnt.h>#define MAX_JOINTS 200#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define MV_RIGHT 1#define MV_LEFT 2#define MV_UP 3#define MV_DOWN 4void InitGraph(void); /*图形驱动初始化函数*/void DrawFence(void); /*绘制游戏场景*/void GameOver(int score); /*结束游戏*/void GamePlay(void); /*玩游戏具体过程*/void PrScore(int score); /*输出成绩*/struct Food /*食物的结构体定义*/{int x; /*食物的横坐标*/int y; /*食物的纵坐标*/int addFood; /*判断是否要出现食物的变量*/};struct Snake /*蛇的结构体定义*/{int x[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的列坐标*/ int y[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的行坐标*/ int joint; /*蛇的节数*/int direction; /*蛇移动方向*/int life; /*蛇的生命,0活着,1死亡*/};/*主函数*/void main(void){InitGraph(); /*图形驱动*/DrawFence(); /*游戏场景*/GamePlay(); /*玩游戏具体过程*/closegraph(); /*图形结束*/}/*图形驱动初始化函数*/void InitGraph(void){int gd = DETECT, gm;initgraph(&gd, &gm, "");cleardevice();setbkcolor(BLUE);cleardevice();setcolor(WHITE);//settextstyle(DEFAULT_FONT, HORIZ_DIR, 3);setfont(32, 0, "宋体");outtextxy(170, 150, "Greedy Snake");outtextxy(219, 254, "Ready?");setcolor(BLUE);cleardevice();}/*游戏开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawFence(void){int i;setbkcolor(LIGHTGREEN);setcolor(11);//setlinestyle(SOLID_LINE, 0, THICK_WIDTH);setlinestyle(PS_SOLID, 0, 3);/*画围墙*/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){int i, key;//int gamespeed = 22000; /*控制游戏速度*/int gamespeed = 200;int score = 0; /*记录游戏得分*/struct Food food; /*食物结构体变量*/struct Snake snake; /*蛇结构体变量*/food.addFood = 1; /*1表示需要出现新食物,0表示已经存在食物*/ snake.life = 0; /*置蛇的生命状态为活着*/snake.direction = MV_RIGHT; /*置蛇头方向往右*/snake.x[0] = 100; snake.y[0] = 100; /*置蛇头初始位置*/snake.x[1] = 110; snake.y[1] = 100;snake.joint = 2; /*置蛇的初始节数为2*/PrScore(score); /*显示游戏得分*//*重复玩游戏,直到按Esc键结束*/srand(time(NULL));while (1){while (!kbhit())/*在没有按键的情况下,蛇自己移动身体*/{if (food.addFood == 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.addFood = 0; /*画面上有食物*/}if (food.addFood == 0) /*画面上有食物,则显示*/{setcolor(GREEN);rectangle(food.x, food.y, food.x+10, food.y-10);}for (i=snake.joint-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 MV_RIGHT: snake.x[0] += 10; break;case MV_LEFT: snake.x[0] -= 10; break;case MV_UP: snake.y[0] -= 10; break;case MV_DOWN: snake.y[0] += 10; break;}/*从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来*/for (i=3; i<snake.joint; i++){if (snake.x[i]==snake.x[0] && snake.y[i]==snake.y[0]){GameOver(score); /*显示失败*/snake.life = 1; /*蛇死*/break;}}/*判断蛇是否撞到墙壁*/if (snake.x[0]<55 || snake.x[0]>595|| snake.y[0]<55 || snake.y[0]>455){GameOver(score); /*本次游戏结束*/snake.life = 1; /*蛇死*/}/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/if (snake.life == 1) break;if (snake.x[0]==food.x && snake.y[0]==food.y) /*吃到食物后*/{/*把画面上的食物清除*/setcolor(0);rectangle(food.x, food.y, food.x+10, food.y-10);/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.x[snake.joint] =-20; snake.y[snake.joint] =-20;snake.joint++; /*蛇的身体长一节*/food.addFood = 1; /*画面上需要出现新食物*/score += 10;PrScore(score); /*输出新得分*/}/*画蛇*/setcolor(4);for (i=0; i<snake.joint; i++){rectangle(snake.x[i], snake.y[i],snake.x[i]+10, snake.y[i]-10);}//delay(gamespeed); /*延时控制蛇的速度*/Sleep(gamespeed);/*去除蛇的最后一节*/setcolor(BLUE);rectangle(snake.x[snake.joint-1], snake.y[snake.joint-1],snake.x[snake.joint-1]+10,snake.y[snake.joint-1]-10);} /*end of while(!kbhit)*/if (snake.life == 1) break; /*如果蛇死,则跳出循环*///key = bioskey(0); /*接收按键*/key = getch();/*if (kbhit()){key = getch();}*//*判断按键,是否往相反方向移动,按Esc键则退出*/ /* if (key == ESC) break;else if (key==UP && snake.direction!=4)snake.direction = MV_UP;else if (key==RIGHT && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key==LEFT && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key==DOWN && snake.direction!= MV_UP)snake.direction = MV_DOWN;*/if (key == ESC) break;else if (key=='W' && snake.direction!=4)snake.direction = MV_UP;else if (key=='D' && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key=='A' && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key=='S' && snake.direction!= MV_UP)snake.direction = MV_DOWN;} /*end of while(1)*/ }/*结束游戏*/void GameOver(int score){cleardevice();PrScore(score);setcolor(RED);//settextstyle(0, 0, 4);setfont(60, 0,"黑体");outtextxy(200, 200, "GAME OVER");getch();}/*输出成绩*/void PrScore(int score){char str[10];setfillstyle(SOLID_FILL, YELLOW);bar(50, 15, 220, 35);setcolor(6);//settextstyle(0, 0, 2);setfont(16, 0,"宋体");sprintf(str, "score:%d", score);outtextxy(55, 20, str);}。

安卓贪吃蛇源代码

安卓贪吃蛇源代码

安卓贪吃蛇源代码#define M 200#include"graphics.h"#include<stdlib.h>#include<stdio.h>#include<string.h>#include<iostream.h>#include<dos.h>#include<conio.h>#include <windows.h>#define LEFT 97//A#define RIGHT 100//D#define DOWN 115//S#define UP 119//W#define Esc 0x011bint i,key;int score=0;int gamespeed=250;//游戏速度可根据实际情况自行调整struct Food{int x;//食物的横坐标int y;//食物的纵坐标int yes;//判断是否要出现食物的变量}food;//食物的结构体struct Snake{int x[M];int y[M];int node;//蛇的节数int direction;//蛇的移动方向int life;//蛇的生命,0表示活着,1表示死亡}snake;void Init();//图形驱动void Close();//图形结束void DrawK();//开始画面void GamePlay();//玩游戏的具体过程void GameOver();//游戏结束void PrScore();//输出成绩void main()//主函数{Init();//图形驱动DrawK();//开始画面GamePlay();//玩游戏的具体过程Close();//图形结束}void Init()//图形驱动{int gd=DETECT,gm;initgraph(&gd,&gm," ");/*此处为turboc的路径,读者可以根据自己的电脑而改*/cleardevice();}void DrawK()//开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙{setbkcolor(GREEN);setcolor(LIGHTRED);setlinestyle(0,0,5);//设置线型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()//玩游戏的具体过程{rand();//随机数发生器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];}switch(snake.direction)//1,2,3,4表示上下左右四个方向,通过这个判断来移动蛇头{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(0);//把画面上的食物去掉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(WHITE);//画出蛇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(0);//用黑色去除蛇的最后一节rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);}if(snake.life==1)//如果蛇死就跳出循环break;key=getchar();//接受案件if(key==Esc)//按ESC键退出break;else if(key==UP&&snake.direction!=4)snake.direction=3;else if(key==RIGHT&&snake.direction!=2)snake.direction=1;else if(key==LEFT&&snake.direction!=1)snake.direction=2;else if(key==DOWN&&snake.direction!=3)snake.direction=4;}//endwhile(1)}void GameOver()//游戏结束{cleardevice();PrScore();setcolor(RED);outtextxy(100,100,"我会回来的!!!!!");getch();}void PrScore()//输出成绩{char str[10];setfillstyle(SOLID_FILL,YELLOW);bar(50,15,220,35);setcolor(6);sprintf(str,"score:%d",score);outtextxy(55,20,str);}void Close()//图形结束{getch();closegraph();}。

C语言贪吃蛇源代码

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

贪吃蛇游戏代码(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++)<>。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

*Snake为主Activity类。

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

贪吃蛇游戏代码

贪吃蛇游戏代码

贪吃蛇游戏代码贪吃蛇是一个经典的小游戏,可以在很多平台和设备上找到。

如果你想自己开发一个贪吃蛇游戏,这里有一个简单的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语⾔代码,⼀个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;。

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码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("游戏结束!")。

汇编语言写的贪吃蛇小游戏源代码

汇编语言写的贪吃蛇小游戏源代码

DATA SEGMENTdw 0,0snk db 1blk db 32food db 3tal1 db 4tal2 db 2adrs db 5len db ?pst db ?addrs dw ?frow db ?fcol db ?hwrt db ?gmov db 'game over press r to restart press q to quit $'score1 db 'score :$'score2 db ?score0 db 1zero db 48writer db 'Developer: Geniusdot $'email db ': geniusdotgmail.$'msg1 db 'The way to play the game:$'way db ' press w to up ,press s to down,press a to left,press d to right$' msg db 'Press any key(except a,s,d,w) to start$'DATA ENDSSTACK SEGMENT stackdb 200 dup(0)STACK ENDSCODE SEGMENTASSUME CS:CODE,DS:DATA,SS:STACKstart:mov ax,datamov ds,axmov ax,0mov es,axmov frow,10mov fcol,6mov dh,10mov dl,26mov ah,2int 10hmov ah,9lea dx,msg1 int 21hmov dh,11 mov dl,7mov ah,2mov bh,0int 10hmov ah,9lea dx,wayint 21hmov dh,12 mov dl,20 mov ah,2mov bh,0int 10hmov ah,9lea dx,msgint 21hmov ah,0int 16hmov ah,6mov al,0mov ch,0mov cl,0mov dh,24 mov dl,79 mov bh,10int 10hmov dh,0mov dl,0mov ah,2mov bh,0int 10hmov ah,9lea dx,score1 int 21hmov dl,15 mov ah,2mov bh,0int 10hlea dx,writerint 21hmov ah,9lea dx,emailint 21hmov score2,48push es:[9*4] ;将原int9入口地址保存pop ds:[0]push es:[9*4+2]pop ds:[2]mov word ptr es:[9*4],offset int9 ;更改中断向量表mov es:[9*4+2],csjmp aawrite macro row,col,cnt ;宏定义用于向当前光标处输出字符push bxpush cxpush dxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,9mov bl,11mov cx,1lea di,cnt ;50mov al,[di]int 10hpop dxpop cxpop bxendmreadh macro row,col ;宏定义用于读出当前光标处字符push dxpush bxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,08hint 10hmov pst,alpop bxpop axpop dxendmwnear macro ;宏定义只用在readcg宏中当readcg的所有判断都不成立调用此宏local wnext1local wnext2local wnext3local wnext4push dxdec dhreadh dh,dlcmp pst,1jne wnext1write dh,dl,tal2jmp wnext4wnext1:inc dhdec dlreadh dh,dlcmp pst,1jne wnext2write dh,dl,tal2jmp wnext4wnext2:inc dhinc dlreadh dh,dlcmp pst,1jne wnext3write dh,dl,tal2jmp wnext4dec dhinc dlreadh dh,dlcmp pst,1jne wnext4write dh,dl,tal2wnext4:pop dxendmreadcg macro row,col ;宏定义用于改变判断出来的字符local tnup,tnup1,tnup2,tnlf,tnlf1,tnlf2,tndn,tndn1,tndn2,tnrt,tnrt1,tnrt2,goout push bxpush axpush dxwrite dh,dl,tal1dec rowreadh dh,dlcmp pst,4jne tnup1jmp tnup2tnup1:jmp near ptr tnuptnup2:write dh,dl,blkinc dhinc dhreadh dh,dlcmp pst,1jne tnupwrite dh,dl,tal2jmp near ptr goouttnup:pop dxpush dxdec colreadh dh,dlcmp pst,4jne tnlf1jmp tnlf2tnlf1:jmp near ptr tnlf tnlf2:write dh,dl,blk inc dlinc dlreadh dh,dlcmp pst,1jne tnlfwrite dh,dl,tal2 jmp near ptr goout tnlf:pop dxpush dxinc rowreadh dh,dlcmp pst,4jne tndn1jmp tndn2tndn1:jmp near ptr tndn tndn2:write dh,dl,blk dec dhdec dhreadh dh,dlcmp pst,1jne tndnwrite dh,dl,tal2 jmp near ptr goout tndn:pop dxpush dxinc colreadh dh,dlcmp pst,4jne tnrt1jmp tnrt2tnrt1:jmp near ptr tnrt tnrt2:write dh,dl,blk dec dldec dlreadh dh,dlcmp pst,1jne tnrtwrite dh,dl,tal2jmp near ptr goouttnrt:pop dxpush dxwneargoout:pop dxpop axpop bxendmaddone: ;此标号功能是将蛇身增加一push dxinc score2mov dh,1mov dl,0mov cx,23cmpad1:push cxmov cx,79cmpad2:readh dh,dlcmp pst,2jne nextad3jmp nextad4nextad3:jmp near ptr nextadnextad4:write dh,dl,snkdec dhreadh dh,dlcmp pst,4jne natupwrite dh,dl,tal2dec dhwrite dh,dl,tal1jmp outonatup:inc dhreadh dh,dlcmp pst,4jne natlfwrite dh,dl,tal2 dec dlwrite dh,dl,tal1 jmp outonatlf:inc dhinc dlreadh dh,dlcmp pst,4jne natdnwrite dh,dl,tal2 inc dhwrite dh,dl,tal1 jmp outonatdn:dec dhinc dlreadh dh,dlcmp pst,4jne natrtwrite dh,dl,tal2 inc dlwrite dh,dl,tal1 natrt:outo:pop cxjmp near ptr endad nextad:inc dljmp nextad2chgad2:jmp near ptr cmpad2 nextad2:loop chgad2sub dl,79inc dhpop cxjmp nextad1chgad1:jmp near ptr cmpad1loop chgad1endad:pop dxjmp near ptr crtfaa: ;从这开始产生最原始的蛇mov addrs,offset turnrightmov dh,10mov dl,1mov cx,3write dh,dl,tal1inc dlwrite dh,dl,tal2wrt:inc dlwrite dh,dl,snkloop wrtmov len,6mov ax,0jmp wrt1ovflw: ;当蛇碰壁或自身转到此游戏结束mov ah,6mov al,0mov ch,0mov cl,0mov dh,24mov dl,79mov bh,7int 10hmov dh,17mov dl,17mov ah,2mov bh,0int 10hmov ah,9lea dx,gmovint 21hmov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]stop:mov ah,0int 16hcmp al,'r'je aa1jmp aa2aa1:jmp near ptr startaa2:cmp al,'q'jne stopjmp near ptr exitwrt1: ;此处蛇行走过程的无限循环call dlypush dxinc dhcmp dh,25je ovflwinc dlcmp dl,80je ovflwpop dxpush dxdec dhcmp dh,0je ovflwdec dlcmp dl,-1je ovflwpop dxpush dxlea ax,turnrightcmp addrs,axjne tonxt2inc dlreadh dh,dlcmp pst,1je tonxt1cmp pst,2je tonxt1cmp pst,4je tonxt1jmp tonxt2 tonxt1:jmp ovflwtonxt2:pop dxpush dxlea ax,turnup cmp addrs,ax jne tonxt4dec dhreadh dh,dl cmp pst,1je tonxt3cmp pst,2je tonxt3cmp pst,4je tonxt3jmp tonxt4 tonxt3:jmp ovflwtonxt4:pop dxpush dxlea ax,turndown cmp addrs,ax jne tonxt6inc dhreadh dh,dl cmp pst,1je tonxt5cmp pst,2je tonxt5cmp pst,4je tonxt5jmp tonxt6 tonxt5:jmp ovflwtonxt6:pop dxpush dxlea ax,turnback cmp addrs,axjne tonxt8dec dlreadh dh,dlcmp pst,1je tonxt7cmp pst,2je tonxt7cmp pst,4je tonxt7jmp tonxt8tonxt7:jmp ovflwtonxt8:pop dxjmp nextacrtf1:jmp near ptr addone crtf:call rand1call rand2inc frowmov ah,frowmov al,fcolpush dxmov dh,1mov dl,0push cxmov cx,23check1:push cxmov cx,79check2:readh dh,dlcmp pst,1je nextncmp pst,2je nextncmp pst,4je nextnjmp nextnnnextn:cmp ax,dxje crtfnextnn:inc dlloop check2inc dhsub dl,79pop cxloop check1pop cxpop dxwrite frow,fcol,food nexta:mov ah,frowmov al,fcolcmp ax,dxje crtf12jmp crtf13crtf12:jmp near ptr crtf1 crtf13:push dxcmp score2,58jl normalmov score2,49inc score0normal:mov dh,0mov dl,8write dh,dl,score2 add dl,score0write dh,dl,zeropop dxcmp adrs,17je jmp1cmp adrs,145je jmp1cmp adrs,31je jmp2cmp adrs,159je jmp2cmp adrs,32je jmp3cmp adrs,160je jmp3cmp adrs,30je jmp4cmp adrs,158je jmp4jmp addrsjmp1:lea ax, turndowncmp ax,addrsje jmp2mov addrs,offset turnupjmp near ptr turnupjmp2:lea ax,turnupcmp ax,addrsje jmp1mov addrs,offset turndownjmp near ptr turndownjmp3:lea ax,turnbackcmp ax,addrsje jmp4mov addrs,offset turnrightjmp near ptr turnrightjmp4:lea ax,turnrightcmp ax,addrsje jmp3mov addrs,offset turnbackjmp near ptr turnbackturnright: ;此处实现蛇向左走push dxmov dh,1mov dl,0mov cx,23cmpr1:push cxmov cx,79cmpr2:readh dh,dlcmp pst,2je nextr4jmp near ptr nextrnextr4:readcg dh,dlpop cxjmp near ptr endrnextr:inc dljmp nextr2chgr2:jmp near ptr cmpr2nextr2:loop chgr2sub dl,79inc dhpop cxjmp nextr1chgr1:jmp near ptr cmpr1nextr1:loop chgr1endr:pop dxinc dlwrite dh,dl,snkjmp near ptr wrt1turnup: ;此处实现蛇向上走push dxmov dh,1mov dl,0mov cx,23cmpu1:push cxmov cx,79cmpu2:readh dh,dlcmp pst,2jne nextu3jmp nextu4nextu3:jmp near ptr nextunextu4:readcg dh,dlpop cxjmp near ptr endunextu:inc dljmp nextu2chgu2:jmp near ptr cmpu2nextu2:loop chgu2sub dl,79inc dhpop cxjmp nextu1chgu1:jmp near ptr cmpu1nextu1:loop chgu1endu:pop dxdec dhwrite dh,dl,snkjmp near ptr wrt1turndown: ;此处实现蛇向下走push dxmov dh,1mov dl,0mov cx,23cmpd1:push cxmov cx,79cmpd2:readh dh,dlcmp pst,2jne nextd3jmp nextd4nextd3:jmp near ptr nextdnextd4:readcg dh,dlpop cxjmp near ptr enddnextd:inc dljmp nextd2chgd2:jmp near ptr cmpd2nextd2:loop chgd2sub dl,79inc dhpop cxjmp nextd1chgd1:jmp near ptr cmpd1nextd1:loop chgd1endd:pop dxinc dhwrite dh,dl,snkjmp near ptr wrt1turnback: ;此处实现蛇向右走push dxmov dh,1mov dl,0mov cx,23cmpb1:push cxmov cx,79cmpb2:readh dh,dlcmp pst,2jne nextb3jmp nextb4nextb3:jmp near ptr nextbnextb4:readcg dh,dlpop cxjmp near ptr endbnextb:jmp nextb2chgb2:jmp near ptr cmpb2nextb2:loop chgb2sub dl,79inc dhpop cxjmp nextb1chgb1:jmp near ptr cmpb1nextb1:loop chgb1endb:pop dxdec dlwrite dh,dl,snkjmp near ptr wrt1exit:mov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]mov ah,4chint 21hint9: ;更改后的中断服务程序push axin al,60hmov adrs,almov al,20hout 20h,aliretDLY PROC near ;延时子程序PUSH CXPUSH DXMOV DX,10000DL1: MOV CX,9801DL2: LOOP DL2DEC DXJNZ DL1POP DXPOP CXRETDLY ENDPRAND1 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,23 ;除23,产生0~23余数DIV DLMOV frow,AH ;余数存frow,作随机行数 POP AXPOP DXPOP CXRETRAND1 ENDPRAND2 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,79 ;除79,产生0~79余数DIV DLMOV fcol,AH ;余数存fcol,作随机列数 POP AXPOP DXPOP CXRETRAND2 ENDPCODE ENDSEND start。

Java贪吃蛇游戏源代码

Java贪吃蛇游戏源代码

import java.awt.Color;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.InputEvent;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JCheckBoxMenuItem;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.KeyStroke;public class 贪吃蛇extends JFrame implements ActionListener, KeyListener,Runnable {private static final long serialV ersionUID = 1L;private JMenuBar menuBar;private JMenu youXiMenu,nanDuMenu,fenShuMenu,guanY uMenu;private JMenuItem kaiShiY ouXi,exitItem,zuoZheItem,fenShuItem;private JCheckBoxMenuItem cJianDan,cPuTong,cKunNan;private int length = 6;private Toolkit toolkit;private int i,x,y,z,objectX,objectY,object=0,growth=0,time;//bojectX,Yprivate int m[]=new int[50];private int n[]=new int[50];private Thread she = null;private int life=0;private int foods = 0;private int fenshu=0;public void run(){time=500;for(i=0;i<=length-1;i++){m[i]=90-i*10;n[i]=60;}x=m[0];y=n[0];z=4;while(she!=null){check();try{Thread.sleep(time);}catch(Exception ee){System.out.println(z+"");}}}public 贪吃蛇() {setVisible(true);menuBar = new JMenuBar();toolkit=getToolkit();youXiMenu = new JMenu("游戏");kaiShiY ouXi = new JMenuItem("开始游戏"); exitItem = new JMenuItem("退出游戏");nanDuMenu = new JMenu("困难程度"); cJianDan = new JCheckBoxMenuItem("简单"); cPuTong = new JCheckBoxMenuItem("普通"); cKunNan = new JCheckBoxMenuItem("困难");fenShuMenu = new JMenu("积分排行"); fenShuItem = new JMenuItem("最高记录");guanY uMenu = new JMenu("关于");zuoZheItem = new JMenuItem("关于作者");guanY uMenu.add(zuoZheItem);nanDuMenu.add(cJianDan);nanDuMenu.add(cPuTong);nanDuMenu.add(cKunNan);fenShuMenu.add(fenShuItem);youXiMenu.add(kaiShiY ouXi);youXiMenu.add(exitItem);menuBar.add(youXiMenu);menuBar.add(nanDuMenu);menuBar.add(fenShuMenu);menuBar.add(guanY uMenu);zuoZheItem.addActionListener(this);kaiShiY ouXi.addActionListener(this);exitItem.addActionListener(this);addKeyListener(this);fenShuItem.addActionListener(this);KeyStroke keyOpen = KeyStroke.getKeyStroke('O',InputEvent.CTRL_DOWN_MASK); kaiShiY ouXi.setAccelerator(keyOpen);KeyStroke keyExit = KeyStroke.getKeyStroke('X',InputEvent.CTRL_DOWN_MASK); exitItem.setAccelerator(keyExit);setJMenuBar(menuBar);setTitle("贪吃蛇");setResizable(false);setBounds(300,200,400,400);validate();setDefaultCloseOperation(EXIT_ON_CLOSE);}public static void main(String args[]) {new 贪吃蛇();}public void actionPerformed(ActionEvent e){if(e.getSource()==kaiShiY ouXi){length = 6;life = 0;foods = 0;if(she==null){she=new Thread(this);she.start();}else if(she!=null){she=null;she= new Thread(this);she.start();}}if(e.getSource()==exitItem){System.exit(0);}if(e.getSource()==zuoZheItem){JOptionPane.showMessageDialog(this, "孤独的野狼制作"+"\n\n"+" "+"QQ号:2442701497"+"\n");}if(e.getSource()==fenShuItem){JOptionPane.showMessageDialog(this,"最高记录为"+fenshu+"");}}public void check(){isDead();if(she!=null){if(growth==0){reform(); //得到食物}else{upgrowth(); //生成食物}if(x==objectX&&y==objectY){object=0;growth=1;toolkit.beep();}if(object==0){object=1;objectX=(int)Math.floor(Math.random()*39)*10;objectY=(int)Math.floor(Math.random()*29)*10+50;}this.repaint(); //重绘}}void isDead(){//判断游戏是否结束的方法if(z==4){x=x+10;}else if(z==3){x=x-10;}else if(z==2){y=y+10;}else if(z==1){y=y-10;}if(x<0||x>390||y<50||y>390){she=null;}for(i=1;i<length;i++){if(m[i]==x&&n[i]==y){she=null;}}}public void upgrowth(){//当蛇吃到东西时的方法if(length<50){length++;}growth--;time=time-10;reform();life+=100;if(fenshu<life){fenshu = life;}foods++;}public void reform(){for(i=length-1;i>0;i--){m[i]=m[i-1];n[i]=n[i-1];}if(z==4){m[0]=m[0]+10;}if(z==3){m[0]=m[0]-10;}if(z==2){n[0]=n[0]+10;}if(z==1){n[0]=n[0]-10;}}public void keyPressed(KeyEvent e) {if(she!=null){if(e.getKeyCode()==KeyEvent.VK_UP){if(z!=2){z=1;check();}}else if(e.getKeyCode()==KeyEvent.VK_DOWN) {if(z!=1){z=2;check();}}else if(e.getKeyCode()==KeyEvent.VK_LEFT){if(z!=4){z=3;check();}}else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {if(z!=3){z=4;check();}}}}public void keyReleased(KeyEvent e){}public void keyTyped(KeyEvent e){}public void paint(Graphics g) {g.setColor(Color.DARK_GRAY); //设置背景g.fillRect(0,50,400,400);g.setColor(Color.pink);for(i=0;i<=length-1;i++){g.fillRect(m[i],n[i],10,10);}g.setColor(Color.green); //蛇的食物g.fillRect(objectX,objectY,10,10);g.setColor(Color.white);g.drawString("当前分数"+this.life,6,60);g.drawString("当前已吃食物数"+this.foods,6,72); }}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

附录1.SnakeView类package com.example.android_snake.view;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import com.example.android_snake.R;import com.example.android_snake.food.Food;import com.example.android_snake.snake.Body;import com.example.android_snake.snake.Head;import com.example.android_snake.snake.Snake;import com.example.android_snake.snake.SnakeDirection; import com.example.android_snake.stone.Stone;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.os.Handler;import android.util.DisplayMetrics;import android.view.Display;import android.view.MotionEvent;import android.view.View;import android.view.ViewManager;import android.view.WindowManager;import android.widget.Toast;public class SnakeView extends View {private Context context;private Bitmap headBitmap;private Bitmap bodyBitmap;private Bitmap foodBitmap;private Bitmap stoneBitmap;// 屏幕的高度和宽度private int screenHeight;private int screenWidth;// 每个小格子的高度和宽度private int eachHeight;private int eachWidth;private Snake snake;private Food food;private Stone stone;private int [] listx;private int [] listy;private Timer timer = new Timer();Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {moveSnake();invalidate();}};public SnakeView(Context context) {super(context);this.context = context;listx =new int[100];listy =new int[100];// 获得屏幕的高和宽DisplayMetrics metrics = new DisplayMetrics();WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);windowManager.getDefaultDisplay().getMetrics(metrics);screenHeight = metrics.heightPixels;screenWidth = metrics.widthPixels;eachHeight = screenHeight / 32;eachWidth = screenWidth / 20;// 初始化图片headBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.head);bodyBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.body);foodBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.food);stoneBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.stone);this.initSnake();this.initFood();this.initstone();gameRun();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint paint = new Paint();// 定义画笔paint.setColor(Color.GRAY);// 设置画笔颜色paint.setAntiAlias(true);// 去除锯齿paint.setStyle(Style.STROKE);// 设置空心实心paint.setTextSize(40);drawLines(canvas, paint);drawStone(canvas, paint);if(isCollide()){canvas.drawText("Game Over!", screenWidth/4, screenHeight/3, paint);canvas.drawText("得分", screenWidth/4, screenHeight/2, paint);timer.cancel();}else{this.drawSnake(canvas, paint);}boolean flag = IsRectCollision(snake.getHead().getPointX(), snake.getHead().getPointY(), eachWidth, eachHeight,food.getPointX(), food.getPointY(), eachWidth, eachHeight);if (flag) {food = null;snake.getBodyList().add(new Body());this.initFood();this.initstone();} else {this.drawFood(canvas, paint);this.drawStone(canvas, paint);}}//方向控制@Overridepublic boolean onTouchEvent(MotionEvent event) {int x = (int) event.getX();int y = (int) event.getY();SnakeDirection nowDir = snake.getSnakeDirection();int m = -screenHeight * x + screenHeight * screenWidth - screenWidth * y;int n = screenHeight * x - screenWidth * y;if ((m > 0 && n > 0) && (nowDir != SnakeDirection.DOWN)) {snake.setSnakeDirection(SnakeDirection.UP);} else if ((m > 0 && n < 0) && (nowDir != SnakeDirection.RIGHT)) { snake.setSnakeDirection(SnakeDirection.LEFT);} else if ((m < 0 && n > 0) && (nowDir != SnakeDirection.LEFT)) { snake.setSnakeDirection(SnakeDirection.RIGHT);} else if ((m < 0 && n < 0) && (nowDir != SnakeDirection.UP)) { snake.setSnakeDirection(SnakeDirection.DOWN);}return super.onTouchEvent(event);}public void gameRun() {timer.scheduleAtFixedRate(new TimerTask() {public void run() {handler.obtainMessage().sendToTarget();}}, 100, 400);}/** 画网格线*/public void drawLines(Canvas canvas, Paint paint) {int startX = 0, startY = 0;for (int i = 0; i < 100; i++) {canvas.drawLine(0, startY, screenWidth, startY, paint);startY = startY + eachHeight;}for (int i = 0; i < 100; i++) {canvas.drawLine(startX, 0, startX, screenHeight, paint);startX = startX + eachWidth;}canvas.drawLine(0, 0, screenWidth, screenHeight, paint);canvas.drawLine(0, screenHeight, screenWidth, 0, paint);}// 初始化蛇public void initSnake() {List<Body> bodies = new ArrayList<Body>();Head head = new Head(eachWidth * 4, eachHeight * 2, headBitmap);Body body1 = new Body(eachWidth * 3, eachHeight * 2, bodyBitmap);Body body2 = new Body(eachWidth * 2, eachHeight * 2, bodyBitmap);Body body3 = new Body(eachWidth * 1, eachHeight * 2, bodyBitmap);Body body4 = new Body(eachWidth * 0, eachHeight * 2, bodyBitmap);bodies.add(body1);bodies.add(body2);bodies.add(body3);bodies.add(body4);snake = new Snake(head, bodies, SnakeDirection.RIGHT);}// 画蛇public void drawSnake(Canvas canvas, Paint paint) {canvas.drawBitmap(headBitmap, snake.getHead().getPointX(), snake .getHead().getPointY(), paint);for (int i = 0; i < snake.getBodyList().size(); i++) {canvas.drawBitmap(bodyBitmap, snake.getBodyList().get(i).getPointX(), snake.getBodyList().get(i).getPointY(), paint);}}// 改变蛇身的位置public void changSnakePosition(int pointX, int pointY) {for (int i = snake.getBodyList().size() - 1; i > 0; i--) {snake.getBodyList().get(i).setPointX(snake.getBodyList().get(i - 1).getPointX());snake.getBodyList().get(i).setPointY(snake.getBodyList().get(i - 1).getPointY());}snake.getBodyList().get(0).setPointX(snake.getHead().getPointX());snake.getBodyList().get(0).setPointY(snake.getHead().getPointY());}// 移动蛇public void moveSnake() {int nowPointX = snake.getHead().getPointX();int nowPointY = snake.getHead().getPointY();if (snake.getSnakeDirection() == SnakeDirection.RIGHT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX >= screenWidth - eachWidth) {snake.getHead().setPointX(0);} else {snake.getHead().setPointX(nowPointX + eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.DOWN) { changSnakePosition(nowPointX, nowPointY);if (nowPointY >= screenHeight - eachHeight) {snake.getHead().setPointY(0);} else {snake.getHead().setPointY(nowPointY + eachHeight);}} else if (snake.getSnakeDirection() == SnakeDirection.LEFT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX <= 0) {snake.getHead().setPointX(screenWidth - eachWidth);} else {snake.getHead().setPointX(nowPointX - eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.UP) {changSnakePosition(nowPointX, nowPointY);if (nowPointY <= 0) {snake.getHead().setPointY(screenHeight - eachHeight);} else {snake.getHead().setPointY(nowPointY - eachHeight);}}}// 初始化foodpublic void initFood() {int x = new Random().nextInt(19);int y = new Random().nextInt(29);food = new Food(eachWidth * x, eachHeight * y, foodBitmap);}// 在界面上画出Foodpublic void drawFood(Canvas canvas, Paint paint) {if (food != null) {canvas.drawBitmap(foodBitmap, food.getPointX(), food.getPointY(),paint);}}// 初始化stonepublic void initstone() {int x = new Random().nextInt(17);int y = new Random().nextInt(23);stone = new Stone(eachWidth * x, eachHeight * y, stoneBitmap);int i=0,j=0;listx[i++]=x;listy[j++]=y;}// 在界面上画出Stonepublic void drawStone(Canvas canvas, Paint paint) {if (true) {canvas.drawBitmap(stoneBitmap, stone.getPointX(), stone.getPointY(),paint);for(int k=0;k<100;k++){//food = new Food(eachWidth * listx[k], eachHeight * listy[k], foodBitmap);//canvas.drawBitmap(stoneBitmap,listx[k], listy[k],paint);}}}/*** 矩形碰撞检测参数为x,y,width,height** @param x1* 第一个矩形的x* @param y1* 第一个矩形的y* @param w1* 第一个矩形的w* @param h1* 第一个矩形的h* @param x2* 第二个矩形的x* @param y2* 第二个矩形的y* @param w2* 第二个矩形的w* @param h2* 第二个矩形的h* @return是否碰撞*/public boolean IsRectCollision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {if (x2 > x1 && x2 >= x1 + w1) {return false;} else if (x2 < x1 && x2 <= x1 - w2) {return false;} else if (y2 > y1 && y2 >= y1 + h1) {return false;} else if (y2 < y1 && y2 <= y1 - h2) {return false;} else {return true;}}//检测蛇头是否与蛇身碰撞//检测蛇头与墙的碰撞//public boolean isCollide() {boolean flag = false;for (int i = 0; i < snake.getBodyList().size(); i++) {flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,snake.getBodyList().get(i).getPointX(),snake.getBodyList().get(i).getPointY(),eachWidth,eachHeight);for(int j=0;j<100;j++){flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,listx[j],listy[j], eachWidth,eachHeight);if(flag){break;}}if ((snake.getHead().getPointX() < 1) ||(snake.getHead().getPointY() < 1) ||(snake.getHead().getPointX() > screenWidth - 1)||(snake.getHead().getPointY() > screenHeight - 1)){flag = true;}if(flag){break;}}return flag;}}2.MainActivity类package com.example.android_snake;import com.example.android_snake.R;import com.example.android_snake.view.SnakeView;//Downloads By import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.Window;import android.view.WindowManager;public class MainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);//设置全屏getWindow().setFlags(youtParams.FLAG_FULLSCREEN, youtParams.FLAG_FULLSCREEN);SnakeView view = new SnakeView(this);setContentView(view);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu);return true;}}3.Food类package com.example.android_snake.food;import android.graphics.Bitmap;public class Food {private int pointX;private int pointY;private Bitmap foodBitmap;public Food() {super();}public Food(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.foodBitmap = foodBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getFoodBitmap() {return foodBitmap;}public void setFoodBitmap(Bitmap foodBitmap) {this.foodBitmap = foodBitmap;}}4.Body类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Body {private int pointX;private int pointY;private Bitmap bodyBitMap;public Body() {super();}public Body(int pointX, int pointY, Bitmap bodyBitMap) { super();this.pointX = pointX;this.pointY = pointY;this.bodyBitMap = bodyBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getBodyBitMap() {return bodyBitMap;}public void setBodyBitMap(Bitmap bodyBitMap) {this.bodyBitMap = bodyBitMap;}}5.Head类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Head {private int pointX;private int pointY;private Bitmap headBitMap;public Head() {super();}public Head(int pointX, int pointY, Bitmap headBitMap) {super();this.pointX = pointX;this.pointY = pointY;this.headBitMap = headBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getHeadBitMap() {return headBitMap;}public void setHeadBitMap(Bitmap headBitMap) {this.headBitMap = headBitMap;}}6.Snake类package com.example.android_snake.snake;import java.util.ArrayList;import java.util.List;import android.graphics.Bitmap;public class Snake {private Head head;private Body body;private List<Body> bodyList;private SnakeDirection snakeDirection;public Snake(){}public Snake(Head head,List<Body> bodyList,SnakeDirection snakeDirection){ super();this.head = head;this.bodyList = bodyList;this.snakeDirection = snakeDirection;}public Head getHead() {return head;}public void setHead(Head head) {this.head = head;}public Body getBody() {return body;}public void setBody(Body body) {this.body = body;}public List<Body> getBodyList() {return bodyList;}public void setBodyList(List<Body> bodyList) {this.bodyList = bodyList;}public SnakeDirection getSnakeDirection() {return snakeDirection;}public void setSnakeDirection(SnakeDirection snakeDirection) { this.snakeDirection = snakeDirection;}}7.SnakeDirection类package com.example.android_snake.snake;public enum SnakeDirection {UP,DOWN,LEFT,RIGHT;}8.Stone类package com.example.android_snake.stone;import android.graphics.Bitmap;public class Stone {private int pointX;private int pointY;private Bitmap stoneBitmap;public Stone() {super();}public Stone(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.stoneBitmap = stoneBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getStoneBitmap() {return stoneBitmap;}public void setFoodBitmap(Bitmap foodBitmap) { this.stoneBitmap = stoneBitmap;}}。

相关文档
最新文档