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

📄 snakedlg.cpp

📁 运用VC++编写的
💻 CPP
字号:
// SnakeDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Snake.h"
#include "SnakeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSnakeDlg dialog

CSnakeDlg::CSnakeDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSnakeDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSnakeDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_time = TIME;
}

void CSnakeDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSnakeDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSnakeDlg, CDialog)
	//{{AFX_MSG_MAP(CSnakeDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CTLCOLOR()
	ON_WM_TIMER()
	ON_WM_KEYDOWN()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSnakeDlg message handlers

BOOL CSnakeDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here

	MakeMap();      //制作方格地图
	InitGame();     //初始化游戏
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSnakeDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CSnakeDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSnakeDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

HBRUSH CSnakeDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
	HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
	
	// TODO: Change any attributes of the DC here
    hbr=(HBRUSH)GetStockObject(BLACK_BRUSH); //将前景设为黑色	
	// TODO: Return a different brush if the default is not desired
	return hbr;
}
void CSnakeDlg::MakeMap()
{
	 //设置窗口大小
	int cxWnd=GetSystemMetrics(SM_CXFRAME)*2+MAX_X*PANE_LEN-GetSystemMetrics(SM_CXEDGE);
	int cyWnd=GetSystemMetrics(SM_CYCAPTION)+GetSystemMetrics(SM_CYFRAME)*2
		+MAX_Y*PANE_LEN-GetSystemMetrics(SM_CYEDGE);	
	SetWindowPos(NULL,0,0,cxWnd,cyWnd,SWP_NOZORDER|SWP_NOMOVE);   

	m_img.LoadBitmap(IDB_PANE);        //加载位图 

	for(int i=0;i<MAX_X;i++)
	{
		for(int j=0;j<MAX_Y;j++)			
		{
			m_map[i][j].Create("",WS_CHILD|SS_BITMAP|WS_DISABLED ,      //创建方块实例
				CRect(PANE_LEN*i,PANE_LEN*j,PANE_LEN*(i+1),PANE_LEN*(j+1)),this);
			m_map[i][j].SetBitmap((HBITMAP)m_img);   //放置位图
			m_map[i][j].SetPoint(i,j);   //为每个方块设置坐标,坐标与数组下标相同
		}
	}
}

void CSnakeDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	
	m_snake.KeepMoving();     //保持原方向移动一步
	
	if(!m_snake.IsTouch(MAX_X,MAX_Y))
	{
		//撞墙处理
		KillTimer(1);  
		MessageBox("留得青山在,哪怕没材烧!");
		InitGame();
	}
	else
	{
		//不撞墙处理
		//吃到食物处理
		if(m_snake.IsEat(m_food))  
		{
			//蛇变长
			m_snake.Grow();   
			//放置新食物
			m_food=SetFood();
		}
		//显示蛇
		ShowSnake();
	}

	//如果达到最大长度,即过关
	if(m_snake.GetBodyLen()==MAX_SNAKE_LEN)
	{
		KillTimer(1);
		m_time=m_time-30;  //下一关,时间间隔减少30MS
		//结局
		if(m_time<=0)
		{
			MessageBox("我对你的敬仰之情有如滔滔江水连绵不绝,黄河泛滥一发不可收拾!---THE END");
			return;
		}

		//挑战下一关
		MessageBox("向下一级挑战!");
		InitGame();
	}

}

void CSnakeDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	// TODO: Add your message handler code here and/or call default
	//游戏的控制
	
	switch(nChar)
	{
	case 'W':
	case VK_UP:
		m_snake.MoveUp();   
		break;
	case 'S':
	case VK_DOWN:
		m_snake.MoveDown();
		break;
	case 'A':
	case VK_LEFT:
		m_snake.MoveLeft();
		break;
	case 'D':
	case VK_RIGHT:
		m_snake.MoveRight();
		break;
	case VK_ESCAPE:
		EndDialog(1);   //退出程序
		break;
	default:;
	}
	CDialog::OnKeyDown(nChar, nRepCnt, nFlags);
}

void CSnakeDlg::ShowSnake()
{
	//蛇身包含着坐标,把坐标对应的方块显示出来即可
	
	int len=m_snake.GetBodyLen();
	for(int i=0;i<len;i++)
	{
		m_map[m_snake.m_body[i].x][m_snake.m_body[i].y].ShowWindow(SW_SHOW);
	}
	//隐藏上一步的尾巴
	m_map[m_snake.m_preEnd.x][m_snake.m_preEnd.y].ShowWindow(SW_HIDE);
}

void CSnakeDlg::BreakGame()
{
	if(m_isRun) 
	{
		KillTimer(1);
		m_isRun=false;
	}
	else
	{
		SetTimer(1,m_time,NULL);
		m_isRun=true;
	}
}

void CSnakeDlg::InitGame()
{
	m_isRun=false;
	
	//全部方块隐藏
	for(int i=0;i<MAX_X;i++)
	{
		for(int j=0;j<MAX_Y;j++)			
		{
            m_map[i][j].ShowWindow(SW_HIDE);
		}
	}
    //初始化蛇
    m_snake.InitSnake(MAX_X,MAX_Y);
	//显示蛇
	ShowSnake();
	//放置食物
	m_food=SetFood();	  
}


CPoint CSnakeDlg::SetFood()
{
	int x=0;
	int y=0;
	CPoint food;
	bool flag=true;
	//随机产生,合适的坐标
	while(flag)
	{
		srand(time(NULL));
		x=rand()%MAX_X;
		y=rand()%MAX_Y;
		food.x=x;
		food.y=y;
		for(int i=0;i<m_snake.GetBodyLen();i++)
		{
			if(food!=m_snake.m_body[i])  //坐标不能与蛇身重合
				flag=false;
		}
	}
	//把该坐标对应的方块显示,作为食物
	m_map[x][y].ShowWindow(SW_SHOW);
    return food;
}

BOOL CSnakeDlg::PreTranslateMessage(MSG *lpmsg)
{
	//对话框默认屏蔽了方向键的消息响应,在这里要处理一下
    switch (lpmsg->message)
    {
    case WM_KEYDOWN:
        switch (lpmsg->wParam)
        {
        case VK_UP:
        case VK_DOWN:
        case VK_LEFT:
        case VK_RIGHT:
			OnKeyDown(lpmsg->wParam, LOWORD(lpmsg ->lParam), HIWORD(lpmsg->lParam));
			break;
		default:;
        } 
	default:;
    } 
    return CDialog::PreTranslateMessage(lpmsg);
}

void CSnakeDlg::OnOK()   //回车键消息响应
{	
	BreakGame();    // 暂停||开始 游戏
//	CDialog::OnOK();      
}

⌨️ 快捷键说明

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