⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 这个一个经典的小游戏
💻 CPP
字号:
#include "Snake.h"
#include <windows.h>

#define ID_TIMER	1
#define	SPEED		750

Snake SK;
int dir;

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	
VOID	CALLBACK TimerProc(HWND, UINT, UINT_PTR, DWORD);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
				   LPSTR szCmdLine, int nCmdShow)
{
	static char szAppName[] = "Snake";
	HWND		hWnd;
	MSG			msg;
	WNDCLASS	wndClass;
	
	wndClass.cbClsExtra		= 0;
	wndClass.cbWndExtra		= 0;
	wndClass.hbrBackground	= (HBRUSH)GetStockObject(WHITE_BRUSH);
	wndClass.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wndClass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	wndClass.hInstance		= hInstance;
	wndClass.lpfnWndProc	= WndProc;
	wndClass.lpszClassName	= szAppName;
	wndClass.lpszMenuName	= NULL;
	wndClass.style			= CS_HREDRAW | CS_VREDRAW;
	
	if (!RegisterClass(&wndClass))
	{
		MessageBox(NULL, "Win2K required for this program!", szAppName, MB_ICONERROR);
		return 1;
	}
	
	hWnd = CreateWindow(szAppName, szAppName, 
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT,
		640 + GetSystemMetrics(SM_CXFRAME) * 2,
		480 + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYFRAME) * 2,
		NULL,
		NULL,
		hInstance,
		NULL);
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	dir = (rand() % 4) * 100;
	SK.SetDirection(dir);
	SK.SetHWND(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)
{
	switch(Msg)
	{
		case WM_CREATE:
			SetTimer(hWnd, ID_TIMER, SPEED, (TIMERPROC)TimerProc);
			return 0;
		case WM_KEYDOWN:
			switch (wParam)
			{
				case VK_UP:
					SK.SetDirection(DIR_UP);
					break;
				case VK_RIGHT:
					SK.SetDirection(DIR_RIGHT);
					break;
				case VK_DOWN:
					SK.SetDirection(DIR_DOWN);
					break;
				case VK_LEFT:
					SK.SetDirection(DIR_LEFT);
					break;
			}
			SK.SnakeMove();
			if (SK.IsSnakeDead())
			{
				KillTimer(hWnd, ID_TIMER);
				MessageBox(hWnd, "You lost!", "Snake", MB_ICONERROR);
				exit(1);
			}
			if (!SK.IsFoodExist())
			{
				SK.FoodInit();
			}
			SK.SnakeDraw();
			return 0;
		case WM_DESTROY:
			KillTimer(hWnd, ID_TIMER);
			PostQuitMessage(0);
			return 0;
		default: break;
	}

	return DefWindowProc(hWnd, Msg, wParam, lParam);
}

VOID	CALLBACK TimerProc(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	SK.SnakeMove();
	if (SK.IsSnakeDead())
	{
		KillTimer(hWnd, ID_TIMER);
		MessageBox(hWnd, "You lost!", "Snake", MB_ICONERROR);
		exit(1);
	}
	if (!SK.IsFoodExist())
	{
		SK.FoodInit();
	}
	SK.SnakeDraw();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -