本程序是一款简易的贪吃蛇程序具有WIN32和JavaScript两个版本,其中WIN3程序写于2010年,麻雀虽小五脏俱全,回头突然发现还是非常佩服五年多之前的自己的。jQuery程序写于2015年。
GitHub下载地址:https://github.com/hujiulin/snake
jQuery演示地址:http://www.coinidea.com/game/snake/
程序整体界面如下:
WIN32版本:
jQuery版本:
WIN32框架代码:
</p> <h1>include <windows.h></h1> <h1>include <math.h></h1> <h1>include <stdlib.h></h1> <h1>include <time.h></h1> <h1>include <string.h></h1> <p>LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);</p> <p>int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { WNDCLASS wndclass; char strClassName[] = "hungry snake"; char strWindowName[] = "贪吃蛇"; HWND hwnd; MSG msg;</p> <pre><code>wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.hCursor = LoadCursor(hInstance,IDC_ARROW); wndclass.hIcon = LoadIcon(hInstance,IDI_APPLICATION); wndclass.hInstance = hInstance; wndclass.lpfnWndProc = WndProc; wndclass.lpszClassName = strClassName; wndclass.lpszMenuName = NULL; wndclass.style = 0; if(!RegisterClass(&amp;wndclass)) { MessageBeep(0); return FALSE; } hwnd = CreateWindow(strClassName, strWindowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hwnd,nCmdShow); UpdateWindow(hwnd); while(GetMessage(&amp;msg,NULL,0,0)) { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } return msg.wParam; </code></pre> <p>}</p> <p>LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; HBRUSH hBrush; HPEN hPen; switch(msg) { case WM_LBUTTONDOWN: InvalidateRect(hwnd,NULL,1); break; case WM_RBUTTONDOWN: InvalidateRect(hwnd,NULL,1); break; case WM_CHAR: InvalidateRect(hwnd,NULL,1); break; case WM_PAINT: InvalidateRect(hwnd,NULL,1); break; case WM_DESTROY: PostQuitMessage(0); default: return DefWindowProc(hwnd,msg,wParam,lParam); } return 0; }</p> <p>
贪吃蛇定义
整个蛇为一个List,然后头部squarehead、定义direction具有四个方向、speed速度、当前蛇的长度List.size();
碰撞检测
1.当贪吃蛇的头部 在 direction方向上 碰到 随机生成的一个square时,即表示吃到事物;
- 当贪吃蛇回头碰到自己身体,或者 碰到边界时,游戏结束。