贪吃蛇代码
贪吃蛇小游戏源代码
}
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(); }。
贪吃蛇游戏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实现的贪吃蛇小游戏代码:```pythonimport pygameimport random# 初始化Pygamepygame.init()# 设置游戏窗口大小和标题screen_width = 480screen_height = 480game_display = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption('贪吃蛇游戏')# 定义颜色white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)green = (0, 255, 0)# 定义蛇的初始位置和尺寸snake_block_size = 20snake_speed = 10initial_snake_pos = {'x': screen_width/2, 'y': screen_height/2}snake_list = [initial_snake_pos]# 定义食物的尺寸和位置food_block_size = 20food_pos = {'x': round(random.randrange(0, screen_width - food_block_size) / 20.0) * 20.0, 'y': round(random.randrange(0, screen_height - food_block_size) / 20.0) * 20.0}# 定义分数、字体和大小score = 0font_style = pygame.font.SysFont(None, 30)# 刷新分数def refresh_score(score):score_text = font_style.render("Score: " + str(score), True, black)game_display.blit(score_text, [0, 0])# 绘制蛇def draw_snake(snake_block_size, snake_list):for pos in snake_list:pygame.draw.rect(game_display, green, [pos['x'], pos['y'], snake_block_size, snake_block_size])# 显示消息def message(msg, color):message_text = font_style.render(msg, True, color)game_display.blit(message_text, [screen_width/6, screen_height/3])# 主函数循环def game_loop():game_over = Falsegame_close = False# 设置蛇头的初始移动方向x_change = 0y_change = 0# 处理事件while not game_over:while game_close:game_display.fill(white)message("You lost! Press Q-Quit or C-Play Again", red)refresh_score(score)pygame.display.update()# 处理重新开始和退出事件for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseelif event.key == pygame.K_c:game_loop()# 处理按键事件for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x_change = -snake_block_sizey_change = 0elif event.key == pygame.K_RIGHT:x_change = snake_block_sizey_change = 0elif event.key == pygame.K_UP:y_change = -snake_block_sizex_change = 0elif event.key == pygame.K_DOWN:y_change = snake_block_sizex_change = 0# 处理蛇的移动位置if snake_list[-1]['x'] >= screen_width or snake_list[-1]['x'] < 0 or snake_list[-1]['y'] >= screen_height or snake_list[-1]['y'] < 0:game_close = Truesnake_list[-1]['x'] += x_changesnake_list[-1]['y'] += y_change# 处理食物被吃掉的情况if snake_list[-1]['x'] == food_pos['x'] and snake_list[-1]['y'] == food_pos['y']:score += 10food_pos = {'x': round(random.randrange(0, screen_width -food_block_size) / 20.0) * 20.0,'y': round(random.randrange(0, screen_height -food_block_size) / 20.0) * 20.0}else:snake_list.pop(0)# 处理蛇撞到自身的情况for pos in snake_list[:-1]:if pos == snake_list[-1]:game_close = True# 刷新游戏窗口game_display.fill(white)draw_snake(snake_block_size, snake_list)pygame.draw.rect(game_display, red, [food_pos['x'], food_pos['y'], food_block_size, food_block_size])refresh_score(score)pygame.display.update()# 设置蛇移动的速度clock = pygame.time.Clock()clock.tick(snake_speed)pygame.quit()quit()game_loop()```当您运行此代码时,将会启动一个贪吃蛇小游戏。
超简单贪吃蛇c语言代码编写
超简单贪吃蛇c语言代码编写贪吃蛇其实就是实现以下几步——1:蛇的运动(通过“画头擦尾”来达到蛇移动的视觉效果)2:生成食物3:蛇吃食物(实现“画头不擦尾”)4:游戏结束判断(也就是蛇除了食物,其余东西都不能碰)#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>#include<time.h>#define width 60#define hight 25#define SNAKESIZE 200//蛇身的最长长度int key=72;//初始化蛇的运动方向,向上int changeflag=1;//用来标识是否生成食物,1表示蛇还没吃到食物,0表示吃到食物int speed=0;//时间延迟struct {int len;//用来记录蛇身每个方块的坐标int x[SNAKESIZE];int y[SNAKESIZE];int speed;}snake;struct{int x;int y;}food;void gotoxy(int x,int y)//调用Windows的API函数,可以在控制台的指定位置直接操作,这里可暂时不用深究{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }//■○void drawmap(){//打印图框for (int _y = 0; _y < hight; _y++){for (int x = 0; x < width; x+=2){if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2){gotoxy(x, _y);printf("■");}}}//打印蛇头snake.len=3;snake.x[0]=width/2;snake.y[0]=hight/2;gotoxy(snake.x[0],snake.y[0]);printf("■");//打印蛇身for(int i=1;i<snake.len;i++){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1]+1;gotoxy(snake.x[i],snake.y[i]);printf("■");}//初始化食物的位置food.x=20;food.y=20;gotoxy(food.x,food.y);printf("○");}/**控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*/void snake_move()//按键处理函数{int history_key=key;if (_kbhit()){fflush(stdin);key = _getch();key = _getch();}if(changeflag==1)//还没吃到食物,把尾巴擦掉{gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);printf(" ");}for(int i=snake.len-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}if(history_key==72&&key==80)key=72;if(history_key==80&&key==72)key=80;if(history_key==75&&key==77)key=75;if(history_key==77&&key==75)key=77;switch(key){case 72:snake.y[0]--;break;case 75:snake.x[0]-= 2;break;case 77:snake.x[0]+= 2;break;case 80:snake.y[0]++;break;}gotoxy(snake.x[0],snake.y[0]);printf("■");gotoxy(0,0);changeflag=1;}void creatfood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//只有蛇吃到食物,才能生成新食物{changeflag=0;snake.len++;if(speed<=100)speed+=10;while(1){srand((unsigned int) time(NULL));food.x=rand()%(width-6)+2;//限定食物的x范围不超出围墙,但不能保证food.x 为偶数food.y=rand()%(hight-2)+1;for(int i=0;i<snake.len;i++){if(food.x==snake.x[i]&&food.y==snake.y[i])//如果产生的食物与蛇身重合则退出break;}if(food.x%2==0)break;//符合要求,退出循环}gotoxy(food.x,food.y);printf("○");}}bool Gameover(){//碰到围墙,OVERif(snake.x[0]==0||snake.x[0]==width-2)return false;if(snake.y[0]==0||snake.y[0]==hight-1) return false;//蛇身达到最长,被迫OVERif(snake.len==SNAKESIZE)return false;//头碰到蛇身,OVERfor(int i=1;i<snake.len;i++){if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i])return false;}return true;}int main(){system("mode con cols=60 lines=27");drawmap();while(Gameover()){snake_move();creatfood();Sleep(350-speed);//蛇的移动速度}return 0;}。
贪吃蛇游戏代码(C语言编写)
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); }
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))
struct 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};
贪吃蛇游戏代码+备注解释
#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;
java贪吃蛇 代码
代码:一:::::::public class Cell {// 格子:食物或者蛇的节点private int x;private int y;private Color color;// 颜色public Cell() {}public Cell(int x, int y) {this.x = x;this.y = y;}public Cell(int x, int y, Color color) { this.color = color;this.x = x;this.y = y;}public Color getColor() {return color;}public int getX() {return x;}public int getY() {return y;}public String toString() {return"[" + x + "]" + "[" + y + "]";}}二::::::::::public class Worm {private int currentDirection;// 蛇包含的格子private Cell[] cells;private Color color;public static final int UP = 1;public static final int DOWN = -1;public static final int RIGHT = 2;public static final int LEFT = -2;// 创建对象创建默认的蛇:(0,0)(1,0)(2,0)······(11,0)public Worm() {// 构造器初始化对象color = Color.pink;// 蛇的颜色cells = new Cell[12];// 创建数组对象for (int x = 0, y = 0, i = 0; x < 12; x++) { // for(int y=0;;){}cells[i++] = new Cell(x, y, color);// 添加数组元素}currentDirection = DOWN;}public boolean contains(int x, int y) {// 数组迭代for (int i = 0; i < cells.length; i++) {Cell cell = cells[i];if (cell.getX() == x && cell.getY() == y) {return true;}}return false;}public String toString() {return Arrays.toString(cells);}public void creep() {for (int i = this.cells.length - 1; i >= 1; i--) {cells[i] = cells[i - 1];}cells[0] = createHead(currentDirection);}// 按照默认方法爬一步private Cell createHead(int direction) {// 根据方向,和当前(this)的头结点,创建新的头结点int x = cells[0].getX();int y = cells[0].getY();switch (direction) {case DOWN:y++;break;case UP:y--;break;case RIGHT:x++;break;case LEFT:x--;break;}return new Cell(x, y);}/*** food 食物**/public boolean creep(Cell food) {Cell head = createHead(currentDirection);boolean eat = head.getX() == food.getX() && head.getY() == food.getY();if (eat) {Cell[] ary = Arrays.copyOf(cells, cells.length + 1);cells = ary;// 丢弃原数组}for (int i = cells.length - 1; i >= 1; i--) { cells[i] = cells[i - 1];}cells[0] = head;return eat;}// 吃到东西就变长一格public boolean creep(int direction, Cell food) {if (currentDirection + direction == 0) {return false;}this.currentDirection = direction;Cell head = createHead(currentDirection);boolean eat = head.getX() == food.getX() && head.getY() == food.getY();if (eat) {Cell[] ary = Arrays.copyOf(cells, cells.length + 1);cells = ary;// 丢弃原数组}for (int i = cells.length - 1; i >= 1; i--) { cells[i] = cells[i - 1];}cells[0] = head;return eat;}// 检测在新的运动方向上是否能够碰到边界和自己(this 蛇)public boolean hit(int direction) {// 生成下个新头节点位置// 如果新头节点出界返回true,表示碰撞边界// ···············if (currentDirection + direction == 0) {return false;}Cell head = createHead(direction);if(head.getX() < 0 || head.getX() >= WormStage.COLS || head.getY() < 0|| head.getY() >= WormStage.ROWS) {return true;}for (int i = 0; i < cells.length - 1; i++) { if (cells[i].getX() == head.getX()&& cells[i].getY() == head.getY()) {return true;}}return false;}public boolean hit() {return hit(currentDirection);}// 为蛇添加会制方法// 利用来自舞台面板的画笔绘制蛇public void paint(Graphics g) {g.setColor(this.color);for (int i = 0; i < cells.length; i++) {Cell cell = cells[i];g.fill3DRect(cell.getX() * WormStage.CELL_SIZE, cell.getY()* WormStage.CELL_SIZE, WormStage.CELL_SIZE,WormStage.CELL_SIZE, true);}}}三:::::::::public class WormStage extends JPanel {/** 舞台的列数 */public static final int COLS = 35;/** 舞台的行数 */public static final int ROWS = 35;/** 舞台格子的大小 */public static final int CELL_SIZE = 10;private Worm worm;private Cell food;public WormStage() {worm = new Worm();food = createFood();}/*** 随机生成食物,要避开蛇的身体 1 生成随机数 x, y 2 检查蛇是否包含(x,y)* 3 如果包含(x,y) 返回 1 4 创建食物节点* */private Cell createFood() {Random random = new Random();int x, y;do {x = random.nextInt(COLS);// COLS列数y = random.nextInt(ROWS);// WOWS行数} while (worm.contains(x, y));return new Cell(x, y, Color.green);// 食物颜色/** 初始化的舞台单元测试 */public static void test() {WormStage stage = new WormStage();System.out.println(stage.worm);System.out.println(stage.food);}/*** 重写JPanel绘制方法paint:绘制,绘画,涂抹Graphics 绘图,* 理解为:绑定到当前面板的画笔*/public void paint(Graphics g) {// 添加自定义绘制!// 绘制背景g.setColor(Color.darkGray);// 背景色g.fillRect(0, 0, getWidth(), getHeight());g.setColor(Color.cyan);// 边框上的颜色// draw 绘制 Rect矩形g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);// 绘制食物g.setColor(food.getColor());// fill 填充 3D 3维 Rect矩形突起的立体按钮形状g.fill3DRect(food.getX() * CELL_SIZE, food.getY() * CELL_SIZE,CELL_SIZE, CELL_SIZE, true);// 绘制蛇worm.paint(g);// 让蛇自己去利用画笔绘制private Timer timer;/*** 启动定时器驱动蛇的运行 1 检查碰撞是否将要发生* 2 如果发生碰撞:创建新的蛇和食物,重写开始* 3 如果没有碰撞就爬行,并检查是否能够吃到食物* 4如果吃到食物:重新创建新的食物* 5 启动重新绘制界面功能 repaint() 更新界面显示效果! repaint()* 方法会尽快调用paint(g) 更新界面!*/private void go() {if (timer == null)timer = new Timer();timer.schedule(new TimerTask() {public void run() {if (worm.hit()) {// 如果蛇碰到边界或自己worm = new Worm();// 创建新的蛇food = createFood();// 创建新食物} else {// 如果没有碰到自己boolean eat = worm.creep(food);// 蛇向前(当前方向)爬行,返回结果表示是否吃到食物if(eat) {// 如果吃到食物,就生成新食物food = createFood();}}repaint();}}, 0, 1000 / 5);this.requestFocus();this.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch (key) {case KeyEvent.VK_UP:creepForFood(Worm.UP);break;case KeyEvent.VK_DOWN:creepForFood(Worm.DOWN);break;case KeyEvent.VK_LEFT:creepForFood(Worm.LEFT);break;case KeyEvent.VK_RIGHT:creepForFood(Worm.RIGHT);break;}}});}private void creepForFood(int direction) { if (worm.hit(direction)) {worm = new Worm();food = createFood();} else {boolean eat = worm.creep(direction, food);if (eat) {food = createFood();}}}/** 软件启动的入口方法 */public static void main(String[] args) {// 启动软件....JFrame frame = new JFrame("贪吃蛇");// 一个画框对象frame.setSize(450, 480);// size 大小,setSize 设置大小// frame.setLocation(100,50);//Locationq位置frame.setLocationRelativeTo(null);// 居中// 设置默认的关闭操作为在关闭时候离开软件frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);// Visible可见的设置可见性frame.setLayout(null);// 关闭默认布局管理,避免面板充满窗口WormStage stage = new WormStage();// System.out.println("CELL_SIZE * COLS:"+CELL_SIZE * COLS);stage.setSize(CELL_SIZE* COLS, CELL_SIZE* ROWS);stage.setLocation(40, 50);stage.setBorder(new LineBorder(Color.BLACK));frame.add(stage);// 在窗口添加舞台stage.go();// 启动定时器驱动蛇自动运行}}。
贪吃蛇代码(C 实现)
for(i=T.tail;i!=T.head;) {
; }
if(kbhit()&&(order=getch(),order=='w'||order=='s'||order=='a'|| order=='d'))
{
sum=T.body[(T.head-1+ML)%ML]; system("CLS"); for(i=T.tail;i!=T.head;) {
jud=order; //printf("-->a\n"); if(map[sum/100][sum%100-1]!=-1) { for(i=T.tail;i!=T.head;) { temp=T.body[i]; map[temp/100][temp%100]=0; i++; i%=ML; }
aaa(); } else {
sum=T.body[i]; map[sum/100][sum%100]=-1; i++; i%=ML; } while(1) { sum=getnum(); if(map[sum/100][sum%100]==0) {
map[sum/100][sum%100]=1; break; } } for(i=T.tail;i!=T.head;) { sum=T.body[i]; map[sum/100][sum%100]=0; i++; i%=ML; } } else { T.body[T.head++]=sum; T.head%=ML; T.tail=(++T.tail)%ML; } } void sss() { int sum,i; sum=T.body[(T.head-1+ML)%ML]+100; if(map[sum/100][sum%100]==1) { T.length++; T.body[T.head++]=sum; T.head%=ML; map[sum/100][sum%100]=0; for(i=T.tail;i!=T.head;) { sum=T.body[i]; map[sum/100][sum%100]=-1; i++;
贪吃蛇代码
#include<stdio.h>#include<conio.h>#include<time.h>#include<windows.h>int length=1;//蛇的当前长度,初始值为1int line[100][2];//蛇的走的路线int head[2]={40,12};//蛇头int food[2];//食物的位置char direction;//蛇运动方向int x_min=1,x_max=77,y_min=2,y_max=23;//设置蛇的运动区域int tail_before[2]={40,12};//上一个状态的蛇尾char direction_before='s';//上一个状态蛇的运动方向int live_death=1;//死活状态,0死,1活int eat_flag=0;//吃食物与否的状态。
0没吃1吃了int max=0;int delay;//移动延迟时间void gotoxy(int x, int y)//x为列坐标,y为行坐标{COORD pos = {x,y};HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOut, pos);}void hidden()//隐藏光标{HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);CONSOLE_CURSOR_INFO cci;GetConsoleCursorInfo(hOut,&cci);cci.bVisible=0;//赋1为显示,赋0为隐藏SetConsoleCursorInfo(hOut,&cci);}void update_score()//更新分数{gotoxy(2,1);printf("我的分数:%d",length);gotoxy(42,1);printf("最高记录:%d",max);}void create_window(){gotoxy(0,0);printf("╔══════════════════╦═══════════════════╗");prin tf("║ ║ ║");printf("╠══════════════════╩═══════════════════╣");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("║║");printf("╚══════════════════════════════════════╝");}void update_line()//更新蛇的线路{int i;if(eat_flag==0)//吃了食物就不用记住上一个状态的蛇尾,否则会被消掉{tail_before[0]=line[0][0];//记住上一个状态的蛇尾tail_before[1]=line[0][1];for(i=0;i<length-1;i++)//更新蛇头以后部分{line[i][0]=line[i+1][0];line[i][1]=line[i+1][1];}line[length-1][0]=head[0];//更新蛇头line[length-1][1]=head[1];}}void initial()//初始化{FILE *fp;gotoxy(head[0],head[1]);printf("蛇");line[0][0]=head[0];//把蛇头装入路线line[0][1]=head[1];if((fp=fopen("highest","r"))==NULL){fp=fopen("highest","w");fprintf(fp,"%d",0);max=0;fclose(fp);}//第一次使用时,初始化奖最高分为0else{fp=fopen("highest","r");fscanf(fp,"%d",&max);}update_score();}void createfood()//产生食物{int flag,i;srand((unsigned)time(NULL));for(;;){for(;;){food[0]=rand()%(x_max+1);if(food[0]%2==0 && food[0]>x_min)break;}//产生一个偶数横坐标for(;;){food[1]=rand()%(y_max);if(food[1]>y_min)break;}for(i=0,flag=0;i<length;i++)//判断产生的食物是否在蛇身上,在flag=1,否则为0 if(food[0]==line[i][0] && food[1]==line[i][1]){ flag=1; break; }if(flag==0)// 食物不在蛇身上结束循环break;}gotoxy(food[0],food[1]);printf("蛇");}void show_snake(){gotoxy(head[0],head[1]);printf("蛇");if(eat_flag==0)//没吃食物时消去蛇尾{gotoxy(tail_before[0],tail_before[1]);printf(" ");//消除蛇尾}elseeat_flag=0;//吃了食物就回到没吃状态}char different_direction(char dir)//方向{switch(dir){case 'a': return 'd';case 'd': return 'a';case 'w': return 's';case 's': return 'w';}}void get_direction(){direction_before=direction;//记住蛇上一个状态的运动方向while(kbhit()!=0) //调试direction=getch();if( direction_before == different_direction(direction) || (direction!='a' && direction!='s' && direction!='d' && direction!='w') ) //新方向和原方向相反,或获得的方向不是wasd时,保持原方向direction=direction_before;switch(direction){case 'a': head[0]-=2; break;case 'd': head[0]+=2; break;case 'w': head[1]--; break;case 's': head[1]++; break;}}void live_state()//判断蛇的生存状态{FILE *fp;int i,flag;for(i=0,flag=0;i<length-1;i++)//判断是否自己咬到自己if( head[0]==line[i][0] && head[1]==line[i][1]){flag=1;break;}if(head[0]<=x_min || head[0]>=x_max || head[1]<=y_min || head[1]>=y_max || flag==1) {system("cls");//游戏结束create_window();update_score();gotoxy(35,12);printf("游戏结束!\n");Sleep(500);live_death=0;fp=fopen("highest","w");fprintf(fp,"%d",max);//保存最高分}}void eat(){if(head[0]==food[0]&&head[1]==food[1]){length++;line[length-1][0]=head[0];//更新蛇头line[length-1][1]=head[1];eat_flag=1;createfood();if(length>max)max=length;update_score();//if(delay>100)delay-=30;//加速}}main(){int x=0,y=0;int i;hidden();//隐藏光标create_window();initial();createfood();for(direction='s',delay=600;;){get_direction();//得到键盘控制方向eat();//吃食物update_line();//更新路线live_state();//判断生死状态if(live_death==1){show_snake();}elsebreak;Sleep(delay);//暂停}}。
贪吃蛇c语言代码
贪吃蛇c语言代码#include <graphics.h>#include <conio.h>#include <stdlib.h>#include <dos.h>#define NULL 0#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181struct snake{int centerx;int centery;int newx;int newy;struct snake *next;};struct snake *head;int grade=60; /*控制速度的*******/int a,b; /* 背静遮的位置*/void *far1,*far2,*far3,*far4; /* 蛇身指针背静遮的指针虫子*/int size1,size2,size3,size4; /* **全局变量**/int ch=RIGHT; /**************存按键开始蛇的方向为RIGHT***********/int chy=RIGHT;int flag=0; /*********判断是否退出游戏**************/int control=4; /***********判断上次方向和下次方向不冲突***/int nextshow=1; /*******控制下次蛇身是否显示***************/int scenterx; /***************随即矩形中心坐标***************/int scentery;int sx; /*******在a b 未改变前得到他们的值保证随机矩形也不在此出现*******/int sy;/************************蛇身初始化**************************/void snakede(){struct snake *p1,*p2;head=p1=p2=(struct snake *)malloc(sizeof(struct snake));p1->centerx=80;p1->newx=80;p1->centery=58;p1->newy=58;p1=(struct snake *)malloc(sizeof(struct snake));p2->next=p1;p1->centerx=58;p1->newx=58;p1->centery=58;p1->newy=58;p1->next=NULL;}/*******************end*******************/void welcome() /*************游戏开始界面,可以选择速度**********/ {int key;int size;int x=240;int y=300;int f;void *buf;setfillstyle(SOLID_FILL,BLUE);bar(98,100,112,125);setfillstyle(SOLID_FILL,RED);bar(98,112,112,114);setfillstyle(SOLID_FILL,GREEN);bar(100,100,110,125);size=imagesize(98,100,112,125);buf=malloc(size);getimage(98,100,112,125,buf);cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(240,300,390,325);outtextxy(193,310,"speed:");setfillstyle(SOLID_FILL,RED);bar(240,312,390,314);setcolor(YELLOW);outtextxy(240,330,"DOWN");outtextxy(390,330,"UP");outtextxy(240,360,"ENTER to start..." );outtextxy(270,200,"SNAKE");fei(220,220);feiyang(280,220);yang(340,220);putimage(x,y,buf,COPY_PUT);setcolor(RED);rectangle(170,190,410,410);while(1){ if(bioskey(1)) /********8选择速度部分************/ key=bioskey(0);switch(key){case ENTER:f=1;break;case DOWN:if(x>=240){ putimage(x-=2,y,buf,COPY_PUT);grade++;key=0;}case UP:if(x<=375){ putimage(x+=2,y,buf,COPY_PUT);grade--;key=0;break;}}if (f==1)break;} /********** end ****************/ free(buf);}/*************************随即矩形*****************//***********当nextshow 为1的时候才调用此函数**********/void ran(){ int nx;int ny;int show; /**********控制是否显示***********/int jump=0;struct snake *p;p=head;if(nextshow==1) /***********是否开始随机产生***************/{show=1;randomize();nx=random(14);ny=random(14);scenterx=nx*22+58;scentery=ny*22+58;while(p!=NULL){if(scenterx==p->centerx&&scentery==p->centery||scenterx==sx&&scentery==sy) {show=0;jump=1;break;}elsep=p->next;if(jump==1)break;}if(show==1){putimage(scenterx-11,scentery-11,far3,COPY_PUT);nextshow=0;break;}}}/***********过关动画**************/ void donghua(){ int i;cleardevice();setbkcolor(BLACK);randomize();while(1){for(i=0;i<=5;i++){putpixel(random(640),random(80),13); putpixel(random(640),random(80)+80,2); putpixel(random(640),random(80)+160,3); putpixel(random(640),random(80)+240,4); putpixel(random(640),random(80)+320,1); putpixel(random(640),random(80)+400,14); }setcolor(YELLOW);settextstyle(0,0,4);outtextxy(130,200,"Wonderful!!"); setfillstyle(SOLID_FILL,10);bar(240,398,375,420);feiyang(300,400);fei(250,400);yang(350,400);if(bioskey(1))if(bioskey(0)==ESC){flag=1;break;}}}/*************************end************************//***********************初始化图形系统*********************/ void init(){int a=DETECT,b;int i,j;initgraph(&a,&b,"");}/***************************end****************************/ /***画立体边框效果函数******/void tline(int x1,int y1,int x2,int y2,int white,int black){ setcolor(white);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(black);line(x2,y1,x2,y2);line(x1,y2,x2,y2);}/****end*********//*************飞洋标志**********/int feiyang(int x,int y){int feiyang[18][18]={ {0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0}, {0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0},{0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0},{0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,0},{0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0},{0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (feiyang[i][j]==1)putpixel(j+x,i+y,RED);}}/********"飞"字*************/int fei(int x,int y){int fei[18][18]={{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (fei[i][j]==1)putpixel(j+x,i+y,BLUE);}}/*********"洋"字**************/int yang(int x,int y){int yang[18][18]={{0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0},{0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0},{0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0},{0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0},{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (yang[i][j]==1)putpixel(j+x,i+y,BLUE);}}/******************主场景**********************/ int bort(){ int a;setfillstyle(SOLID_FILL,15);bar(49,49,71,71);setfillstyle(SOLID_FILL,BLUE);bar(50,50,70,70);size1=imagesize(49,49,71,71);far1=(void *)malloc(size1);getimage(49,49,71,71,far1);cleardevice();setfillstyle(SOLID_FILL,12);bar(49,49,71,71);size2=imagesize(49,49,71,71);far2=(void *)malloc(size2);getimage(49,49,71,71,far2);setfillstyle(SOLID_FILL,12);bar(49,49,71,71);setfillstyle(SOLID_FILL,GREEN);bar(50,50,70,70);size3=imagesize(49,49,71,71);far3=(void *)malloc(size3);getimage(49,49,71,71,far3);cleardevice(); /*取蛇身节点背景节点虫子节点end*/ setbkcolor(8);setfillstyle(SOLID_FILL,GREEN);bar(21,23,600,450);tline(21,23,600,450,15,8); /***开始游戏场景边框立体效果*******/ tline(23,25,598,448,15,8);tline(45,45,379,379,8,15);tline(43,43,381,381,8,15);tline(390,43,580,430,8,15);tline(392,45,578,428,8,15);tline(412,65,462,85,15,8);tline(410,63,464,87,15,8);tline(410,92,555,390,15,8);tline(412,94,553,388,15,8);tline(431,397,540,420,15,8);tline(429,395,542,422,15,8);tline(46,386,377,428,8,15);tline(44,384,379,430,8,15);setcolor(8);outtextxy(429,109,"press ENTER ");outtextxy(429,129,"---to start"); /*键盘控制说明*/outtextxy(429,169,"press ESC ");outtextxy(429,189,"---to quiet");outtextxy(469,249,"UP");outtextxy(429,289,"LEFT");outtextxy(465,329,"DOWN");outtextxy(509,289,"RIGHT");setcolor(15);outtextxy(425,105,"press ENTER ");outtextxy(425,125,"---to start");outtextxy(425,165,"press ESC ");outtextxy(425,185,"---to quiet");outtextxy(465,245,"UP");outtextxy(425,285,"LEFT");outtextxy(461,325,"DOWN");outtextxy(505,285,"RIGHT"); /*******end*************/ setcolor(8);outtextxy(411,52,"score");outtextxy(514,52,"left");setcolor(15);outtextxy(407,48,"score");outtextxy(510,48,"left");size4=imagesize(409,62,465,88); /****分数框放到内存********/ far4=(void *)malloc(size4);getimage(409,62,465,88,far4);putimage(500,62,far4,COPY_PUT); /*******输出生命框***********/setfillstyle(SOLID_FILL,12);setcolor(RED);outtextxy(415,70,"0"); /***************输入分数为零**********/outtextxy(512,70,"20"); /*************显示还要吃的虫子的数目*********/ bar(46,46,378,378);feiyang(475,400);fei(450,400);yang(500,400);outtextxy(58,390,"mailto:");outtextxy(58,410,"snake game");outtextxy(200,410,"made by yefeng");while(1){ if(bioskey(1))a=bioskey(0);if(a==ENTER)break;}}/******************gameover()******************/void gameover(){ char *p="GAME OVER";int cha;setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,p);while(1){if(bioskey(1))cha=bioskey(0);if(cha==ESC){flag=1;break;}}}/***********显示蛇身**********************/void snakepaint(){struct snake *p1;p1=head;putimage(a-11,b-11,far2,COPY_PUT);while(p1!=NULL){putimage(p1->newx-11,p1->newy-11,far1,COPY_PUT);p1=p1->next;}}/****************end**********************//*********************蛇身刷新变化游戏关键部分*******************/ void snakechange(){struct snake *p1,*p2,*p3,*p4,*p5;int i,j;static int n=0;static int score;static int left=20;char sscore[5];char sleft[1];p2=p1=head;while(p1!=NULL){ p1=p1->next;if(p1->next==NULL){a=p1->newx;b=p1->newy; /************记录最后节点的坐标************/ sx=a;sy=b;}p1->newx=p2->centerx;p1->newy=p2->centery;p2=p1;}p1=head;while(p1!=NULL){p1->centerx=p1->newx;p1->centery=p1->newy;p1=p1->next;}/********判断按键方向*******/if(bioskey(1)){ ch=bioskey(0);if(ch!=RIGHT&&ch!=LEFT&&ch!=UP&&ch!=DOWN&&ch!=ESC) /********chy为上一次的方向*********/ch=chy;}switch(ch){case LEFT: if(control!=4){head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}else{ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}chy=ch;break;case DOWN:if(control!=1){ head->newy=head->newy+22;head->centery=head->newy; control=3;if(head->newy>377)gameover();}else{ head->newy=head->newy-22; head->centery=head->newy;control=1;if(head->newy<47)gameover();}chy=ch;break;case RIGHT: if(control!=2){ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}else{ head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}chy=ch;break;case UP: if(control!=3){ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}else{ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();}chy=ch;break;case ESC:flag=1;break;}/* if 判断是否吃蛇*/if(flag!=1){ if(head->newx==scenterx&&head->newy==scentery){ p3=head;while(p3!=NULL){ p4=p3;p3=p3->next;}p3=(struct snake *)malloc(sizeof(struct snake));p4->next=p3;p3->centerx=a;p3->newx=a;p3->centery=b;p3->newy=b;p3->next=NULL;a=500;b=500;putimage(409,62,far4,COPY_PUT); /********** 分数框挡住**************/ putimage(500,62,far4,COPY_PUT); /*********把以前的剩下虫子的框挡住********/ score=(++n)*100;left--;itoa(score,sscore,10);itoa(left,sleft,10);setcolor(RED);outtextxy(415,70,sscore);outtextxy(512,70,sleft);nextshow=1;if(left==0) /************判断是否过关**********/donghua(); /*******如果过关,播放过关动画*********************/}p5=head; /*********************判断是否自杀***************************/ p5=p5->next;p5=p5->next;p5=p5->next;p5=p5->next; /****从第五个节点判断是否自杀************/while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->centery){ gameover();break;}elsep5=p5->next;}}}/************snakechange()函数结束*******************//*****************************主函数******************************************/ int main(){ int i;init(); /**********初始化图形系统**********/ welcome(); /*********8欢迎界面**************/ bort(); /*********主场景***************/ snakede(); /**********连表初始化**********/ while(1){ snakechange();if(flag==1)break;snakepaint();ran();for(i=0;i<=grade;i++)delay(3000);}free(far1);free(far2);free(far3);free(far4);closegraph();return 0;}。
贪吃蛇(C语言)
贪吃蛇(C语言)#include#include#include#include#include//蛇头移动方向#define UP 1#define DOWN 2#define LEFT 3#define RIGHT 4〃死亡判定(葱墙或葱自己)#define KISSASS 1#define KISSWALL 2//坐标转化#define POINT(x,y) ((y)*80+(x)+1)// 将(x,y)坐标转化为一个int 类数值#define GETX(x) (((x)-1)%80)// 将int 类数值提取出原先的x#define GETY(y) (((y)-1)/80)// 同理,提取出yHANDLE Console;void Position(int x, int y); // 移动光标到(x,y) //Windows.hvoid DrawMap();// 画墙void ShowText(char *text);//根据字符串的长短智能打印出包围字符串的笑脸void ResetSnake();// 初始化贪吃蛇int RefreshSnake();// 更新蛇的移动void CreatFood();// 生成食物void Draw();//画出蛇身和食物void RefreshScreen();// 屏幕刷新void GameOver(int Type);// 游戏结束条件int Gaming();//代码跑起来char play = 0; ////值为1则继续游戏,值为0游戏退出char pause = 0; //值为1则暂停,值为0游戏继续char direction; // 蛇头方向int snake[500]; //snake[0]为蛇头int body; //蛇身体长度int newbody;//吃完食物新长的蛇身int addHead,deleteTail;//增加蛇头擦去蛇尾,使贪吃蛇动起来int food = 0; // 食物void main()(CONSOLE_CURSOR_INFO CurrInfo = { sizeof(CONSOLE_CURSOR_INFO), 0 };Console = GetStdHandle(STD_OUTPUT_HANDLE);DrawMap();ShowT ext("Copyright reserve by 博元");while(Gaming()){if (play)DrawMap();};return 0;}void Position(int x, int y)// 移动光标到(x,y) //Windows.h{COORD coors = { x, y };SetConsoleCursorPosition(Console, coors);}void DrawMap() // 画墙{int i;for (i = 3; i < 70; i = i + 12){Position(i, 0);printf("===我是墙===");}for (i = 0; i < 25; i = i + 1){Position(0, i);printf("|| ");}for (i = 3; i < 70; i = i + 12){Position(i, 24);printf("============");}for (i = 0; i < 25; i = i + 1){Position(76, i); printf("|| ");void ShowText(char *text) //根据字符串的长短智能打印出包围字符串的笑脸(int i;int strLength = strlen(text); // 得到字符串长度Position(40 - (strLength / 2)-1, 11);printf("%c”, 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);Position(40 - (strLength / 2)-1, 12);printf("%c ", 1);printf(text);printf(" %c", 1);Position(40 - (strLength / 2)-1, 13);printf("%c", 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);}void ResetSnake() //初始化贪吃蛇(int x, y;for (x = 39, y = 0; y < 2; y++)(snake[y] = POINT(x, 7 - y);}body = 2; //设定蛇身初始长度为2newbody = 6;addHead = 0;deleteTail = 0;direction = LEFT;}int RefreshSnake() 〃更新蛇的移动〃返回值为1游戏结束( int x, y;memcpy(snake + 1, snake, sizeof(int)*body);if (!newbody){deleteTail = snake[body];snake[body] = 0;}else{body++;newbody--;}x = GETX(snake[0]);y = GETY(snake[0]);switch (direction) //控制蛇头移动方向{case UP:y -= 1; //蛇头向上移动一格(对应坐标y-1 ) snake[0] = POINT(x, y);break;case DOWN:y += 1;snake[0] = POINT(x, y); break;case LEFT:x -= 1;snake[0] = POINT(x, y); break;case RIGHT:x += 1;snake[0] = POINT(x, y); break;}addHead = snake[0];if (x > 75 || x < 3 ||y > 23 || y < 1) // 检测是否撞墙(GameOver(KISSWALL);return 1;}int i;for (i = 1; i < body; i++)if (snake[0] == snake[i]) // 检测是否撞到自己身体(GameOver(KISSASS);return 1;}if (snake[0] == food)(while (1) //食物的位置不与蛇身重合(food = (rand() % (75 * 23));for (i = 0; snake[i]; i++)if (food == snake[i])// 检测是否吃到食物,吃到则reset食物food = 0;if (food) 〃如果food==0 则重新建立一个食物坐标break;}CreatFood(); // 吃了?再来一个!newbody = (rand() % 6) + 1; // 吃完食物蛇身增长一节}return 0;}void CreatFood() // 生成食物(if (GETX(food) > 75 || GETX(food) < 3 || GETY(food) > 23 || GETY(food) < 1) CreatFood;elsePosition(GETX(food), GETY(food));printf("%c”,4);}void Draw() //画出蛇身和食物(system("cls");int i;for (i = 0; snake[i]; i++)(Position(GETX(snake[i]), GETY(snake[i])); printf("%c”,1);}CreatFood();}void RefreshScreen() // 屏幕刷新(if (deleteTail)(Position(GETX(deleteTail), GETY(deleteTail)); printf("");}if (addHead)(Position(GETX(addHead), GETY(addHead)); printf("%c",1);}addHead = deleteTail = 0;}void GameOver(int Type) // 游戏结束条件(switch (Type)(case KISSASS://? 至ij 自己身体ShowT ext("NOOB !当你以光速绕着一棵树奔跑就会发现自己在葱自己!");break;case KISSWALL://撞墙ShowT ext("NOOB !你有考虑过墙的感受吗");}food = 0;play = 0;memset(snake, 0, sizeof(int) * 500); // 存初始化} int Gaming() // 执行int Keyboardinput;Sleep(60);// 速度if (kbhit())(Keyboardinput = getch();if (Keyboardi nput == 0 || Keyboardinput == 0xE0) (Keyboardinput = getch();switch (Keyboardi nput) // 方向控制(case 72:if (direction != DOWN) direction = UP;break;case 80:if (direction != UP)direction = DOWN;break;case 75:if (direction != RiGHT)direction = LEFT;break;case 77:if (direction != LEFT)direction = RiGHT;break;}}if (Keyboardi nput == '\r') // 暂停(if (!play)(play = 1;if (pause)(Draw();pause = 0;}}else(ShowT ext("不许暂停,继续葱!!");play = 0;pause =1;}}else if (KeyboardI nput == 0x1B) // 退出return 0; } if (play)(if (!food)(srand(clock());food = (rand() % (75 * 23)); ResetSnake();Draw();}else(if (!RefreshSnake())(RefreshScreen();}}}。
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;}。
贪吃蛇源代码
#include<stdio.h>#include <stdlib.h>#include <windows.h>#include<time.h>#include <conio.h>struct snake{int x, y;snake *next;};snake *head;static int direction=1;//1,2,3,4分别代表左上右下int food_x, food_y;int foodflag = false;int count = 0;int manu();void init();int gamerun();//游戏开始void move();//移动void printframe();//画界面void paint();//打印蛇身int check();//检测int food();//产生实物int setposition(int x, int y);//设置光标位置int check(){if (head->x == 2 || head->x == 63 || head->y == 1 || head->y == 25) return 0;elsereturn 1;}int food(){srand(unsigned int(time(0)));if (!foodflag){food_x = rand() % 60 + 3;food_y = rand() % 23 + 2;foodflag = true;}setposition(food_x, food_y);printf("*");return 0;}int setposition(int x,int y){HANDLE hOut;hOut = GetStdHandle(STD_OUTPUT_HANDLE);COORD pos = { x-1, y-1 }; /* 光标的起始位(第1列,第3行)0是第1列2是第3行*/SetConsoleCursorPosition(hOut, pos);return 0;}void printframe(){HANDLE consolehwnd;//创建句柄consolehwnd =GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄SetConsoleTextAttribute(consolehwnd, BACKGROUND_GREEN );//设置字体颜色for (int i = 1; i <40;i++){printf(" ");}setposition(1, 25);for (int i = 1; i < 41; i++){printf(" ");}for (int i = 1; i < 25; i++){setposition(1, i);printf(" ");}for (int i = 1; i < 25; i++){setposition(79, i);printf(" ");}for (int i = 1; i < 25;i++){setposition(63, i);printf(" ");}setposition(67, 5);SetConsoleTextAttribute(consolehwnd, 0x07);//设置字体颜色printf("你的分数:%d\n",count);setposition(66, 8);printf("暂停请按回车");}void init(){snake *temp1, *temp2;head = new snake;temp1 = new snake;temp2 = new snake;head->x = 26;head->y = 12;head->next = temp1;temp1->x = 27;temp1->y = 12;temp1->next = temp2;temp2->x = 28;temp2->y = 12;temp2->next = NULL;}void paint(){snake *p;p = head;while (p){setposition(p->x, p->y);printf("*");p = p->next;}}void move(){snake * newHead;newHead = new snake;newHead->next = head;if (direction==1){newHead->x = head->x - 1;newHead->y = head->y;}if (direction == 2){newHead->x = head->x ;newHead->y = head->y-1;}if (direction == 3){newHead->x = head->x +1;newHead->y = head->y;}if (direction == 4){newHead->x = head->x;newHead->y = head->y+1;}head = newHead;}int gamerun(){char c;setposition(30, 13);printf("按任意键开始");_getch();system("cls");printframe();init();while (1){food();paint();if (_kbhit()){c = _getch();if (c ==-32){c = _getch();if (c ==75 && direction != 3){direction = 1;}if (c == 72 && direction != 4){direction = 2;}if (c == 77 && direction != 1){direction = 3;}if (c == 80 && direction != 2){direction = 4;}}if (c==' '){c = _getch();}if ((c == 'a' || c == 'A')&&direction !=3){direction = 1;}if ((c == 'w' || c == 'W')&&direction != 4){direction = 2;}if ((c == 'd' || c == 'D')&&direction != 1){direction = 3;}if ((c == 's' || c == 'S')&&direction != 2){direction = 4;}}move();paint();if (head->x!=food_x||head->y!=food_y) {snake *t;t = head;while (t->next->next){t = t->next;}setposition(t->next->x, t->next->y);printf(" ");delete t->next;t->next = NULL;}else{foodflag = false;count++;HANDLE consolehwnd;//创建句柄consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄setposition(67, 5);SetConsoleTextAttribute(consolehwnd, 0x07);//设置字体颜色printf("你的分数:%d\n", count);}if (!check()){system("cls");setposition(20, 10);printf("你的最终分数为:%d", count);break;}Sleep(200);}return 1;}int main(){gamerun();_getch();return 0;}。
经典游戏贪吃蛇代码(c++编写)
经典游戏贪吃蛇代码(c++编写)/* 头文件 */#include#includeusing namespace std;#ifndef SNAKE_H#define SNAKE_Hclass Cmp{friend class Csnake;int rSign; //横坐标int lSign; //竖坐标public://friend bool isDead(const Cmp& cmp); Cmp(int r,int l){setPoint(r,l);}Cmp(){}void setPoint(int r,int l){rSign=r;lSign=l;}Cmp operator-(const Cmp &m)const{return Cmp(rSign - m.rSign,lSign - m.lSign);}Cmp operator+(const Cmp &m)const{return Cmp(rSign + m.rSign,lSign + m.lSign);}};const int maxSize = 5; //初始蛇身长度class Csnake{Cmp firstSign; //蛇头坐标Cmp secondSign;//蛇颈坐标Cmp lastSign; //蛇尾坐标Cmp nextSign; //预备蛇头int row; //列数int line; //行数int count; //蛇身长度vector<vector > snakeMap;//整个游戏界面queue snakeBody; //蛇身public:int GetDirections()const;char getSymbol(const Cmp& c)const //获取指定坐标点上的字符{return snakeMap[c.lSign][c.rSign];}Csnake(int n) //初始化游戏界面大小{if(n<20)line=20+2;else if(n>30)line = 30 + 2;else line=n+2;row=line*3+2;}bool isDead(const Cmp& cmp){return ( getSymbol(cmp)=='c' || cmp.rSign == row-1 || cmp.rSign== 0 || cmp.lSign == line-1 || cmp.lSign == 0 );}void InitInstance(); //初始化游戏界面bool UpdataGame(); //更新游戏界面void ShowGame(); //显示游戏界面};#endif // SNAKE_H====================================== ==============================/* 类的实现及应用*/#include#include#include#include "snake.h"using namespace std;//测试成功void Csnake::InitInstance(){snakeMap.resize(line); // snakeMap[竖坐标][横坐标]for(int i=0;i{snakeMap[i].resize(row);for(int j=0;j{snakeMap[i][j]=' ';}}for(int m=1;m{//初始蛇身snakeMap[line/2][m]='c';//将蛇身坐标压入队列snakeBody.push(Cmp(m,(line/2)));//snakeBody[横坐标][竖坐标]}//链表头尾firstSign=snakeBody.back();secondSign.setPoint(maxSize-1,line/2);}//测试成功int Csnake::GetDirections()const{if(GetKeyState(VK_UP)<0) return 1; //1表示按下上键if(GetKeyState(VK_DOWN)<0) return 2; //2表示按下下键if(GetKeyState(VK_LEFT)<0) return 3; //3表示按下左键if(GetKeyState(VK_RIGHT)<0)return 4; //4表示按下右键return 0;}bool Csnake::UpdataGame(){//-----------------------------------------------//初始化得分0static int score=0;//获取用户按键信息int choice;choice=GetDirections();cout<<"Total score: "<<score</</score<</vector/随机产生食物所在坐标int r,l;//开始初始已经吃食,产生一个食物static bool eatFood=true;//如果吃了一个,才再出现第2个食物if(eatFood){do{//坐标范围限制在(1,1)到(line-2,row-2)对点矩型之间srand(time(0));r=(rand()%(row-2))+1; //横坐标l=(rand()%(line-2))+1;//竖坐标//如果随机产生的坐标不是蛇身,则可行//否则重新产生坐标if(snakeMap[l][r]!='c'){snakeMap[l][r]='*';}}while (snakeMap[l][r]=='c');}switch (choice){case 1://向上//如果蛇头和社颈的横坐标不相同,执行下面操作if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign-1);//否则,如下在原本方向上继续移动else nextSign=firstSign+(firstSign-secondSign); break;case 2://向下if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign+1);else nextSign=firstSign+(firstSign-secondSign); break;case 3://向左if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign-1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;case 4://向右if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign+1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;default:nextSign=firstSign+(firstSign-secondSign);}//----------------------------------------------------------if(getSymbol(nextSign)!='*' && !isDead(nextSign)) //如果没有碰到食物(且没有死亡的情况下),删除蛇尾,压入新的蛇头{//删除蛇尾lastSign=snakeBody.front();snakeMap[lastSign.lSign][lastSign.rSign]=' ';snakeBody.pop();//更新蛇头secondSign=firstSign;//压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();snakeMap[firstSign.lSign][firstSign.rSign]='c';//没有吃食eatFood=false;return true;}//-----吃食-----else if(getSymbol(nextSign)=='*' && !isDead(nextSign)){secondSign=firstSign;snakeMap[nextSign.lSign][nextSign.rSign]='c';//只压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();eatFood=true;//加分score+=20;return true;}//-----死亡-----else {cout<<"Dead"<<endl;cout<<"your "<<score<}void Csnake::ShowGame(){for(int i=0;i{for(int j=0;jcout<cout<}Sleep(1);system("cls");}======================================================================/*主函数部分 */#include#include "snake.h"#includeusing namespace std;int main(){Csnake s(20);s.InitInstance();//s.ShowGame();int noDead;do{s.ShowGame();noDead=s.UpdataGame();}while (noDead</endl;cout<<"your>);system("pause");return 0;}。
贪吃蛇游戏代码
贪吃蛇游戏代码贪吃蛇是一个经典的小游戏,可以在很多平台和设备上找到。
如果你想自己开发一个贪吃蛇游戏,这里有一个简单的Python版本,使用pygame库。
首先,确保你已经安装了pygame库。
如果没有,可以通过pip来安装:bash复制代码pip install pygame然后,你可以使用以下代码来创建一个简单的贪吃蛇游戏:python复制代码import pygameimport random# 初始化pygamepygame.init()# 颜色定义WHITE = (255, 255, 255)RED = (213, 50, 80)GREEN = (0, 255, 0)BLACK = (0, 0, 0)# 游戏屏幕大小WIDTH, HEIGHT = 640, 480screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("贪吃蛇")# 时钟对象来控制帧速度clock = pygame.time.Clock()# 蛇的初始位置和大小snake = [(5, 5), (6, 5), (7, 5)]snake_dir = (1, 0)# 食物的初始位置food = (10, 10)food_spawn = True# 游戏主循环running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_UP:snake_dir = (0, -1)elif event.key == pygame.K_DOWN:snake_dir = (0, 1)elif event.key == pygame.K_LEFT:snake_dir = (-1, 0)elif event.key == pygame.K_RIGHT:snake_dir = (1, 0)# 检查蛇是否吃到了食物if snake[0] == food:food_spawn = Falseelse:del snake[-1]if food_spawn is False:food = (random.randint(1, (WIDTH // 20)) * 20, random.randint(1, (HEIGHT // 20)) * 20)food_spawn = Truenew_head = ((snake[0][0] + snake_dir[0]) % (WIDTH // 20), (snake[0][1] + snake_dir[1]) % (HEIGHT // 20))snake.insert(0, new_head)# 检查游戏结束条件if snake[0] in snake[1:]:running = False# 清屏screen.fill(BLACK)# 绘制蛇for segment in snake:pygame.draw.rect(screen, GREEN, (segment[0], segment[1], 20, 20))# 绘制食物pygame.draw.rect(screen, RED, (food[0], food[1], 20, 20))# 更新屏幕显示pygame.display.flip()# 控制帧速度clock.tick(10)pygame.quit()这个代码实现了一个基本的贪吃蛇游戏。
贪吃蛇游戏代码
贪吃蛇游戏可以使用Python的pygame库来实现。
以下是一份完整的贪吃蛇游戏代码:```pythonimport pygameimport sysimport random#初始化pygamepygame.init()#设置屏幕尺寸和标题screen_size=(800,600)screen=pygame.display.set_mode(screen_size)pygame.display.set_caption('贪吃蛇')#设置颜色white=(255,255,255)black=(0,0,0)#设置蛇和食物的大小snake_size=20food_size=20#设置速度clock=pygame.time.Clock()speed=10snake_pos=[[100,100],[120,100],[140,100]]snake_speed=[snake_size,0]food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size]food_spawn=True#游戏主循环while True:for event in pygame.event.get():if event.type==pygame.QUIT:pygame.quit()sys.exit()keys=pygame.key.get_pressed()for key in keys:if keys[pygame.K_UP]and snake_speed[1]!=snake_size:snake_speed=[0,-snake_size]if keys[pygame.K_DOWN]and snake_speed[1]!=-snake_size:snake_speed=[0,snake_size]if keys[pygame.K_LEFT]and snake_speed[0]!=snake_size:snake_speed=[-snake_size,0]if keys[pygame.K_RIGHT]and snake_speed[0]!=-snake_size:snake_speed=[snake_size,0]snake_pos[0][0]+=snake_speed[0]snake_pos[0][1]+=snake_speed[1]#碰撞检测if snake_pos[0][0]<0or snake_pos[0][0]>=screen_size[0]or\snake_pos[0][1]<0or snake_pos[0][1]>=screen_size[1]or\snake_pos[0]in snake_pos[1:]:pygame.quit()sys.exit()#蛇吃食物if snake_pos[0]==food_pos:food_spawn=Falseelse:snake_pos.pop()if not food_spawn:food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size] food_spawn=True#绘制screen.fill(black)for pos in snake_pos:pygame.draw.rect(screen,white,pygame.Rect(pos[0],pos[1],snake_size,snake_size)) pygame.draw.rect(screen,white,pygame.Rect(food_pos[0],food_pos[1],food_size, food_size))pygame.display.flip()clock.tick(speed)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。
《贪吃蛇》游戏程序代码
《贪吃蛇》游戏程序代码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("游戏结束!")。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
choice=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,xb03,yb03,xb04,yb04,xb05,yb05);
}
choice=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,xb03,yb03,xb04,yb04,xb05,yb05);
//用于储存用户输入的密码
char IptPsd[PsdMaxLength]={'','','','','','','','\0'};
int isagin=0; //用于判断是否再玩一次,为1表示再玩一次
系统主函数
void main()
{
char str_again[]="再来一次"
//控件(按钮或输入框)的位置坐标
char UserName[5]={'m','a','r','r','y'}; //系统设定的用户名
char Password[6]={'t','o','m','1','2','3'}; //系统设定的密码
//用于储存用户输入的账号
char IptName[NameMaxLength]={'','','','','','','','\0'};
#define width_gameBoard 398 //游戏区域的宽度
#define high_gameBoard 398 //游戏区域的高度
#define sw 10 //用一个圆表示蛇的一节,sw表示圆的半径
#define num_food 16 //设定的食物个数,全部吃完则游戏胜利结束
if(choice==1)
{
InputName();//输入账号
}
if(choice==2)
{
InputPsd();//输入密码
}
if(choice==3)
{
ret=ChkNamePsd(IptName,IptPsd);//点击登录
choice=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb0ce==1)//点击了“操作指南”
{
BtnMoveClicked(xb00,yb00,xb01,yb01,6,6,str_guide);
void GameOver(bool iskillde); //判断游戏是否结束
void ClearTailNode(); //擦除蛇尾结点
void Eat(int x,int y); //吃食物
void SnakeMove(int x,int y,int d); //蛇按照玩家的控制命令进行移动
//添加启动画面
cleardevice();//用当前背景色清空屏幕,并将当前点移至(0,0)
IMAGE img;
loadimage(&img, _T("SnakesLaunch1.bmp"));//加载图像
putimage(0,0,&img);//显示图像作为启动画面
}
while(1)
{
if(ret==0)//判断是否已经发生过输入用户名或密码错误
{
//设置字体颜色为框体填充颜色,目的是擦掉提示错误的信息
setcolor(boxbkclr);
//设置输入文本的背景颜色为框体填充颜色,目的是擦掉提示错误的信息
void pause(); //游戏暂停
void DrawMsgBox(); //绘制消息窗口
int ResponseMouse(int,int,int,int,int,int,int,int,int,int,int,int);
//响应鼠标
void DrawTwoBtn(); //绘制启动画面上的两个按钮
break;
}
}
closegraph();
}
1、播放背景音乐和添加启动画面
void bkMusic_launchImg()
{
//播放背景音乐
mciSendString("open./千年等一回.mp3 alias 千年等一回",0,0,0);
mciSendString("play 千年等一回 repeat",0,0,0);
SnakeMove(sx,sy,sd);//蛇按照玩家的指控命令进行移动
DrawMsgBox();//绘制消息窗口
isagain=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,xb03,yb03,0,0,0,0);//响应鼠标点击
#define NameMaxLength 12 //设定用户名的最大字符数为:NameMaxLength-2
#define PsdMaxLength 10 //设定密码的最大字符数
#define boxbkclr 0xfedcbd //绘制消息框和登录框的主题填充颜色
#define drawFieldbkclr 0xFFFFFF //窗口区域的背景填充颜色
//绘制动感按钮
Sleep(200);
//加载并显示操作指南图片
IMAGE img;
loadimage(&img,_T("SnakesLaunch2.bmp"));
putimage(0,0,&img);
choice=ResponseMouse(-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0);
setorigin(0,0);//设置绘图窗口区域的左上角为逻辑坐标原点
setbkcolor(0xFFFFFF);//设置背景颜色,0xFFFFFF为白色
bkMusic_launchImg();//播放背景音乐和添加启动画面
if(isagain!=1)//是否是重新开始一局
{
DrawTwoBtn();//绘制启动画面上的两个按钮
void BthMoveClicked(int,int,int,int,int,int,char*);
typedef struct snake
{
int x;
int y;
struct snake*next;
}SNAKE;
SNAKE*head=(snake*)malloc(sizeof(snake));
预处理
#include<graphics.h>
#include<conio.h>
#include<time.h>
#pragma comment(lib,"Winmm.lib")
#define width_window 500 //窗口的宽度
#define high_window 398 //窗口的高度
int n=0; //初始化放置食物的个数为0
int sx=0,sy=0,sd=0; //蛇头的位置坐标和移动方向
int xb00=0,xb01=0,xb02=0,xb03=0,xb04=0,xb05=0;
//控件(按钮或输入框)的位置坐标
int yb00=0,yb01=0,yb02=0,yb03=0,yb04=0,yb05=0;
setbkcolor(boxbkclr);
setbkmode(TRANSPARENT);//设置文字输出时的背景模式为透明色
settexstyle(18,0,_T("宋体"));
//用框体填充颜色输出错误信息,即擦除
outtextxy(xb00-50,yb00-20,"账号或密码输入错误,请重新输入!");
char str_exit[]="我不玩了"
while(1)
{
n=0;//每局开始需要初始化放置食物的个数为0
InitGameBoard();//创建绘图窗口,并初始化
InitSnake(sx,sy,sd);//用随机数的方式在某个位置产生蛇和蛇的移动方向
SetFood();//随机地在蛇以外的位置放置食物
#define MovDist 1 //按钮移动量为MovDist像素
void InitGameBoard(); //创建绘图窗口,并初始化
void InitSnake(int x0,int y0,int d0); //用随机数产生蛇的位置和方向
void SetFood(); //随机地在蛇以外的位置放置食物
int GetPlayerCommand(); //获取游戏玩家发出的控制指令
void dispScore(); //动态显示得分
void dispInfo(); //显示得分、操作指南和版本等信息
void bkMusic_launchImg(); //播放背景音乐和添加启动画面
void window_segmented(); //画线分割窗口
line(width_gameBoard+1,200,width_window,200);//划线分割窗口