贪吃蛇(第一次写,代码乱而多,勿喷,谢谢,)
JS100行代码实现贪吃蛇,快写给你的女朋友
JS100⾏代码实现贪吃蛇,快写给你的⼥朋友<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>贪吃蛇</title><style>*{margin: 0;padding: 0;}#root{width: 100%;font-size: 0;}.block{display: inline-block;}</style></head><body><div id="root"></div><script>const BLOCK_LENGTH = 30; //⽅格边长const BLOCK_COLOR = "white"; //⽅格颜⾊const FOOD_COLOR = "salmon"; //⾷物颜⾊const HEAD_COLOR = "orchid"; //头部颜⾊const BODY_COLOR = "plum"; //⾝体颜⾊let js = 0; //定时器IDlet w_size = Math.floor((window.screen.width || 450) / BLOCK_LENGTH), //横向⽅格数量h_size = Math.floor((document.documentElement.clientHeight || 450) / BLOCK_LENGTH); //纵向⽅格数量//⽣成地图 startif(true){let map = "";for(let i = 0, len = w_size * h_size; i < len; ++i){map += `<div class='block' style='width:${BLOCK_LENGTH}px;height:${BLOCK_LENGTH}px;background-color:${BLOCK_COLOR};'></div>`; }document.getElementById('root').innerHTML = map;}//⽣成地图 endlet snake_list = [0]; //蛇⾝let snake_length = 1; //蛇⾝长度let block_list = document.getElementsByClassName('block'); //⽅格列表function creat_food(){ //⽣成⾷物let sub = 0;if(snake_list.length / (w_size * h_size) < 0.75){sub = Math.floor(Math.random()*(w_size*h_size));while(block_list[sub].style.backgroundColor != BLOCK_COLOR){sub = Math.floor(Math.random()*(w_size*h_size));}}else{let block_arr = [];for(let i = 0, len = w_size * h_size; i < len; ++i){if(block_list[i].style.backgroundColor == BLOCK_COLOR){block_arr.push(i);}}sub = block_arr[Math.floor(Math.random()*(block_arr.length))];}block_list[sub].style.backgroundColor = FOOD_COLOR;}let dir = 4; //移动⽅向(上:1下:2左:3右:4)function move(){ //移动let handle = function(next){let max = next > snake_list[snake_length - 1] ? next : snake_list[snake_length - 1];if(block_list[next] == undefined ||block_list[next].style.backgroundColor == BODY_COLOR ||(Math.abs(next - snake_list[snake_length - 1]) == 1 &&max % w_size == 0)){clearInterval(js);alert("得分:" + snake_length);location.reload();}else if(block_list[next].style.backgroundColor == FOOD_COLOR){block_list[snake_list[snake_length - 1]].style.backgroundColor = BODY_COLOR;snake_list.push(next);++snake_length;block_list[next].style.backgroundColor = HEAD_COLOR;creat_food();}else{block_list[snake_list[snake_length - 1]].style.backgroundColor = BODY_COLOR;block_list[snake_list[0]].style.backgroundColor = BLOCK_COLOR;snake_list.shift();snake_list.push(next);block_list[snake_list[snake_length - 1]].style.backgroundColor = HEAD_COLOR;}};switch(dir){case 1:handle(snake_list[snake_length - 1] - w_size);break;case 2:handle(snake_list[snake_length - 1] + w_size);break;case 3:handle(snake_list[snake_length - 1] - 1);break;case 4:handle(snake_list[snake_length - 1] + 1);break;default:;}}document.onkeypress = function(e){let theEvent = e || window.event;let code = theEvent.keyCode || theEvent.which || theEvent.charCode;switch(code){case 38: case 119:(dir == 1 || dir == 2) ? void 0 : dir = 1;break;case 37: case 97:(dir == 3 || dir == 4) ? void 0 : dir = 3;break;case 40: case 115:(dir == 1 || dir == 2) ? void 0 : dir = 2;break;case 39: case 100:(dir == 3 || dir == 4) ? void 0 : dir = 4;break;default:;}};block_list[snake_list[0]].style.backgroundColor = HEAD_COLOR;creat_food();js = setInterval(move, 300);</script></body></html>代码易读不⽤解释,只提⼀个事,蛇移动的时候,没必要每个部位都动,只处理头尾就可以了,这个应该也是显⽽易见的。
贪吃蛇代码-c语言-vc6.0
#include <conio.h>
#define N 21
int apple[3];
char score[3];
char tail[3];
void gotoxy(int x, int y) //输出坐标
{
COORD pos;
pos.X = x;
pos.Y = y;
/*这是一个贪吃蛇代码,运行环境VC++6.0(亲测完美运行)*/
/*该程序在dos系统下运行,不需要graphics.h头文件*/
/*该程序由C语言小方贡献,谢谢您的支持*/
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
apple[0] = rand()%N + 1;
apple[1] = rand()%N + 1;
apple[2] = 1;
}
Sleep(200-score[3]*10);
setbuf(stdin, NULL);
if (kbhit())
{
gotoxy(0, N+2);
ch = getche();
}
snake = Move(snake, ch, &len);
}
int File_in() //取记录的分数
{
FILE *fp;
if((fp = fopen("C:\\tcs.txt","a+")) == NULL)
超简单贪吃蛇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;}。
贪吃蛇游戏源代码
//主函数# include <windows.h># include <time.h># include "resource.h"#include "snake.h"#include "table.h"#define GAME_STATE_W AIT 0//游戏等待状态#define GAME_STATE_RUN 1//游戏运行状态#define GAME_STATE_END 2//游戏结束状态//界面相关物件尺寸的定义#define WALL_WIDTH 80//外墙左部到游戏区的宽度#define WALL_HEIGHT 80//外墙顶部到游戏区的高度#define BMP_W ALL_WIDTH 16//墙位图的宽度#define BMP_W ALL_HEIGHT 16//墙位图的高度LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam);void DrawGame(void);void ShellDraw( HDC hdc );void GameAreaDraw(HDC hdc);void OnTimer(UINT uTIMER_ID);void StartGame( void );void EndGame( void );//创建一个桌子CTable table;int tableBlockWidth = 0; //桌子的格子的宽度int tableBlockHeight = 0; //桌子的格子的高度int iScores = 0; //游戏的得分UINT uGameState = GAME_STATE_W AIT; //当前游戏状态HDC windowDC = NULL; //windows屏幕设备HDC bufferDC = NULL; //缓冲设备环境HDC picDC = NULL; //snake图像内存设备HDC endDC = NULL; //游戏终结图像内存设备HDC scoreDC = NULL; //分数板内存设备HWND hAppWnd = NULL; //本application窗口句柄HBITMAP picBMP = NULL; //snake图像位图句柄HBITMAP bufferBMP = NULL; //缓冲位图句柄HBITMAP endBMP = NULL; //游戏终结hAppWnd图像内存句柄HBITMAP hbmpWall = NULL; //墙位图句柄HBITMAP hbmpScore = NULL; //分数板位图句柄HBRUSH hbrushWall = NULL; //墙画刷//定时器标识UINT uSnakeMoveTimer; //蛇的移动UINT uFoodAddTimer; //水果的产生//框架的位置数据定义//GDI RECT 而不是MFC CRectRECT g_ClientRect;int g_iClientWidth;int g_iClientHeight;int WINAPI WinMain(HINSTANCE hInstance, // handle to current instanceHINSTANCE hPrevInstance, // handle to previous instanceLPSTR lpCmdLine, // command lineint nCmdShow // show state){WNDCLASS wndClass;UINT width,height;//定义窗口wndClass.cbClsExtra = 0;wndClass.cbWndExtra = 0;wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);wndClass.hIcon = LoadIcon(NULL,MAKEINTRESOURCE(IDI_MAIN));wndClass.hCursor = LoadCursor(NULL,IDC_ARROW);wndClass.hInstance = hInstance;wndClass.lpfnWndProc = WndProc;wndClass.lpszClassName = "Snake";wndClass.lpszMenuName = NULL;wndClass.style = CS_HREDRAW | CS_VREDRAW;//注册窗口RegisterClass(&wndClass);width = GetSystemMetrics(SM_CXSCREEN);height = GetSystemMetrics(SM_CYSCREEN);HWND hWnd;hWnd = CreateWindow("Snake","贪吃蛇游戏",WS_POPUP,0,0,width,height,NULL,NULL,hInstance,NULL);hAppWnd = hWnd;//显示窗口ShowWindow(hWnd,SW_SHOWNORMAL);UpdateWindow(hWnd);GetClientRect(hWnd,&g_ClientRect);g_iClientWidth = g_ClientRect.right - g_ClientRect.left;g_iClientHeight = g_ClientRect.bottom - g_ClientRect.top;//将游戏区域分成横纵均匀的20小块tableBlockWidth = (g_ClientRect.right - 2 * WALL_WIDTH) / 20;tableBlockHeight = (g_ClientRect.bottom - 2 * WALL_HEIGHT) / 20;//获取当前主设备与windowDC相连windowDC = GetDC(NULL);//创建与windowDC兼容的内存设备环境bufferDC = CreateCompatibleDC(windowDC);picDC = CreateCompatibleDC(windowDC);endDC = CreateCompatibleDC(windowDC);scoreDC =CreateCompatibleDC(windowDC);//位图的初始化与载入位图bufferBMP = CreateCompatibleBitmap(windowDC,g_iClientWidth,g_iClientHeight);picBMP = (HBITMAP)LoadImage(NULL,"snake.bmp",IMAGE_BITMAP,160,80,LR_LOADFROMFILE);hbmpWall = (HBITMAP)LoadImage(NULL,"brick.bmp",IMAGE_BITMAP,16,16,LR_LOADFROMFILE);endBMP = (HBITMAP)LoadImage(NULL,"end.bmp",IMAGE_BITMAP,369,300,LR_LOADFROMFILE);hbmpScore = (HBITMAP)LoadImage(NULL,"scoreboard.bmp",IMAGE_BITMAP,265,55,LR_LOADFROMFILE);//生声明位图与设备环境的关联SelectObject(bufferDC,bufferBMP);SelectObject(picDC,picBMP);SelectObject(endDC,endBMP);SelectObject(scoreDC,hbmpScore);hbrushWall = CreatePatternBrush(hbmpWall);StartGame();MSG Msg;while (GetMessage(&Msg,NULL,0,0)){TranslateMessage(&Msg);DispatchMessage(&Msg);}return Msg.wParam;}LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam){switch (message){case WM_TIMER:OnTimer((UINT)wParam);break;case WM_KEYDOWN:switch (wParam){case VK_ESCAPE:KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_W AIT;if (IDYES == MessageBox(hWnd,"真的要退出吗?","贪吃蛇",MB_YESNO | MB_ICONQUESTION)){exit(0);}uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;break;case VK_UP:table.ChangeSnakeDirect(S_UP);break;case VK_DOWN:table.ChangeSnakeDirect(S_DOWN);break;case VK_LEFT:table.ChangeSnakeDirect(S_LEFT);break;case VK_RIGHT:table.ChangeSnakeDirect(S_RIGHT);break;case VK_SPACE:if (GAME_STATE_END == uGameState){StartGame();}else if (GAME_STATE_RUN == uGameState){KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_W AIT;}else{uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;}break;}break;case WM_SETCURSOR:SetCursor(NULL);break;case WM_DESTROY:ReleaseDC(hWnd,picDC);ReleaseDC(hWnd,bufferDC);ReleaseDC(hWnd,windowDC);PostQuitMessage(0);break;}return DefWindowProc(hWnd,message,wParam,lParam);}void DrawGame(){ShellDraw(bufferDC);GameAreaDraw(bufferDC);BitBlt(windowDC,0,0,g_iClientWidth,g_iClientHeight,bufferDC,0,0,SRCCOPY);}void OnTimer(UINT uTIMER_ID){if (uTIMER_ID == uSnakeMoveTimer){//移动蛇table.SnakeMove();//检测蛇是否碰到自己的身体if (table.GetSnake() ->IsHeadTouchBody(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y)){EndGame();}//根据蛇头所在区域做相应的处理switch (table.GetData(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y)){case TB_STATE_FOOD:table.ClearFood(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y);table.AddBlock((rand())%tableBlockWidth,rand()%tableBlockHeight);table.GetSnake() ->AddBody();iScores++;break;case TB_STATE_BLOCK:case TB_STATE_SBLOCK:EndGame();break;}//xianshiDrawGame();}else if (uTIMER_ID == uFoodAddTimer){//定时加食物table.AddFood((rand())%tableBlockWidth,rand()%tableBlockHeight);}}//开始游戏void StartGame(){iScores = 0;int iFoodNumber;//桌面初始化table.InitialTable(tableBlockWidth,tableBlockHeight);table.GetSnake() ->ChangeDirect(S_RIGHT);table.GetSnake() ->SetHeadPos(tableBlockWidth / 2,tableBlockHeight / 2);//预先随机产生一些食物srand( (unsigned)time(NULL));for (iFoodNumber = 0; iFoodNumber < 400; iFoodNumber++){table.AddFood((rand())%tableBlockWidth,(rand())%tableBlockHeight);}//打开定时器DrawGame();uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;}void EndGame(){//关计时器KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_END;}void ShellDraw(HDC hdc){char szText[30] = "Score: ";char szNum[20];int iNowScores = iScores * 100;itoa(iNowScores,szNum,10);strcat(szText,szNum);RECT rt,rect;GetClientRect(hAppWnd,&rt);//墙的绘制SelectObject(hdc,hbrushWall);PatBlt(hdc,rt.left,rt.top,rt.right,rt.bottom,PATCOPY);//内部游戏区为白色底平面rect.left = rt.left + WALL_WIDTH;rect.top = rt.top + WALL_HEIGHT;rect.right = rt.right - WALL_WIDTH;rect.bottom = rt.bottom - WALL_HEIGHT;FillRect(hdc,&rect,(HBRUSH)(COLOR_WINDOW + 1));BitBlt(hdc,GetSystemMetrics(SM_CXSCREEN) / 3 ,10,256,55,scoreDC,0,0,SRCCOPY);SetBkMode(hdc,TRANSPARENT);TextOut(hdc,GetSystemMetrics(SM_CXSCREEN) / 3 + 50,30,szText,strlen(szText));}void GameAreaDraw(HDC hdc){int i,j;int x, y, x_pos, y_pos;BitmapState state;//绘制水果与毒果for (i = 0; i < tableBlockHeight; i++){for (j = 0; j < tableBlockWidth; j++){x_pos = j * 20 + WALL_WIDTH;y_pos = i * 20 + WALL_HEIGHT;switch (table.GetData(j,i)){case TB_STATE_FOOD:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,0,SRCAND);break;case TB_STATE_BLOCK:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,0,SRCAND);break;}}}//根据当前的形状绘制蛇头x = table.GetSnake()->GetPos()[0].x;y = table.GetSnake()->GetPos()[0].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[0];switch (state){case M_UP_UP:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,20,SRCAND);break;case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,20,SRCAND);break;case M_LEFT_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,20,SRCAND);break;case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,20,SRCAND);break;}//根据蛇身各节点的状态绘制蛇身for (i = 1; i < table.GetSnake()->GetLength() - 1; i++){x = table.GetSnake()->GetPos()[i].x;y = table.GetSnake()->GetPos()[i].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[i];switch (state){case M_UP_UP:case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,40,SRCAND);break;case M_LEFT_LEFT:case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,40,SRCAND);break;case M_RIGHT_DOWN:case M_UP_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,60,SRCAND);break;case M_RIGHT_UP:case M_DOWN_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,40,SRCAND);break;case M_LEFT_DOWN:case M_UP_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,60,SRCAND);break;case M_LEFT_UP:case M_DOWN_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,40,SRCAND);break;}}//绘制蛇尾巴x = table.GetSnake()->GetPos()[table.GetSnake()->GetLength()-1].x;y = table.GetSnake()->GetPos()[table.GetSnake()->GetLength()-1].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[table.GetSnake()->GetLength()-1];switch (state){case M_UP_UP:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,60,SRCAND);break;case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,0,SRCAND);break;case M_LEFT_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,60,SRCAND);break;case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,0,SRCAND);break;}//绘制游戏结束图案if (uGameState == GAME_STA TE_END){x_pos = g_iClientWidth / 3;y_pos = g_iClientHeight / 4;BitBlt(hdc,x_pos,y_pos,369,300,endDC,0,0,SRCCOPY);}}# include "snake.h"CSnake::CSnake(int x_pos,int y_pos,int len){if (len < 1){len = 1;}int i;m_length = len;//蛇的身体体长//初始化蛇的坐标位置m_pPos = new SPoint[m_length+2];m_pPos[0].x = x_pos;m_pPos[0].y = y_pos;for (i = 1; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length];m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}}CSnake::~CSnake(){SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);}//根据新旧两蛇的运动状态,确定当前显示的运动状态BitmapState CSnake::GetRightState(MoveState oldDirect,MoveState newDirect) {BitmapState re;switch(oldDirect){case S_NONE:switch(newDirect){case S_NONE:re = M_NONE;break;case S_UP:re = M_UP_UP;break;case S_DOWN:re = M_DOWN_DOWN;break;case S_LEFT:re = M_LEFT_LEFT;break;case S_RIGHT:re = M_RIGHT_RIGHT;break;}break;case S_UP:switch(newDirect){case S_UP:re = M_UP_UP;break;case S_LEFT:re = M_UP_LEFT;break;case S_RIGHT:re = M_UP_RIGHT;break;}break;case S_DOWN:switch(newDirect){case S_DOWN:re = M_DOWN_DOWN;break;case S_LEFT:re = M_DOWN_LEFT;break;case S_RIGHT:re = M_DOWN_RIGHT;break;}break;case S_LEFT:switch(newDirect){case S_UP:re = M_LEFT_UP;break;case S_LEFT:re = M_LEFT_LEFT;break;case S_DOWN:re = M_LEFT_DOWN;break;}break;case S_RIGHT:switch(newDirect){case S_UP:re = M_RIGHT_UP;break;case S_DOWN:re = M_RIGHT_DOWN;break;case S_RIGHT:re = M_RIGHT_RIGHT;break;}break;}return re;}//改变方向void CSnake::ChangeDirect(MoveState d) {//方向不能为其对立方switch(d){case S_NONE:m_newSnake.head = S_NONE;break;case S_UP:if(m_newSnake.head != S_DOWN)m_newSnake.head = S_UP;break;case S_DOWN:if(m_newSnake.head != S_UP)m_newSnake.head = S_DOWN;break;case S_LEFT:if(m_newSnake.head != S_RIGHT)m_newSnake.head = S_LEFT;break;case S_RIGHT:if(m_newSnake.head != S_LEFT)m_newSnake.head = S_RIGHT;break;}}//蛇移动void CSnake::Move(){int i;//1.计算各节点的新状态//保存蛇身体各部位的形状for (i = 0; i < m_length; i++){m_oldSnake.body[i] = m_newSnake.body[i];}m_newSnake.tail = m_newSnake.body[m_length-1];for(i = m_length - 1; i > 0; i--){m_newSnake.body[i] = m_newSnake.body[i-1];}m_newSnake.body[0] = m_newSnake.head;//根据新旧状态获取新的状态m_pStateArray[0] = GetRightState(m_oldSnake.head,m_newSnake.head);for(i = 0; i < m_length; i++){m_pStateArray[i+1] = GetRightState(m_oldSnake.body[i],m_newSnake.body[i]);}m_pStateArray[m_length+1] = GetRightState(m_oldSnake.tail,m_newSnake.tail);//2、整个蛇坐标移动,除蛇头外其他为原状态的前一位置for(i = m_length + 1; i > 0; i--){m_pPos[i] = m_pPos[i-1];}//蛇头根据新位置进行偏移switch(m_newSnake.head){case S_UP:m_pPos[0].y -= SNAKE_MOVE;break;case S_DOWN:m_pPos[0].y += SNAKE_MOVE;break;case S_LEFT:m_pPos[0].x -= SNAKE_MOVE;break;case S_RIGHT:m_pPos[0].x += SNAKE_MOVE;break;}}//蛇身体的增长void CSnake::AddBody(int n){//分配变量作为保存各种数据状态int i;Snake_Struct saveOldSnake,saveNewSnake;BitmapState *saveStateArray;SPoint *savePos;//保存蛇的位置信息savePos = new SPoint[m_length+2];for(i = 0; i < m_length + 2; i++){savePos[i] = m_pPos[i];}//保存蛇的状态信息saveOldSnake.head = m_oldSnake.head;saveOldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){saveOldSnake.body[i] = m_oldSnake.body[i];}saveOldSnake.tail = m_oldSnake.tail;saveNewSnake.head = m_newSnake.head;saveNewSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){saveNewSnake.body[i] = m_newSnake.body[i];}saveNewSnake.tail = m_newSnake.tail;saveStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){saveStateArray[i] = m_pStateArray[i];}//将长度增长m_length += n;//释放所有存储蛇状态数据的存储空间SAFE_DELETE_ARRAY(m_newSnake.body); SAFE_DELETE_ARRAY(m_oldSnake.body); SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);//创建并初始化蛇增长后的存储空间m_pPos = new SPoint[m_length+2];for (i = 0; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length]; m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2]; for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}//恢复原来的长度数据m_newSnake.head = saveNewSnake.head;m_oldSnake.head = saveOldSnake.head;for(i = 0; i < m_length - n; i++){m_newSnake.body[i] = saveNewSnake.body[i];m_oldSnake.body[i] = saveOldSnake.body[i];}m_newSnake.tail = saveNewSnake.tail;m_oldSnake.tail = saveOldSnake.tail;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2 - n; i++)m_pStateArray[i] = saveStateArray[i];m_pPos = new SPoint[m_length+2];for(i = 0; i < m_length + 2 - n; i++)m_pPos[i] = savePos[i];}//设置蛇头坐标void CSnake::SetHeadPos(int x, int y){m_pPos[0].x = x;m_pPos[0].y = y;}//取蛇状态的标志数组BitmapState* CSnake::GetStateArray(){return m_pStateArray;}//取蛇的位置信息SPoint* CSnake::GetPos(){return m_pPos;}//取蛇长度int CSnake::GetLength()return m_length + 2;}//检测蛇头是否碰到身体bool CSnake::IsHeadTouchBody(int x, int y){int i;for(i = 1; i < m_length + 2; i++){if (m_pPos[i].x == x && m_pPos[i].y == y)return true;}return false;}//初始化,用作游戏结束后重新开始void CSnake::Initial(){//释放以前的存储空间SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);SAFE_DELETE_ARRAY(m_newSnake.body);SAFE_DELETE_ARRAY(m_oldSnake.body);int i;int x_pos = 0;int y_pos = 0;m_length = 1;//蛇的身体体长//初始化蛇的坐标位置m_pPos = new SPoint[m_length+2];m_pPos[0].x = x_pos;m_pPos[0].y = y_pos;for (i = 1; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length];m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}}#ifndef __SNAKE_H_H#define __SNAKE_H_H#define SNAKE_MOVE 1#define SAFE_DELETE_ARRAY(p) {delete [](p);(p)=NULL;}#include <stdio.h>//节点图像显示位图状态enumBitmapState{M_NONE,M_UP_UP,M_DOWN_DOWN,M_LEFT_LEFT,M_RIGHT_RIGHT, M_UP_LEFT,M_UP_RIGHT,M_DOWN_LEFT,M_DOWN_RIGHT,M_LEFT_UP,M_LEFT_DOWN,M_RIGHT_UP,M_RIGHT_DOWN};//节点运动状态enum MoveState{S_NONE,S_UP,S_DOWN,S_LEFT,S_RIGHT};//节点位置坐标struct SPointint x;int y;};//定义蛇体状态struct Snake_Struct{MoveState head;//头部MoveState *body;//身体MoveState tail;//尾部};class CSnake{private:int m_length; //蛇的长度Snake_Struct m_newSnake; //蛇的新态的所有节点的运动状态Snake_Struct m_oldSnake; //蛇的原态的所有节点的坐标的运动状态BitmapState *m_pStateArray; //蛇的所有节点显示位图的状态SPoint *m_pPos; //蛇体坐标BitmapState GetRightState(MoveState oldDirect,MoveState newDirect);public:void Move(void);void ChangeDirect(MoveState d);void AddBody(int n=1);void SetHeadPos(int x, int y);BitmapState * GetStateArray(void);SPoint * GetPos(void);bool IsHeadTouchBody(int x, int y);int GetLength(void);void Initial(void);CSnake(int x_pos = 0, int y_pos = 0, int len = 1);~CSnake();};#endif#include "table.h"CTable::CTable()m_width = 0;m_height = 0;m_foodNumber = 0;m_blockNumber = 0;m_board = NULL;}CTable::~CTable(){if (m_board != NULL){SAFE_DELETE_ARRAY(m_board);}}//初始化面板void CTable::InitialTable(int w,int h){int i, j;m_width = w;m_height = h;m_snake.Initial();if (m_board != NULL){SAFE_DELETE_ARRAY(m_board);}//根据高度和宽度设置新的桌子m_board = new int * [m_height];for (i = 0; i < m_height; i++){m_board[i] = new int[m_width];for (j = 0; j < m_width; j++){m_board[i][j] = 0;}}//将桌子四周设置为墙for (i = 0; i < m_height; i++){m_board[i][0] = TB_STATE_SBLOCK;m_board[i][m_width-1] = TB_STA TE_SBLOCK;}for (i = 0; i < m_width; i++){m_board[0][i] = TB_STATE_SBLOCK;m_board[m_height-1][i] = TB_STA TE_SBLOCK;}}//食物的操作bool CTable::AddBlock(int x, int y){if( (x > 0) && (x < m_width) && (y > 0) && (y < m_height) && (m_board[y][x] == TB_STATE_OK)){m_board[y][x] = TB_STA TE_BLOCK;m_blockNumber++;return true;}return false;}bool CTable::AddFood(int x, int y){if( (x > 0) && (x < m_width) && (y > 0) && (y < m_height) && (m_board[y][x] == TB_STATE_OK)){m_board[y][x] = TB_STA TE_FOOD;m_foodNumber++;return true;}return false;}bool CTable::ClearFood(int x, int y){m_board[y][x] = TB_STA TE_OK;return true;}//取蛇对象CSnake * CTable::GetSnake(void){return &m_snake;}//取桌子对象int ** CTable::GetBoard(void){return m_board;}//获取数据信息int CTable::GetData(int x, int y){return m_board[y][x];}//蛇的操作void CTable::SnakeMove(void){m_snake.Move();}bool CTable::ChangeSnakeDirect(MoveState d){m_snake.ChangeDirect(d);return true;}#ifndef __TABLE_H_H#define __TABLE_H_H#define TB_STATE_OK 0 //正常#define TB_STATE_FOOD 1 //食物#define TB_STATE_BLOCK 2 //障碍-毒果#define TB_STATE_SBLOCK 3 //障碍-墙#include "snake.h"class CTable{private:int m_width;//桌子的宽度int m_height;//桌子的宽度int m_foodNumber;//桌子上食物的数量int m_blockNumber;//毒果的数量CSnake m_snake;//桌上的蛇int ** m_board;//桌的面板public:CTable();~CTable();//初始化面板void InitialTable(int w,int h);//食物的操作bool AddBlock(int x, int y);bool AddFood(int x, int y);bool ClearFood(int x, int y);//物件获取CSnake * GetSnake(void);int ** GetBoard(void);int GetData(int x, int y);//蛇的操作void SnakeMove(void);bool ChangeSnakeDirect(MoveState d); };#endif。
使用Python写一个贪吃蛇游戏实例代码
使⽤Python写⼀个贪吃蛇游戏实例代码我在程序中加⼊了分数显⽰,三种特殊⾷物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,⽽不是在Snake类中。
特殊⾷物:1.绿⾊:普通,吃了增加体型2.红⾊:吃了减少体型3.⾦⾊:吃了回到最初体型4.变⾊⾷物:吃了会根据⾷物颜⾊改变蛇的颜⾊#coding=UTF-8from Tkinter import *from random import randintimport tkMessageBoxclass Grid(object):def __init__(self, master=None,height=16, width=24, offset=10, grid_width=50, bg="#808080"):self.height = heightself.width = widthself.offset = offsetself.grid_width = grid_widthself.bg = bgself.canvas = Canvas(master, width=self.width*self.grid_width+2*self.offset, height=self.height*self.grid_width+2*self.offset, bg=self.bg)self.canvas.pack(side=RIGHT, fill=Y)def draw(self, pos, color, ):x = pos[0] * self.grid_width + self.offsety = pos[1] * self.grid_width + self.offset#outline属性要与⽹格的背景⾊(self.bg)相同,要不然会很丑self.canvas.create_rectangle(x, y, x + self.grid_width, y + self.grid_width, fill=color, outline=self.bg)class Food(object):def __init__(self, grid, color = "#23D978"):self.grid = gridself.color = colorself.set_pos()self.type = 1def set_pos(self):x = randint(0, self.grid.width - 1)y = randint(0, self.grid.height - 1)self.pos = (x, y)def display(self):self.grid.draw(self.pos, self.color)class Snake(object):def __init__(self, grid, color = "#000000"):self.grid = gridself.color = colorself.body = [(8, 11), (8, 12), (8, 13)]self.direction = "Up"for i in self.body:self.grid.draw(i, self.color)#这个⽅法⽤于游戏重新开始时初始化贪吃蛇的位置def initial(self):while not len(self.body) == 0:pop = self.body.pop()self.grid.draw(pop, self.grid.bg)self.body = [(8, 11), (8, 12), (8, 13)]self.direction = "Up"self.color = "#000000"for i in self.body:self.grid.draw(i, self.color)#蛇像⼀个指定点移动def move(self, new):self.body.insert(0, new)pop = self.body.pop()self.grid.draw(pop, self.grid.bg)self.grid.draw(new, self.color)#蛇像⼀个指定点移动,并增加长度def add(self ,new):self.body.insert(0, new)self.grid.draw(new, self.color)#蛇吃到了特殊⾷物1,剪短⾃⾝的长度def cut_down(self,new):self.body.insert(0, new)self.grid.draw(new, self.color)for i in range(0,3):pop = self.body.pop()self.grid.draw(pop, self.grid.bg)#蛇吃到了特殊⾷物2,回到最初长度def init(self, new):self.body.insert(0, new)self.grid.draw(new, self.color)while len(self.body) > 3:pop = self.body.pop()self.grid.draw(pop, self.grid.bg)#蛇吃到了特殊⾷物3,改变了⾃⾝的颜⾊,纯属好玩def change(self, new, color):self.color = colorself.body.insert(0, new)for item in self.body:self.grid.draw(item, self.color)class SnakeGame(Frame):def __init__(self, master):Frame.__init__(self, master)self.grid = Grid(master)self.snake = Snake(self.grid)self.food = Food(self.grid)self.gameover = Falseself.score = 0self.status = ['run', 'stop']self.speed = 300self.grid.canvas.bind_all("<KeyRelease>", self.key_release)self.display_food()#⽤于设置变⾊⾷物self.color_c = ("#FFB6C1","#6A5ACD","#0000FF","#F0FFF0","#FFFFE0","#F0F8FF","#EE82EE","#000000","#5FA8D9","#32CD32") self.i = 0#界⾯左侧显⽰分数self.m = StringVar()self.ft1 = ('Fixdsys', 40, "bold")self.m1 = Message(master, textvariable=self.m, aspect=5000, font=self.ft1, bg="#696969")self.m1.pack(side=LEFT, fill=Y)self.m.set("Score:"+str(self.score))#这个⽅法⽤于游戏重新开始时初始化游戏def initial(self):self.gameover = Falseself.score = 0self.m.set("Score:"+str(self.score))self.snake.initial()#type1:普通⾷物 type2:减少2 type3:⼤乐透,回到最初状态 type4:吃了会变⾊def display_food(self):self.food.color = "#23D978"self.food.type = 1if randint(0, 40) == 5:self.food.color = "#FFD700"self.food.type = 3while (self.food.pos in self.snake.body):self.food.set_pos()self.food.display()elif randint(0, 4) == 2:self.food.color = "#EE82EE"self.food.type = 4while (self.food.pos in self.snake.body):self.food.set_pos()self.food.display()elif len(self.snake.body) > 10 and randint(0, 16) == 5:self.food.color = "#BC8F8F"self.food.type = 2while (self.food.pos in self.snake.body):self.food.set_pos()self.food.display()else:while (self.food.pos in self.snake.body):self.food.set_pos()self.food.display()def key_release(self, event):key = event.keysymkey_dict = {"Up": "Down", "Down": "Up", "Left": "Right", "Right": "Left"}#蛇不可以像⾃⼰的反⽅向⾛if key_dict.has_key(key) and not key == key_dict[self.snake.direction]:self.snake.direction = keyself.move()elif key == 'p':self.status.reverse()def run(self):#⾸先判断游戏是否暂停if not self.status[0] == 'stop':#判断游戏是否结束if self.gameover == True:message = tkMessageBox.showinfo("Game Over", "your score: %d" % self.score)if message == 'ok':self.initial()if self.food.type == 4:color = self.color_c[self.i]self.i = (self.i+1)%10self.food.color = colorself.food.display()self.move(color)else:self.move()self.after(self.speed, self.run)def move(self, color="#EE82EE"):# 计算蛇下⼀次移动的点head = self.snake.body[0]if self.snake.direction == 'Up':if head[1] - 1 < 0:new = (head[0], 16)else:new = (head[0], head[1] - 1)elif self.snake.direction == 'Down':new = (head[0], (head[1] + 1) % 16)elif self.snake.direction == 'Left':if head[0] - 1 < 0:new = (24, head[1])else:new = (head[0] - 1, head[1])else:new = ((head[0] + 1) % 24, head[1])#撞到⾃⼰,设置游戏结束的标志位,等待下⼀循环if new in self.snake.body:self.gameover=True#吃到⾷物elif new == self.food.pos:if self.food.type == 1:self.snake.add(new)elif self.food.type == 2:self.snake.cut_down(new)elif self.food.type == 4:self.snake.change(new, color)else:self.snake.init(new)self.display_food()self.score = self.score+1self.m.set("Score:" + str(self.score))#什么都没撞到,继续前进else:self.snake.move(new)if __name__ == '__main__':root = Tk()snakegame = SnakeGame(root)snakegame.run()snakegame.mainloop()总结以上所述是⼩编给⼤家介绍的使⽤Python写⼀个贪吃蛇游戏实例代码,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
java实现贪吃蛇游戏代码(附完整源码)
java实现贪吃蛇游戏代码(附完整源码)先给⼤家分享源码,喜欢的朋友。
游戏界⾯GUI界⾯java实现贪吃蛇游戏需要创建⼀个桌⾯窗⼝出来,此时就需要使⽤java中的swing控件创建⼀个新窗⼝JFrame frame = new JFrame("贪吃蛇游戏");//设置⼤⼩frame.setBounds(10, 10, 900, 720);向窗⼝中添加控件可以直接⽤add⽅法往窗⼝中添加控件这⾥我创建GamePanel类继承⾃Panel,最后使⽤add⽅法添加GamePanel加载图⽚图⽚加载之后可以添加到窗⼝上public static URL bodyUrl = GetImage.class.getResource("/picture/body.png");public static ImageIcon body = new ImageIcon(bodyUrl);逻辑实现//每次刷新页⾯需要进⾏的操作@Overridepublic void actionPerformed(ActionEvent e) {//当游戏处于开始状态且游戏没有失败时if(gameStart && !isFail) {//蛇头所在的位置就是下⼀次蛇⾝体的位置bodyX[++bodyIndexRight] = headX;bodyY[bodyIndexRight] = headY;//bodyIndexLeft++;//长度到达数组的尾部if(bodyIndexRight==480) {for(int i=bodyIndexLeft, j=0; i<=bodyIndexRight; i++,j++) {bodyX[j]=bodyX[i];bodyY[j]=bodyY[i];}bodyIndexLeft=0;bodyIndexRight=length-1;}//更新头部位置if(fdirection==1) {//头部⽅向为上,将蛇头向上移动⼀个单位headY-=25;}else if(fdirection==2) {//头部⽅向为下,将蛇头向下移动⼀个单位headY+=25;}else if(fdirection==3) {//头部⽅向为左,将蛇头向左移动⼀个单位headX-=25;}else if(fdirection==4) {//头部⽅向为右,将蛇头向右移动⼀个单位headX+=25;}//当X坐标与Y坐标到达极限的时候,从另⼀端出来if(headX<25)headX = 850;if(headX>850)headX = 25;if(headY<75)headY = 650;if(headY>650)headY = 75;//当头部坐标和⾷物坐标重合时if(headX==foodX && headY==foodY){length++;score+=10;//重新⽣成⾷物,判断⾷物坐标和蛇⾝坐标是否重合,效率较慢while(true) {foodX = 25 + 25* random.nextInt(34);foodY = 75 + 25* random.nextInt(24);//判断⾷物是否和头部⾝体重合boolean isRepeat = false;//和头部重合if(foodX == headX && foodY == headY)isRepeat = true;//和⾝体重合for(int i=bodyIndexLeft; i<=bodyIndexRight; i++) {if(foodX == bodyX[i] && foodY == bodyY[i]){isRepeat = true;}}//当不重复的时候,⾷物⽣成成功,跳出循环if(isRepeat==false)break;}}else bodyIndexLeft++;//判断头部是否和⾝体重合for(int i=bodyIndexLeft; i<=bodyIndexRight;i++) {if(headX==bodyX[i] && headY==bodyY[i]){//游戏失败isFail = true;break;}}repaint();}timer.start();}键盘监听实现KeyListener接⼝,重写KeyPressed⽅法,在其中写当键盘按下时所对应的操作。
《贪吃蛇》游戏程序代码
“贪吃蛇”游戏程序代码我个人是比较喜欢玩游戏的,所以学习编程二年多了,很想做个游戏程序,由于能力有限,一直没能做好,后来突然看同学在手机上玩“贪吃蛇”,故想做出来,其一是因为此游戏界而容易设计,算法也比较简单,今天我就把我程序的代码和算法介绍一下,顺便把程序界而皮肤设计说一下.....程序中一个关于游戏信息的类如下,由于类的说明在程序中写的很清楚了,就不再多解释了:#include"time,h"〃方向定义const CPoint UP(CPoint(0,-1));const CPoint DOVN(CPoint(0,1));const CPoint LEFT(CPoint(-1,0)):const CPoint RIGHT(CPoint(1,0)):〃速度快慢定义const int HIGH =75;const int NORMAL =180;const int SLOW =300;const int MAX =80;〃表示转向数const int LENGTH=10;class GamcMsgpublic:GamcMsg(void):m_icon(0)InitGame();void InitGame(int up=VK_UP,int down = VK_DOWN,int left= VK.LEFT,int right= VK.RIGHT?(srand((unsigned)time(NULL));m_gameSpeed= NORMAL;m_speedNum=2;m_snakeNum=4:for(int i=0;i<m_snakcNum;++i)m_snakePoint[i]=CPoint(5+LENGTH*2*5+LENGTH,LENGTH*2*(i+5));m_run=true:m_direction=RIGHT;turnUP=up;turnDOWN=down;turnLEFT =left:turnRIGHT=right;}public:int m_gamcSpeed;//游戏速度int m_speedNum;//游戏速度数CPoint m_foodPoint:〃食物定义bool m_run;〃游戏状态,运得态还是暂停(结束)态CPoint m_snakePoint[MAX]:〃蛇身定义CPoint m_direction://蛇运动方向int m_snakeNum;〃蛇身结点数int m.icon;//用来设定食物是那种图标的int turnUP://用来表示玩家“上”键设的键int turnDOWN;〃用来表示玩家“下”键设的键int turnLEFT;//用来表示玩家“左”键设的键int turnRIGHT;//用来表示玩家“右”键设的键int m_num;//用来记录所选水果的编号);再让读者看一下程序主干类的设计,其中以下只列出由我们自己添加的一些变量的说明,其他的是由程序向导自动生成的,我就不说了:public:afx_msg void OnTimer(UINT_PTR nIDEvent);//程序中运行函数,即是一个定时器,时间就是上而类中的m_gameSpecd来控制的CStatic*m_staticArray;//这是一个蛇定义,是用来显示蛇的,上面只告诉蛇身结点的中心点位置坐标,然后在此中心画一个控件就类似于蛇身了afx.msg void OnCloseO://结束,主要是在其中销毁定时器的void GamcOver(void);//游戏结束函数afx_msg void OnRButtonDown(UINT nFlags,CPoint point);//当点击鼠标右键出现菜单afx_msg void OnNewGameO;//菜单选项,新游戏afx_msg void OnPauseOrStart();〃菜单选项,暂停/开始游戏afxjnsg void OnUpdatcQuick(CCmdUI*pCmdUI);//这3个函数本来是来标记速度的,和上面类中的m_speedNum对应,但是没有标记成功afx.msg void OnUpdateNormal(CCmdUI*pCmdUI);afx_msg void OnUpdateSlow(CCmdUI*pCmdUI):afx_msg void OnNormal0;//菜单选项,设定为普通速度afx_msg void OnSlowO;〃菜单选项,设定为慢速度afx_msg void OnQuickO;//菜单选项,设定为快速度afx_msg void OnlntroduceO://游戏介绍,就是弹出一个对话框而以afx_msg void OnMoreprogram();〃进入我的博客的函数afx_msg void OnAbout():〃关于"贪吃蛇”说明的对话框afx_msg void OnExit();//退出游戏CFont m.font;〃这就是上图中显示"空心字体”的亍体设置void ShowHo11o wFont(int ex,int cy,CString str)://显示空心字体函数,在(Cx,Cy)处显示字符串strafx_msg void OnBnClickedExit();//退出游戏private:int m_iconl;//表明蛇吃第1种水果的个数int m_icon2://表明蛇吃第2种水果的个数int m_icon3://表明蛇吃第3种水果的个数然后给读者写的是我程序运行很重要的一个函数,W3!_TIMER显示函数,里面有食物位置随机出现,判断蛇死,蛇移动等:void CSnakeDlg::OnTimer(UINT_PTR nIDEvent)(if(game.m_snakePoint[0].x<011game.m_snakePoint[0].y<LENGTH I|game.m_snakePoint[0].x>70011game.m_snakePoint[0].y>500)//当蛇跑出边算,游戏结束(GamcOver();}for(int j=game.m_snakeNum-l:j>0;—j)//蛇移动的量的变化,当重新设定这些控件的位置时也就是让蛇移动起来game.m_snakePoint[j]=game.m_snakePoint[j-1];game.m_snakePoint[0].x+= game.m_di recti on.x* LENGTH * 2;//蛇头移动game.m_snakePoint[0].y+= game.m_di recti on.y*LENGTH * 2;for(int i=0;i<game.m_snakcNum;++i){m_staticArray[i].SetWindowPos(NULL,game.m_snakePoint[i],x-LENGTH,game.m_snakePoint[i].y-LENGTH,game.m_snakePoint[i].x+ LENGTH,game.m_snakePoint[i].y+LENGTH,SW_SHOW);}for(int j=l;j<game.m_snakcNum;++j)//当蛇撞到自己也结束游戏if(game.m_snakcPoint[0]=game.m_snakePoint[j]){GamcOver();)m.staticArray[NIAX].ModifyStyle(OxF,SS_ICON|SS_CENTERIMAGE);〃显示水果m_stat icArray[MAX].Set Icon(AfxGetAppO->LoadIcon(game.m_icon));m_stat icArray[MAX].SetWi ndowPos(NULL,game.m_foodPoint.x,game.m_foodPoint.y,32,32,SW_SHOW);〃当蛇吃到水果if(game.m_snakePoint[0].x<game.m_foodPoint.x+20+LENGTH&& game.m_snakePoint[0].x>game.m_foodPoint.x-LENGTH&&game.m_snakePoint[0].y<game.m_foodPoint.y+20+LENGTH&&game.m_snakePoint[0].y>game.m_foodPoint.y-LENGTH)(game.m_foodPoint= CPoint(LENGTH*gamc.RandNum(2,37),LENGTH*game.RandNum(2,27));CString str:if(game.m_num =0){++m_iconl;str.Formatm_iconl);GetDlgItem(IDC_EDITl)->SetWindowTextA(str);else if(game.m_num =1)++m_icon2;str.Formatm_icon2);GetDlgItem(IDC_EDIT2)->SetWindowTextA(str):)else{++m_icon3:str.Format(飞d”,m_icon3);GetDlgItem(IDC_EDIT3)->SetWindowTextA(str);}game.m_num = game.RandNum(0,3);game.m_icon=IDI_ICON1+game.m_num;//重新加1个水果game.m_snakeNum++;〃蛇的长度加1str.Format(*%<!*,game.m_snakeNum);GetDlgItem(IDC_EDIT4)->Se t W i ndowTextA(str):)CDialog::OnTimer(nIDEvent);)如下再介绍应用在对话框中来响应键盘消息,我写的是一个键盘“钩子”,代码如下:HHOOK g_hKcyboard=NULL;HWND g_hWnd= NULL:LRESULT CALLBACK KeyboardProc(int code,//hook code WPARAM wParam,//virtual-key code LPARAM1Param //keystroke-message information)(if(wParam=game.turnUP){if(game.m_direction.y=0)game.m_direction=UP;}else if(wParam=game.turnDOWN)(if(game.m_direction.y=0)game.m_direction=DOWN:)else if(wParam=game.turnLEFT){if(game.m_direction.x=0)game.m_direction=LEFT:)else if(wParam=game.turnRIGHT){if(game.m_direction.x=0)game.m_direction=RIGHT;)elsereturn1;然后介绍一下,点击鼠标右键出现菜单:voidCSnakcDlg::OnRButtonDown(UINT nFlags,CPoint point){if(game.m_run)KillTimer(l);CMenu oMenu;if(oMenu.LoadMenu(IDR.MENU1))(CMenu*pPopup = oMenu.GetSubMcnu(O);ASSERT(pPopup!=NULL);CPoint oPoint:GetCursorPos(&oPoint);SetForegroundWindowO;pPopup->TrackPopupMenu(TPM_LEFTALIGN,oPoint.x,oPoint.y,this);}if(game.m_run)SetTimer(1,game.m_gameSpeed,NULL);CDialog::OnRBu11onDown(nF1ags,point);}然后来介绍一下程序中是怎样来改变按键的,首先说一下,我开始用EDIT控件来让用户输入,但是程序中我用的是键盘"钩子”来处理消息的,所以EDIT 控件在程序中是不可以输入信息的,所以我选的是下拉列表,代码如下,解释也在程序中相应给出:int keyNum[40]={〃定义玩家可以设的键,把所有的健信息存在这个数组中VK.UP,VK.DOWN,VK.LEFT,VK.RIGHT,VK.NUMPADO,VK_NUMPAD1,VK.NUMPAD2,VK.NUMPAD3,VK_NUMPAD4,VK_NUMPAD5, VK NUMPAD6,VK NUMPAD7,VK NUMPAD8,VK NUMPAD9);void CSnakeDlg::0nKeyset()//键盘设置响应消息函数//T0D0:在此添加命令处理程序代码if(game.m_run)KillTimer(l);CKcySetDlg dig:if(dig.DoModalO=IDOK)(if(dig.m_up =dig.m_down11dig.m_up =dig.m_left||dig.m_up =dig.m_right||dig.m_down=dig.m_left||dig.m_down ==dig.m_right||dig.m_left=dig.m_right)(MessageBox(w键位不能设置为重复的,设置失败!");if(game.m_run)SetTimcr(1,game.m_gamcSpeed,NULL);return;}game.turnUP =kcyNum[GetMarkNum(dlg.m_up)]://重新设置键game.turnDOWN=keyNum[GetMarkNum(dlg.m_down)]:game.turnLEFT =keyNum[GetMarkNum(dlg.m_left)];game.turnRIGHT =keyNum[GetMarkNum(dlg.m_right)];}if(game.m_run)SetTimcr(1,game.m_gamcSpeed,NULL);}int CSnakcDlg::GetMarkNum(CString str)//返回重新设置键对应数组的“索引”int backNum = 0;if(str="上")backNum = 0:else if(str=="下”) backNum =1:else if(str=="左") backNum=2;else if(str="右") backNum=3:else{CString ss;for(char i='A';i〈='Z';++i) {ss.Format(飞c”,i);if(ss―str.Right(l))(backNum=i-'A'+4;return backNum;})for(int i=0:i<=9:++i)ss.Format("%d",i);if(ss=str.Right(1))(backNum=i+30;return backNum;})}return backNum;)最后写一下程序更换皮肤的一段代码,本来觉得不算很难的,不过还是介绍一下吧,对了我用的是Skinmagic做的皮肤,不过这个软件你可以通过网上的说明进行注册,也可以自己把它破解,其实很简单,大家可以试试:void CSnakeDlg::0nChangSkin()(//T0D0:在此添加命令处理程序代码i f(game.m_run)KillTimer(l);CFileDialog dig(TRUE,NULL,NULL,OFN.HIDEREADONLY|OFN.OVERWRITEPROMPT,"Skin Files(*.smf7|*.smf|T,AfxGetMainWndO);CString strPath,strText="";if(dig.DoModalO=IDOK)(strPath=dig.GetPathNamcO:VERIFYd=LoadSkinFile(strPath));if(game.m_run)SetTimerd,game.m_gameSpeed,NULL);)还有很多小函数,由于都是比较简单的,就不多写了,程序介绍就到这里,呵呵,希望我能够帮你解决你写程序遇到的问题,如果大家想知道如何做程序的皮肤的话,网上有很多这样的博客,我就是在那样的博客里学到的,如果还是想我来介绍的话,那给我留言说下哦,呵呵,谢了,有问题请在下面留言.。
贪吃蛇游戏代码(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++)<>。
纯C语言编写贪吃蛇(附源码,无EasyX、MFC)
纯C语⾔编写贪吃蛇(附源码,⽆EasyX、MFC)⼤⼀下学期,我所选的C语⾔⼯程实践是写⼀个贪吃蛇游戏。
那⼏天真的挺肝的,完成本专业的答辩之后就没怎么动过这程序了。
那时候写的贪吃蛇,还有⼀个栈溢出的问题没有解决,是因为当时所学知识有限,还没想到较好的解决⽅法。
现在⼤⼆上学期,在上了好⼏节数据结构之后,对栈有了⼀定的了解,随着对栈的学习,我想出了解决我写的贪吃蛇栈溢出的办法。
其实是前两天刚刚有这个想法,刚刚才测试并实现了,办法可⾏。
现在我加⼊了计算机学院的创新开放实验室,打算做的⼀个项⽬是微信⼩程序。
以后想记录⼀下我的开发过程和⼀些经历,⼜刚刚完善好贪吃蛇的代码,就简单记录⼀下吧。
因为代码⽐较长,先把参考资料写⼀下,想⾃⼰⼿写⼀遍的建议先看参考资料,再看这⾥的代码参考资料源代码/*预处理*/#include <windows.h>#include <stdio.h>#include <conio.h>#include <string.h>#include <time.h>/*宏定义*/#define YES 1#define NO 0//蛇的移动⽅向#define U 1 //上#define D 2 //下#define L 3 //左#define R 4 //右#define RESPEED 250 //蛇的移动速度/*定义节点*/typedef struct SNAKE{int x;int y;struct SNAKE* next;}snake;/*全局变量*/snake* head, * food; //蛇头指针,⾷物指针snake* q; //遍历蛇的时候⽤到的指针/*【以下为所有函数的声明】*/void HideCursor(void); //隐藏光标void color(short int num); //颜⾊函数void StartWindow(void); //开始界⾯int gotoxy(int x, int y); //定位光标位置void creatMap(void); //创建地图void notice(int* score, int* highscore, int* Time, int* LongTime); //提⽰void initsnake(void); //初始化蛇⾝int biteself(unsigned long* sleeptime); //判断是否咬到了⾃⼰int createfood(void); //随机出现⾷物void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime); //结束游戏void pause(int* PauseBegin, int* PauseEnd); //暂停游戏void gamecontrol(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //控制游戏(包含蛇不能穿墙)void snakemove(unsigned long* sleeptime, int* count, int* score, int* status, int* endgamestatus); //蛇移动void gamestart(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime, int* TimeBegin); //游戏初始化void gamecontinue(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //再来⼀局void stop(unsigned long* sleeptime); //蛇停⽌移动void start(unsigned long* sleeptime); //蛇恢复移动void reset(int* count, int* score, int* Time, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //重置多项数据void updatescore(int* score, int* highscore, int* Time, int* LongTime); //更新多项数据int main(void){unsigned long sleeptime = RESPEED;int score = 0, highscore = 0, count = 0; //count是记录吃到⾷物的次数int status, endgamestatus = 0; //游戏结束情况,0未开始游戏前退出,1撞到墙,2咬到⾃⼰,3主动退出游戏,4通关HideCursor();gamestart(&score, &highscore, &endgamestatus, &Time, &LongTime, &TimeBegin);gamecontrol(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &Pa useBegin, &PauseEnd);endgame(&score, &highscore, &endgamestatus, &Time, &LongTime);gamecontinue(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &P auseBegin, &PauseEnd);return 0;}void HideCursor(void) //隐藏光标{CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);}void color(short int num){HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE));SetConsoleTextAttribute(hConsole, num);}void StartWindow(void){short int i;system("mode con cols=120 lines=30"); //设置窗⼝⼤⼩printf("温馨提⽰:请使⽤键盘操作(⿏标点击可能会导致程序出错)\n");printf("╔═══════════════════════════════════════════════════╗ \n");for (i = 0; i < 26; i++){printf("║ ║ \n");}printf("╚═══════════════════════════════════════════════════╝ \n");gotoxy(23, 2);color(3);printf("贪吃蛇");for (i = 15; ; i--){gotoxy(18, 4);color(i);printf("按任意键加载程序");Sleep(600);if (i == 1){i = 15;}if (kbhit()) //判断是否按键,等待输⼊按键为0,按键为1{break;}}gotoxy(10, 4);printf("1.开始游戏 2.退出游戏");getch();}int gotoxy(int x, int y){HANDLE handle; //定义句柄变量handle,创建⼀个句柄COORD pos; //定义结构体coord (坐标系coord)pos.X = x; //横坐标xpos.Y = y; //纵坐标yhandle = GetStdHandle(STD_OUTPUT_HANDLE); //获取控制台输出句柄(值为-11)SetConsoleCursorPosition(handle, pos); //移动光标return YES;}void creatMap(void){int i;//地图⼤⼩:长24×宽20printf("■");gotoxy(i, 27);printf("■");}for (i = 7; i < 28; i++) //打印左右边框{gotoxy(2, i);printf("■");gotoxy(50, i);printf("■");}}void notice(int* score, int* highscore, int* Time, int* LongTime){system("title 2018051170 Project:贪吃蛇");gotoxy(4, 4);color(15);printf("得分:%3d 最⾼分:%3d ⽣存:%4ds 最久⽣存:%4ds", *score, *highscore, *Time, *LongTime); gotoxy(60, 7);printf("Author: 2018051170 Project: 贪吃蛇");gotoxy(60, 9);printf("游戏说明:");gotoxy(60, 10);printf("不能穿墙,不能咬到⾃⼰");gotoxy(60, 11);printf("↑↓←→控制蛇的移动");gotoxy(60, 12);printf("ESC:退出游戏空格:暂停游戏");}void initsnake(void){int i;snake* tail;tail = (snake*)malloc(sizeof(snake)); //从蛇尾开始,插头法,以x,y设定开始的位置tail->x = 26;tail->y = 14;tail->next = NULL;for (i = 1; i < 3; i++){head = (snake*)malloc(sizeof(snake));head->next = tail;head->x = 26 - 2 * i;head->y = 14;tail = head;}while (tail != NULL) //从头到为,输出蛇⾝{gotoxy(tail->x, tail->y);if (i == 3){color(2);printf("●");i++;}else if (tail != NULL){color(2);printf("■");}tail = tail->next;}}int biteself(unsigned long* sleeptime){snake* self;self = head->next;while (self != NULL){if (self->x == head->x && self->y == head->y)self = self->next;}return NO;}int createfood(void){snake* food_1;food_1 = (snake*)malloc(sizeof(snake));srand((unsigned)time(NULL)); //产⽣⼀个随机数while ((food_1->x % 2) != 0) //保证其为偶数,使得⾷物能与蛇头对其{food_1->x = rand() % 50; //保证其在墙壁⾥X1 < X < X2if (food_1->x <= 4){food_1->x = food_1->x + 4;}}food_1->y = rand() % 27; //保证其在墙壁⾥Y1 < Y < Y2if (food_1->y < 7){food_1->y = food_1->y + 7;}q = head;while (q != NULL) //判断蛇⾝是否与⾷物重合{if (q->x == food_1->x && q->y == food_1->y){free(food_1);return 1;}if (q->next == NULL){break;}q = q->next;}gotoxy(food_1->x, food_1->y);food = food_1;color(3);printf("★");return 0;}void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime) {color(15);gotoxy(60, 14);if (*endgamestatus == 0){printf("您退出了游戏。
C语言版贪吃蛇代码
C语言版贪食蛇游戏源代码(我自己写的)热1已有58 次阅读2011-01-18 17:57#include <stdio.h>#include <windows.h>#include <conio.h>#include <string.h>#define UP 0#define DOWN 1#define LEFT 2#define RIGHT 3//宏定义,定义四个方向--0 1 2 3分别代表上下左右#define TURN_NUM 1000//可以保存的最多转弯次数,一条蛇同时最多只能有1000次的弯曲#define INIT_LENGTH 8#define UP_EDGE 0#define DOWN_EDGE 24#define LEFT_EDGE 0#define RIGHT_EDGE 79//定义上下左右四个边界#define X 0//初始状态下蛇的身体坐标(LEFT_EDGE+X,UP_EDGE+Y)#define Y 0//决定初始状态下蛇的身体相对于游戏界面原点(LEFT_EDGE,UP_EDGE)的位置/*定义全局变量*/char buf[1000]="@*******";//决定初始的snake_length的值:必须与INIT_LENGTH保持同步char *snake=buf;//蛇的身体,最长有1000个环节char FOOD='$';//记录食物的形状int food_num=0;//记录已经吃下的食物数量int score=0;//记录当前的得分,由food_num决定int snake_length=INIT_LENGTH;//initializer is not a constant:strlen(snake); int cursor[2]={LEFT_EDGE+20+INIT_LENGTH,UP_EDGE+10};//记录当前光标所指位置int head[2]={LEFT_EDGE+20+INIT_LENGTH-1,UP_EDGE+10};//记录头部的坐标int tail[2]={0,0};//记录尾巴的坐标int old_tail[2];//记录上一步尾巴所在位置int food[2]={0,0};//记录食物的坐标int init_position[2]={LEFT_EDGE+X,UP_EDGE+Y};//蛇的初始位置int direction=RIGHT;//记录当前蛇的头部的运动方向int turn_point[TURN_NUM][2];int head_turn_num=0;//记录头部的转弯次数int tail_turn_num=0;//记录尾巴的转弯次数int game_over=0;//判断游戏是否结束/*主方法*/void main(){//函数声名void gotoxy(int x,int y);//移动光标的位置void cur_state();//测试游戏的当前状态参数void print_introduction();//打印游戏规则void init();//初始化游戏void control();//接收键盘控制命令void move();//控制身体的运动void move_up();//向上运动void move_down();//向下运动void move_left();//向左运动void move_right();//向右运动void update_tail_position();//更新尾巴的坐标void generate_food();//随机产生食物void eat_food();//吃下食物char ch;while(!game_over){print_introduction();printf("\t\t按任意键开始游戏");getch();system("cls");//cur_state();init();control();system("cls");gotoxy(0,10);printf("\t\t您的当前得分是%d\n",score);printf("\t\t这条蛇共转了%d次弯,它的身体长度是%d\n",head_turn_num,strlen(snake));printf("\t\t游戏结束,您要再玩一局吗?(y/n)");scanf("%c",&ch);getchar();if(ch=='y'||ch=='Y'){continue;}else{system("cls");printf("\n\n\n\t\t\t谢谢您的使用,再见!");_sleep(3000);game_over=1;}}}/*打印游戏规则*/void print_introduction(){int i=0;int rule_num;char *rule[4];rule[i++]="\n\n\t\t\t欢迎您来玩贪食蛇游戏\n";rule[i++]="\t\t游戏规则如下:\n";rule[i++]="\t\t1.按上下左右键控制蛇的运动方向\n";rule[i++]="\t\t2.按Ctrl+C结束当前游戏\n";rule_num=i;system("cls");for(i=0;i<rule_num;i++){puts(rule[i]);}}/*移动光标的位置*/void gotoxy(int x,int y){COORD coord={x,y};SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); }/*测试游戏的当前状态参数*/void cur_state(){printf("游戏的当前状态参数如下:\n");printf("snake=%s\n",snake);printf("snake_body_length=%d\n",strlen(snake));printf("head=(%d,%d)\n",head[0],head[1]);printf("tail=(%d,%d)\n",tail[0],tail[1]);printf("direction=%d\n",direction);printf("game_over=%d\n",game_over);}/*游戏进入初始状态*/void init(){int i;/*初始化游戏参数*/food_num=0;//记录已经吃下的食物数量score=0;//记录当前的得分,由food_num决定snake_length=INIT_LENGTH;cursor[0]=init_position[0]+INIT_LENGTH;cursor[1]=init_position[1];//记录当前光标所指位置head[0]=init_position[0]+INIT_LENGTH-1;head[1]=init_position[1];//记录头部的坐标tail[0]=init_position[0];tail[1]=init_position[1];//记录尾巴的坐标direction=RIGHT;//记录当前蛇的头部的运动方向head_turn_num=0;//记录头部的转弯次数tail_turn_num=0;//记录尾巴的转弯次数game_over=0;//判断游戏是否结束turn_point[0][0]=RIGHT_EDGE;turn_point[0][1]=0;/*游戏参数初始化完毕*/generate_food();//投下第一粒食物gotoxy(init_position[0],init_position[1]);//将光标移动到到初始化位置for(i=snake_length;i>0;i--){putchar(snake[i-1]);}}/*接收键盘控制命令*/void control(){char command;//存放接收到命令while(1){command=getch();if(command==-32){//F11,F12:-123,-122command=getch();if(command=='H' && (direction==LEFT || direction==RIGHT)){//光标上移direction=UP;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command=='P' && (direction==LEFT || direction==RIGHT)){//光标下移direction=DOWN;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command=='K' && (direction==UP || direction==DOWN)){//光标左移direction=LEFT;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command=='M' && (direction==UP || direction==DOWN)){//光标右移direction=RIGHT;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command==-122 || command==-123);}else if(command==0){command=getch();//接收Fn的下一个字符//F1~F10:59~68}else if(command>=1&&command<=26){//Ctrl+a~z:1~26if(command==3){break;}}else{//do nothing!}move();if(head[0]==food[0] && head[1]==food[1]){eat_food();//吃掉一粒事物generate_food();//投下新食物}}}/*蛇的身体运动*/void move(){if(direction==UP){//printf("Moving up!\n");move_up();}else if(direction==DOWN){//printf("Moving down!\n");move_down();}else if(direction==LEFT){//printf("Moving left!\n");move_left();}else if(direction==RIGHT){//printf("Moving right!\n");move_right();}}/*向上运动*/void move_up(){if(cursor[1]>=UP_EDGE){gotoxy(head[0],head[1]);putchar('*');gotoxy(head[0],head[1]-1); putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[1]-=1;cursor[0]=head[0];cursor[1]=head[1]-1; gotoxy(cursor[0],cursor[1]); }else{gotoxy(head[0],head[1]);}}/*向下运动*/void move_down(){if(cursor[1]<=DOWN_EDGE){ gotoxy(head[0],head[1]); putchar('*');gotoxy(head[0],head[1]+1); putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[1]+=1;cursor[0]=head[0];cursor[1]=head[1]+1; gotoxy(cursor[0],cursor[1]); }else{gotoxy(head[0],head[1]);}}/*向左运动*/void move_left(){if(cursor[0]>=LEFT_EDGE){ gotoxy(head[0],head[1]); putchar('*');gotoxy(head[0]-1,head[1]); putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[0]-=1;cursor[0]=head[0]-1;cursor[1]=head[1];gotoxy(cursor[0],cursor[1]);}else{gotoxy(head[0],head[1]);}}/*向右运动*/void move_right(){if(cursor[0]<=RIGHT_EDGE){gotoxy(head[0],head[1]);putchar('*');putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[0]+=1;cursor[0]=head[0]+1;cursor[1]=head[1];gotoxy(cursor[0],cursor[1]);}else{gotoxy(head[0],head[1]);}}/*更新尾巴的坐标*/void update_tail_position(){old_tail[0]=tail[0];old_tail[1]=tail[1];//保存上次尾巴的位置if(tail[0]==food[0] && tail[1]==food[1]){gotoxy(tail[0],tail[1]);putchar(FOOD);}if(tail_turn_num<head_turn_num){if(tail[0]<turn_point[tail_turn_num%TURN_NUM][0]){tail[0]+=1;}else if(tail[0]>turn_point[tail_turn_num%TURN_NUM][0]){ tail[0]-=1;}else if(tail[1]<turn_point[tail_turn_num%TURN_NUM][1]){ tail[1]+=1;}else if(tail[1]>turn_point[tail_turn_num%TURN_NUM][1]){ tail[1]-=1;}else if(tail[0]==turn_point[(tail_turn_num-1)%TURN_NUM][0] && tail[1]==turn_point[(tail_turn_num-1)%TURN_NUM][1]){if(tail[0]<turn_point[tail_turn_num%TURN_NUM][0]){tail[0]+=1;}else if(tail[0]>turn_point[tail_turn_num%TURN_NUM][0]){tail[0]-=1;}else if(tail[1]<turn_point[tail_turn_num%TURN_NUM][1]){tail[1]+=1;}else if(tail[1]>turn_point[tail_turn_num%TURN_NUM][1]){tail[1]-=1;}}if(tail[0]==turn_point[tail_turn_num%TURN_NUM][0] && tail[1]==turn_point[tail_turn_num%TURN_NUM][1]){tail_turn_num+=1;}}else if(tail_turn_num==head_turn_num){if(tail[0]<head[0]){tail[0]+=1;}else if(tail[0]>head[0]){tail[0]-=1;}else if(tail[1]<head[1]){tail[1]+=1;}else if(tail[1]>head[1]){tail[1]-=1;}}}void generate_food(){int i=0,j=0;do{i=rand()%DOWN_EDGE;}while(i<UP_EDGE || i>DOWN_EDGE);do{j=rand()%DOWN_EDGE;}while(j<LEFT_EDGE || j>RIGHT_EDGE);food[0]=i;food[1]=j;gotoxy(food[0],food[1]);//抵达食物投放点putchar(FOOD);//放置食物gotoxy(cursor[0],cursor[1]);//返回光标当前位置}void eat_food(){if(tail[0]==turn_point[(tail_turn_num-1)%TURN_NUM][0] &&tail[1]==turn_point[(tail_turn_num-1)%TURN_NUM][1]){ tail_turn_num-=1;}snake[snake_length++]=snake[1];tail[0]=old_tail[0];tail[1]=old_tail[1];//将尾巴回退到上一步所在的位置gotoxy(tail[0],tail[1]);putchar(snake[1]);food_num++;score=food_num;gotoxy(cursor[0],cursor[1]);}。
贪吃蛇游戏代码
贪吃蛇游戏代码贪吃蛇是一个经典的小游戏,可以在很多平台和设备上找到。
如果你想自己开发一个贪吃蛇游戏,这里有一个简单的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()这个代码实现了一个基本的贪吃蛇游戏。
经典游戏贪吃蛇代码(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编程代码
游戏贪吃蛇python编程代码基本准备首先,我们需要安装pygame库,小编通过pip install pygame,很快就安装好了。
在完成贪吃蛇小游戏的时候,我们需要知道整个游戏分为四部分:游戏显示:游戏界面、结束界面贪吃蛇:头部、身体、食物判断、死亡判断树莓:随机生成按键控制:上、下、左、右游戏显示首先,我们来初始化pygame,定义颜色、游戏界面的窗口大小、标题和图标等。
1# 初始化pygame2pygame.init()3fpsClock = pygame.time.Clock()4# 创建pygame显示层5playSurface = pygame.display.set_mode((600,460))#窗口大小6pygame.display.set_caption('Snake Game')#窗口名称7# 定义颜色变量8redColour = pygame.Color(255,0,0)9blackColour = pygame.Color(0,0,0)10whiteColour = pygame.Color(255,255,255)11greyColour = pygame.Color(150,150,150)游戏结束界面,我们会显示“Game Over!”和该局游戏所得分数,相关代码如下:1# 定义gameOver函数2def gameOver(playSurface,score):3 gameOverFont = pygame.font.SysFont('arial.ttf',54) #游戏结束字体和大小4 gameOverSurf = gameOverFont.render('Game Over!', True, greyColour) #游戏结束内容显示5 gameOverRect = gameOverSurf.get_rect()6 gameOverRect.midtop = (300, 10) #显示位置7 playSurface.blit(gameOverSurf, gameOverRect)8 scoreFont = pygame.font.SysFont('arial.ttf',54) #得分情况显示9 scoreSurf = scoreFont.render('Score:'+str(score), True, greyColour)10 scoreRect = scoreSurf.get_rect()11 scoreRect.midtop = (300, 50)12 playSurface.blit(scoreSurf, scoreRect)13 pygame.display.flip() #刷新显示界面14 time.sleep(5) #休眠五秒钟自动退出界面15 pygame.quit()16 sys.exit()贪吃蛇和树莓我们需要将整个界面看成许多20*20的小方块,每个方块代表一个单位,蛇的长度用单位来表示,同时我们采用列表的形式存储蛇的身体。
pthon贪吃蛇游戏详细代码
pthon贪吃蛇游戏详细代码本⽂实例为⼤家分享了pthon贪吃蛇游戏的具体代码,供⼤家参考,具体内容如下在写Python游戏项⽬时,最重要的时python中的pygame库。
安装pygame库和⽤法在我CSDN博客另⼀篇⽂章上。
这⾥就不详细说了,下边时运⾏游戏界⾯。
下边是详细的代码和注释import pygame,sys,random,timefrom pygame.locals import * #从pygame模块导⼊常⽤的函数和常量#定义颜⾊变量black_colour = pygame.Color(0,0,0)white_colour = pygame.Color(255,255,255)red_colour = pygame.Color(255,0,0)grey_colour = pygame.Color(150,150,150)#定义游戏结束函数def GameOver(gamesurface):#设置提⽰字体的格式GameOver_font = pygame.font.SysFont("MicrosoftYaHei", 16)#设置提⽰字体的颜⾊GameOver_colour = GameOver_font.render('Game Over',True,grey_colour)#设置提⽰位置GameOver_location = GameOver_colour.get_rect()GameOver_location.midtop = (320,10)#绑定以上设置到句柄gamesurface.blit(GameOver_colour,GameOver_location)#提⽰运⾏信息pygame.display.flip()#休眠5秒time.sleep(5)#退出游戏pygame.quit()#退出程序sys.exit()#定义主函数def main():#初始化pygame,为使⽤硬件做准备pygame.init()pygame.time.Clock()ftpsClock = pygame.time.Clock()#创建⼀个窗⼝gamesurface = pygame.display.set_mode((640,480))#设置窗⼝的标题pygame.display.set_caption('tanchishe snake')#初始化变量#初始化贪吃蛇的起始位置snakeposition = [100,100]#初始化贪吃蛇的长度snakelength = [[100,100],[80,100],[60,100]]#初始化⽬标⽅块的位置square_purpose = [300,300]#初始化⼀个数来判断⽬标⽅块是否存在square_position = 1#初始化⽅向,⽤来使贪吃蛇移动derection = "right"change_derection = derection#进⾏游戏主循环while True:#检测按键等pygame事件for event in pygame.event.get():if event.type==QUIT:#接收到退出事件后,退出程序pygame.quit()sys.exit()elif event.type==KEYDOWN:#判断键盘事件,⽤w,s,a,d来表⽰上下左右if event.key==K_RIGHT or event.key==ord('d'):change_derection = "right"if event.key==K_LEFT or event.key==ord('a'):change_derection = "left"if event.key==K_UP or event.key==ord('w'):change_derection = "up"if event.key==K_DOWN or event.key==ord('s'):change_derection = "down"if event.key==K_ESCAPE:pygame.event.post(pygame.event.Event(QUIT))#判断移动的⽅向是否相反if change_derection =='left'and not derection =='right':derection = change_derectionif change_derection =='right'and not derection =='left':derection = change_derectionif change_derection == 'up' and not derection =='down':derection = change_derectionif change_derection == 'down' and not derection == 'up':derection = change_derection#根据⽅向,改变坐标if derection == 'left':snakeposition[0] -= 20if derection == 'right':snakeposition[0] += 20if derection == 'up':snakeposition[1] -= 20if derection == 'down':snakeposition[1] += 20#增加蛇的长度snakelength.insert(0,list(snakeposition))#判断是否吃掉⽬标⽅块if snakeposition[0]==square_purpose[0] and snakeposition[1]==square_purpose[1]:square_position = 0else:snakelength.pop()#重新⽣成⽬标⽅块if square_position ==0:#随机⽣成x,y,扩⼤⼆⼗倍,在窗⼝范围内x = random.randrange(1,32)y = random.randrange(1,24)square_purpose = [int(x*20),int(y*20)]square_position = 1#绘制pygame显⽰层gamesurface.fill(black_colour)for position in snakelength:pygame.draw.rect(gamesurface,white_colour,Rect(position[0],position[1],20,20))pygame.draw.rect(gamesurface,red_colour,Rect(square_purpose[0],square_purpose[1],20,20)) #刷新pygame显⽰层pygame.display.flip()#判断是否死亡if snakeposition[0]<0 or snakeposition[0]>620:GameOver(gamesurface)if snakeposition[1]<0 or snakeposition[1]>460:GameOver(gamesurface)for snakebody in snakelength[1:]:if snakeposition[0]==snakebody[0] and snakeposition[1]==snakebody[1]:GameOver(gamesurface)#控制游戏速度ftpsClock.tick(5)if __name__ == "__main__":main()以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
记一次贪吃蛇游戏作文
记一次贪吃蛇游戏作文英文回答:Once upon a time, I was playing the addictive game of Snake on my phone. It was a simple yet challenging game where I controlled a snake to eat as many apples as possible without crashing into the walls or its own tail. The more apples the snake ate, the longer it became, making it harder to maneuver around the screen.As I started the game, I quickly realized that strategy was key. I had to plan my moves carefully to avoid getting trapped or hitting a wall. It was a game of anticipation and quick reflexes. Each time the snake ate an apple, it grew longer, and I had to adjust my strategy accordingly.I remember one particular moment when I was about to reach a new high score. The snake had grown so long that it was almost filling up the entire screen. I had to navigate through a narrow passage between the wall and the snake'stail to reach the next apple. It was a tense moment, and I could feel my heart racing as I made split-second decisions to avoid collision. Finally, I managed to get the apple and continue the game.The game of Snake taught me valuable lessons about patience, strategy, and adaptability. It showed me the importance of planning ahead and thinking on my feet. It also taught me that sometimes taking risks can lead to great rewards. For example, there were times when I had to make daring moves to avoid getting trapped, and those moves paid off in the end.中文回答:从前,我在手机上玩贪吃蛇这个令人上瘾的游戏。
贪吃蛇代码
#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);//暂停}}。
python贪吃蛇游戏代码
python贪吃蛇游戏代码本⽂实例为⼤家分享了python贪吃蛇游戏的具体代码,供⼤家参考,具体内容如下贪吃蛇游戏截图:⾸先安装pygame,可以使⽤pip安装pygame:pip install pygame运⾏以下代码即可:#!/usr/bin/env pythonimport pygame,sys,time,randomfrom pygame.locals import *# 定义颜⾊变量redColour = pygame.Color(255,0,0)blackColour = pygame.Color(0,0,0)whiteColour = pygame.Color(255,255,255)greyColour = pygame.Color(150,150,150)# 定义gameOver函数def gameOver(playSurface):gameOverFont = pygame.font.Font('arial.ttf',72)gameOverSurf = gameOverFont.render('Game Over', True, greyColour)gameOverRect = gameOverSurf.get_rect()gameOverRect.midtop = (320, 10)playSurface.blit(gameOverSurf, gameOverRect)pygame.display.flip()time.sleep(5)pygame.quit()sys.exit()# 定义main函数def main():# 初始化pygamepygame.init()fpsClock = pygame.time.Clock()# 创建pygame显⽰层playSurface = pygame.display.set_mode((640,480))pygame.display.set_caption('Raspberry Snake')# 初始化变量snakePosition = [100,100]snakeSegments = [[100,100],[80,100],[60,100]]raspberryPosition = [300,300]raspberrySpawned = 1direction = 'right'changeDirection = directionwhile True:# 检测例如按键等pygame事件for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit()elif event.type == KEYDOWN:# 判断键盘事件if event.key == K_RIGHT or event.key == ord('d'):changeDirection = 'right'if event.key == K_LEFT or event.key == ord('a'):changeDirection = 'left'if event.key == K_UP or event.key == ord('w'):changeDirection = 'up'if event.key == K_DOWN or event.key == ord('s'):changeDirection = 'down'if event.key == K_ESCAPE:pygame.event.post(pygame.event.Event(QUIT))# 判断是否输⼊了反⽅向if changeDirection == 'right' and not direction == 'left':direction = changeDirectionif changeDirection == 'left' and not direction == 'right':direction = changeDirectionif changeDirection == 'up' and not direction == 'down':direction = changeDirectionif changeDirection == 'down' and not direction == 'up':direction = changeDirection# 根据⽅向移动蛇头的坐标if direction == 'right':snakePosition[0] += 20if direction == 'left':snakePosition[0] -= 20if direction == 'up':snakePosition[1] -= 20if direction == 'down':snakePosition[1] += 20# 增加蛇的长度snakeSegments.insert(0,list(snakePosition))# 判断是否吃掉了树莓if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:raspberrySpawned = 0else:snakeSegments.pop()# 如果吃掉树莓,则重新⽣成树莓if raspberrySpawned == 0:x = random.randrange(1,32)y = random.randrange(1,24)raspberryPosition = [int(x*20),int(y*20)]raspberrySpawned = 1# 绘制pygame显⽰层playSurface.fill(blackColour)for position in snakeSegments:pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20)) # 刷新pygame显⽰层pygame.display.flip()# 判断是否死亡if snakePosition[0] > 620 or snakePosition[0] < 0:gameOver(playSurface)if snakePosition[1] > 460 or snakePosition[1] < 0:for snakeBody in snakeSegments[1:]:if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:gameOver(playSurface)# 控制游戏速度fpsClock.tick(5)if __name__ == "__main__":main()操作⽅法:上下左右键或wsad键控制ESC键退出游戏下载代码:游戏代码来源于《Raspberry Pi ⽤户指南》,仅供参考。
Python贪吃蛇游戏编写代码
Python贪吃蛇游戏编写代码最近在学Python,想做点什么来练练⼿,命令⾏的贪吃蛇⼀般是C的练⼿项⽬,但是⼀时之间找不到别的,就先做个贪吃蛇来练练简单的语法。
由于Python监听键盘很⿇烦,没有C语⾔的kbhit(),所以这条贪吃蛇不会⾃⼰动,运⾏效果如下:要求:⽤#表⽰边框,⽤*表⽰⾷物,o表⽰蛇的⾝体,O表⽰蛇头,使⽤wsad来移动Python版本:3.6.1系统环境:Win10类: board:棋盘,也就是游戏区域 snake:贪吃蛇,通过记录⾝体每个点来记录蛇的状态 game:游戏类 本来还想要个food类的,但是food只需要⼀个坐标,和⼀个新建,所以⼲脆使⽤list来保存坐标,新建food放在game⾥⾯,从逻辑上也没有太⼤问题源码:# Write By Guobao# 2017/4//7## 贪吃蛇# ⽤#做边界,*做⾷物,o做⾝体和头部# python 3.6.1import copyimport randomimport osimport msvcrt# the board class, used to put everythingclass board:__points =[]def __init__(self):self.__points.clear()for i in range(22):line = []if i == 0 or i == 21:for j in range(22):line.append('#')else:line.append('#')for j in range(20):line.append(' ')line.append('#')self.__points.append(line)def getPoint(self, location):return self.__points[location[0]][location[1]]def clear(self):self.__points.clear()for i in range(22):line = []if i == 0 or i == 21:for j in range(22):line.append('#')else:line.append('#')for j in range(20):line.append(' ')line.append('#')self.__points.append(line)def put_snake(self, snake_locations):# clear the boardself.clear()# put the snake pointsfor x in snake_locations:self.__points[x[0]][x[1]] = 'o'# the headx = snake_locations[len(snake_locations) - 1]self.__points[x[0]][x[1]] = 'O'def put_food(self, food_location):self.__points[food_location[0]][food_location[1]] = '*' def show(self):os.system("cls")for i in range(22):for j in range(22):print(self.__points[i][j], end='')print()# the snake classclass snake:__points = []def __init__(self):for i in range(1, 6):self.__points.append([1, i])def getPoints(self):return self.__points# move to the next position# give the next headdef move(self, next_head):self.__points.pop(0)self.__points.append(next_head)# eat the food# give the next headdef eat(self, next_head):self.__points.append(next_head)# calc the next state# and return the directiondef next_head(self, direction='default'):# need to change the value, so copy ithead = copy.deepcopy(self.__points[len(self.__points) - 1])# calc the "default" directionif direction == 'default':neck = self.__points[len(self.__points) - 2]if neck[0] > head[0]:direction = 'up'elif neck[0] < head[0]:direction = 'down'elif neck[1] > head[1]:direction = 'left'elif neck[1] < head[1]:direction = 'right'if direction == 'up':head[0] = head[0] - 1elif direction == 'down':head[0] = head[0] + 1elif direction == 'left':head[1] = head[1] - 1elif direction == 'right':head[1] = head[1] + 1return head# the gameclass game:board = board()snake = snake()food = []count = 0def __init__(self):self.new_food()self.board.clear()self.board.put_snake(self.snake.getPoints())self.board.put_food(self.food)def new_food(self):while 1:line = random.randint(1, 20)column = random.randint(1, 20)if self.board.getPoint([column, line]) == ' ':self.food = [column, line]returndef show(self):self.board.clear()self.board.put_snake(self.snake.getPoints())self.board.put_food(self.food)self.board.show()def run(self):self.board.show()# the 'w a s d' are the directionsoperation_dict = {b'w': 'up', b'W': 'up', b's': 'down', b'S': 'down', b'a': 'left', b'A': 'left', b'd': 'right', b'D': 'right'} op = msvcrt.getch()while op != b'q':if op not in operation_dict:op = msvcrt.getch()else:new_head = self.snake.next_head(operation_dict[op])# get the foodif self.board.getPoint(new_head) == '*':self.snake.eat(new_head)self.count = self.count + 1if self.count >= 15:self.show()print("Good Job")breakelse:self.new_food()self.show()# 反向⼀Q⽇神仙elif new_head == self.snake.getPoints()[len(self.snake.getPoints()) - 2]:pass# rush the wallelif self.board.getPoint(new_head) == '#' or self.board.getPoint(new_head) == 'o':print('GG')break# normal moveelse:self.snake.move(new_head)self.show()op = msvcrt.getch()game().run()笔记: 1.Python 没有Switch case语句,可以利⽤dirt来实现 2.Python的=号是复制,复制引⽤,深复制需要使⽤copy的deepcopy()函数来实现 3.即使在成员函数内,也需要使⽤self来访问成员变量,这和C++、JAVA很不⼀样更多关于python游戏的精彩⽂章请点击查看以下专题:更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
贪吃蛇代码
贪吃蛇代码预处理#include#include#include#pragma comment(lib,"Winmm.lib")#define width_window 500 //窗口的宽度#define high_window 398 //窗口的高度#define width_gameBoard 398 //游戏区域的宽度#define high_gameBoard 398 //游戏区域的高度#define sw 10 //用一个圆表示蛇的一节,sw表示圆的半径#define num_food 16 //设定的食物个数,全部吃完则游戏胜利结束#define NameMaxLength 12 //设定用户名的最大字符数为:NameMaxLength-2#define PsdMaxLength 10 //设定密码的最大字符数#define boxbkclr 0xfedcbd //绘制消息框和登录框的主题填充颜色#define drawFieldbkclr 0xFFFFFF //窗口区域的背景填充颜色#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(); //画线分割窗口void GameOver(bool iskillde); //判断游戏是否结束void ClearTailNode(); //擦除蛇尾结点void Eat(int x,int y); //吃食物void SnakeMove(int x,int y,int d); //蛇按照玩家的控制命令进行移动void pause(); //游戏暂停void DrawMsgBox(); //绘制消息窗口int ResponseMouse(int,int,int,int,int,int,int,int,int,int,int,int);//响应鼠标void DrawTwoBtn(); //绘制启动画面上的两个按钮void DrawLoginUI(); //绘制登陆界面void InputName(); //输入账号void InputPsd(); //输入密码int ChkNamePsd(char*,char*); //点击登陆,核对用户名和密码//绘制按钮被点击时有被按压下去并回弹的动感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));int n=0; //初始化放置食物的个数为0int 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;//控件(按钮或输入框)的位置坐标char UserName[5]={'m','a','r','r','y'}; //系统设定的用户名char Password[6]={'t','o','m','1','2','3'}; //系统设定的密码//用于储存用户输入的账号char IptName[NameMaxLength]={'','','','','','','','\0'};//用于储存用户输入的密码char IptPsd[PsdMaxLength]={'','','','','','','','\0'};int isagin=0; //用于判断是否再玩一次,为1表示再玩一次系统主函数void main(){char str_again[]="再来一次"char str_exit[]="我不玩了"while(1){n=0;//每局开始需要初始化放置食物的个数为0InitGameBoard();//创建绘图窗口,并初始化InitSnake(sx,sy,sd);//用随机数的方式在某个位置产生蛇和蛇的移动方向SetFood();//随机地在蛇以外的位置放置食物SnakeMove(sx,sy,sd);//蛇按照玩家的指控命令进行移动DrawMsgBox();//绘制消息窗口isagain=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,x b03,yb03,0,0,0,0);//响应鼠标点击if(isagain==1)//点击了按钮1“再来一次”{BtnMoveClicked(xb00,yb00,xb01,yb01,6,6,str_again);//绘制动态按钮}if(isagain==2)//点击了按钮1“我不玩了”{BtnMoveClicked(xb02,yb02,xb03,yb03,6,6,str_exit);//绘制动态按钮break;}}closegraph();}1、播放背景音乐和添加启动画面void bkMusic_launchImg(){//播放背景音乐mciSendString("open./千年等一回.mp3 alias 千年等一回",0,0,0);mciSendString("play 千年等一回 repeat",0,0,0);//添加启动画面cleardevice();//用当前背景色清空屏幕,并将当前点移至(0,0)IMAGE img;loadimage(&img, _T("SnakesLaunch1.bmp"));//加载图像putimage(0,0,&img);//显示图像作为启动画面}2、划线分割窗口void window_segmented(){setlinecolor(BLUE);setlinestyle(PS_SOLID|PS_ENDCAP_FLAT,6);//设置线条宽度6的实线,平端点setfillcolor(YELLOW);//划线分割窗口line(width_gameBoard+1,0,width_gameBoard+1,high_game Board);line(width_gameBoard+1,200,width_window,200);//划线分割窗口setlinestyle(PS_SOLID|PS_ENDCAP_FLAT,1);//恢复线条样式为宽度1的实线}3、创建绘图窗口,并初始化void InitGameBoard(){int choice;//点击了哪个按钮int ret=-1;//用于表示核对用户名密码是否正确char str_guide[]="操作指南";char str_regist[]="登录游戏"initgraph(width_window,high_window);//创建大小为width_window*high_window的窗口setorigin(0,0);//设置绘图窗口区域的左上角为逻辑坐标原点setbkcolor(0xFFFFFF);//设置背景颜色,0xFFFFFF为白色bkMusic_launchImg();//播放背景音乐和添加启动画面if(isagain!=1)//是否是重新开始一局{DrawTwoBtn();//绘制启动画面上的两个按钮choice=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,xb 03,yb03,0,0,0,0);if(choice==1)//点击了“操作指南”{BtnMoveClicked(xb00,yb00,xb01,yb01,6,6,str_guide);//绘制动感按钮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);if(choice==0)//点击了鼠标左键{//设置绘图样式setlinecolor(WHITE); //设置线条颜色为白色setlinestyle(PS_SOLID|PS_ENDCAP_FLAT,1); //设置线条样式setfillcolor(YELLOW);}}else//点击了“登录游戏”{BtnMoveClicked(xb02,yb02,xb03,yb03,6,6,str_regist);Sleep(200);}DrawLoginUI();//绘制登陆界面window_segmented();//划线分割窗口while(1){if(ret==0)//判断是否已经发生过输入用户名或密码错误{//设置字体颜色为框体填充颜色,目的是擦掉提示错误的信息setcolor(boxbkclr);//设置输入文本的背景颜色为框体填充颜色,目的是擦掉提示错误的信息setbkcolor(boxbkclr);setbkmode(TRANSPARENT);//设置文字输出时的背景模式为透明色settexstyle(18,0,_T("宋体"));//用框体填充颜色输出错误信息,即擦除outtextxy(xb00-50,yb00-20,"账号或密码输入错误,请重新输入!");setbkcolor(drawFieldbkclr);choice=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,xb 03,yb03,xb04,yb04,xb05,yb05);}choice=ResponseMouse(xb00,yb00,xb01,yb01,xb02,yb02,xb 03,yb03,xb04,yb04,xb05,yb05);if(choice==1){InputName();//输入账号}if(choice==2){InputPsd();//输入密码}if(choice==3){ret=ChkNamePsd(IptName,IptPsd);//点击登录if(ret==1)break;}}}cleardevice();//用当前背景色清空屏幕,并将当前点移至(0,0)window_segmented();//划线分割窗口dispInfo();//显示得分和操作指南信息}4、显示得分、操作指南和版本等信息void dispInfo(){//显示得分情况setcolor(BLACK);//设置字体颜色settextstyle(18,0,_T("黑体"));//设置字体类型outtextxy(width_gameBoard+10,30,"当前得分:"); settextstyle(38,0,_T("黑体"));//设置字体类型outtextxy(width_gameBoard+10,60,"0");//显示操作指南信息settextstyle(18,0,_T("黑体"));//设置字体类型outtextxy(width_gameBoard+10,220,"操作指南"); settextstyle(12,0,_T("宋体"));//设置字体类型outtextxy(width_gameBoard+10,250,"按F或f键向东转");outtextxy(width_gameBoard+10,265,"按S或s键向西转"); outtextxy(width_gameBoard+10,280,"按D或d键向南转"); outtextxy(width_gameBoard+10,295,"按E或e键向北转"); outtextxy(width_gameBoard+10,320,"按A或a键向东转"); outtextxy(width_gameBoard+10,335,"按空格键暂停"); outtextxy(width_gameBoard+10,350,"按ESC键退出");//显示版本信息outtextxy(width_gameBoard+10,380,"**贪吃蛇V1.0.0"); }5、动态显示得分void dispScore(){char str_score[6];int num_score=0;num_score=(n-1)*10;//每吃一个得10分itoa(num_score,str_score,10);//数字转化为字符setcolor(RED);setbkmode(OPAQUE);settextstyle(38,0,_T("黑体"));outtextxy(width_gameBoard+10,60,str_score);//显示得分}6、用随机数的方式在某个位置产生蛇和蛇的移动方向void InitSnake(int x0,int y0,int d0){int x,y,d;//蛇的初始位置(x,y)和蛇的移动方向d//用伪随机数产生蛇的初始位置(x,y)和物体的移动方向d//注意:(x,y)不要太靠近四个边,否则可能会出现游戏刚开始就结束了的情况。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
/********************************************************/
char kz(void)
{
char a;
if(kbhit())
{
a=getch();//获取一个按键信息
if(a==-32)//输入上下左右后会返回-32,需要再次获取才能返回正确的值
{
int i,j;
for(i=0;i<snack1.sum;i++)
{
//kk[snack1.x[i]][snack1.y[i]]=2;//把蛇的坐标置于地图数组kk中并初始化为2
gotoxy(hOut,snack1.x[i],snack1.y[i]);
putchar('@');
snack1.y[0]=12; //初始化蛇的位置
snack1.x[1]=25; //
snack1.y[1]=12; //
snack1.x[2]=24; //
snack1.y[2]=12; //
int yidong,i;
kuangjia();
#include<stdio.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
void gotoxy(HANDLE hOut,int x,int y)//移动光标函数,,看不懂
{
COORD pos;
pos.X=x;
gotoxy(hOut,53,6);
puts("按字母A开始游戏");
gotoxy(hOut,53,9);
puts("按上下左右控制移动!");
gotoxy(hOut,63,12);
printf("第%d关!",dengji);
}
void move(void)//把蛇置于地图中
}
snack1.x[0]=snack1.x[0]-1;//改变蛇头的坐标
biaoji='l';
}return 0;
break;
case 'r':
if(biaoji!='l')
{
for(i=snack1.sum-1;i>0;i--)//改变蛇身的坐标
panduan();
yidong=anjian();
switch(yidong)
{
case 'u':for(i=snack1.sum-1;i>0;i--)//除了蛇头,其余部分向蛇身的前一格移动
{
snack1.x[i]=snack1.x[i-1];
{
case 'u':
if(biaoji!='d')
{
for(i=snack1.sum-1;i>0;i--)//除了蛇头,其余部分向蛇身的前一格移动
{
snack1.x[i]=snack1.x[i-1];
snack1.y[i]=snack1.y[i-1];
{
gotoxy(hOut,23,12);
printf("Game Over");
a=getch();
}
}
void kuangjia(void)
{
int i,j;
for(i=0;i<25;i++)
{
kk[0][i]=1;//把地图左边界初始化为1
{
snack1.x[i]=snack1.x[i-1];
snack1.y[i]=snack1.y[i-1];
}
snack1.y[0]=snack1.y[0]+1;//改变蛇头的坐标
biaoji='d';
}return 0;
break;
case 'l':
if(biaoji!='r')
{
for(i=snack1.sum-1;i>0;i--)//改变蛇身的坐标
{
snack1.x[i]=snack1.x[i-1];
snack1.y[i]=snack1.y[i-1];
snack1.y[i]=snack1.y[i-1];
}
snack1.x[0]=snack1.x[0]+1;;break;
}
Sleep(200);
system("cls");
}
}
{
snack1.x[i]=snack1.x[i-1];
snack1.y[i]=snack1.y[i-1];
}
snack1.x[0]=snack1.x[0]+1;//改变蛇头的坐标
biaoji='r';
}return 0;
snack1.y[i]=snack1.y[i-1];
}
snack1.x[0]=snack1.x[0]-1;;break;
case 'r':for(i=snack1.sum-1;i>0;i--)//改变蛇身的坐标
{
snack1.x[i]=snack1.x[i-1];
}
return biaoji;
}
void food(void)
{
int i;
x=rand()%47+2;
y=rand()%22+2;
}
void main(void)
{
srand(time(0));
system("title 贪吃蛇");
snack1.x[0]=26; //
gotoxy(hOut,50,25);
}
}
char anjian(void)
{
char kz(void);
static char biaoji;
char a;
int i;
a://获取一个按键信息
//输入上下左右后会返回-32,需要再次获取才能返回正确的值
switch(kz())//根据按键改变坐标
struct snack snack1={{0},{0},3};//定义一条蛇,并把蛇初始化
int dengji=1;//关卡,等级
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);//看不懂
char kk[50][25]={0};//定义地图的大小,并初始化为0
snack1.y[i]=snack1.y[i-1];
}
snack1.y[0]=snack1.y[0]+1;;break;
case 'l':for(i=snack1.sum-1;i>0;i--)//改变蛇身的坐标
{
snack1.x[i]=snack1.x[i-1];
pos.Y=y;
SetConsoleCursorPosition(hOut,pos);
}
struct snack //
{
int x[50]; //蛇的坐标
int y[50]; //
int sum; //蛇的长度
};
/*****************全局变量*******************************/
switch(getch())//根据按键改变坐标
{
case 80:return 'பைடு நூலகம்';
case 72:return 'u';
case 77:return 'r';
case 75:return 'l';
}
}
}
void panduan(void)
food();
while(1)
{
gotoxy(hOut,x,y);
putchar(3);
if(snack1.x[0]==x&&snack1.y[0]==y)
{
snack1.sum+=1;
food();
}
kuangjia();
move();
kk[49][i]=1;//右边界初始化为1
}
for(i=0;i<50;i++)
{
kk[i][0]=1;//上边界初始化为1
kk[i][24]=1;//下边界初始化为1
}
for(i=0;i<50;i++) //
for(j=0;j<25;j++) //寻找所有的地图
{
if(kk[i][j]==1)//把坐标对应为1的找出,也就是找出边界的坐标
{
gotoxy(hOut,i+1,j+1);//把光标移动到该位置
putchar(4);//输出边界符号
}
}
gotoxy(hOut,63,3);
puts("贪吃蛇");
snack1.y[i]=snack1.y[i-1];
}
snack1.y[0]=snack1.y[0]-1;;break;