Open-Source Snake Game in WIN32 and jQuery

This is a simple snake game available in both WIN32 and JavaScript versions. The WIN32 version was written in 2010 – small but complete. Looking back, I’m quite impressed with myself from over five years ago. The jQuery version was written in 2015.

GitHub download link: https://github.com/hujiulin/snake

jQuery demo: http://www.coinidea.com/game/snake/

The overall interface looks like this:

WIN32 Version:

1442639966167035.gif

jQuery Version:

jQuery贪吃蛇

WIN32 Framework Code:

 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;
}

Snake Definition

The entire snake is a List, with a head squarehead, a direction with four possible values, a speed, and the current snake length List.size().

Collision Detection

  1. When the snake’s head encounters a randomly generated square in the current direction, it means food has been eaten.
  2. When the snake turns back and hits its own body, or hits the boundary, the game is over.