WIN32和jQuery贪吃蛇的开源实现

本程序是一款简易的贪吃蛇程序具有WIN32和JavaScript两个版本,其中WIN32程序写于2010年,麻雀虽小五脏俱全,回头突然发现还是非常佩服五年多之前的自己的。jQuery程序写于2015年。

GitHub下载地址:https://github.com/hujiulin/snake

jQuery演示地址:http://www.coinidea.com/game/snake/

程序整体界面如下:

WIN32版本:

1442639966167035.gif

jQuery版本:

jQuery贪吃蛇

WIN32框架代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <windows.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) {
    WNDCLASS wndclass;
    char strClassName[] = "hungry snake";
    char strWindowName[] = "贪吃蛇";
    HWND hwnd;
    MSG msg;

    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(&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(&msg,NULL,0,0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) {
    HDC hdc;
    PAINTSTRUCT ps;
    HBRUSH hBrush;
    HPEN hPen;
    switch(msg) {
        case WM_LBUTTONDOWN:
        case WM_RBUTTONDOWN:
        case WM_CHAR:
        case WM_PAINT:
            InvalidateRect(hwnd,NULL,1);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hwnd,msg,wParam,lParam);
    }
    return 0;
}

贪吃蛇定义

整个蛇为一个List,然后头部squarehead、定义direction具有四个方向、speed速度、当前蛇的长度List.size()

碰撞检测

  1. 当贪吃蛇的头部在direction方向上碰到随机生成的一个square时,即表示吃到食物;
  2. 当贪吃蛇回头碰到自己身体,或者碰到边界时,游戏结束。