这次是关于game类的实现:
#pragma once
#ifndef GAME_H
#define GAME_H
#include "Array.h"
#include <iostream>
using namespace std;
class Game : public Array {
private:
Array ar;/*矩阵成员变量*/
public:
Game() { };
~Game() {};
virtual void TestShowArray() {/*重载矩阵输出函数*/
ar.TestShowArray();
}
void StartGame();
void Start();/*绘制入口界面*/
void GameWindows();/*绘制游戏窗口*/
void OnGameTime();/*接收游戏玩家的操作,进行游戏*/
};
#endif //GAME_H
以及对应的.cpp文件:
#include "pch.h"
#include "Game.h"
#include "graphics.h"
#include <conio.h>
#include <stdio.h>
void Game::StartGame()
{
TestShowArray();
}
void Game::Start()
{
initgraph(880, 640);
setbkcolor(WHITE); // 白色背景
cleardevice(); // 初始化背景
/*
setlinestyle(4094, 10); // 改笔的颜色、状态
setlinecolor(RGB(0, 100, 0));
line(0, 0, 0, 640);
line(0, 0, 880, 0);
line(880, 0, 880, 640);
line(0, 640, 880, 640);
*/
settextcolor(RED); // 改字体
setbkmode(TRANSPARENT);
settextstyle(60, 0, _T("宋体"));
outtextxy(50, 40, _T("自制2048小游戏"));
settextstyle(32, 0, _T("宋体"));
outtextxy(75, 95, _T("2019/4/20"));
settextcolor(BLUE); // 改字体
outtextxy(50, 130, _T("W上移 S下移 A左移 D右移"));
settextcolor(BLACK); //改字体
settextstyle(32, 0, _T("宋体"));
outtextxy(384, 500, _T("按任意键开始游戏"));
_getch();
}
int relx = 50, rely = 50, rerx = 450, rery = 450;
void Game::GameWindows()/*2048游戏界面*/
{
clearcliprgn();//清除屏幕
settextcolor(BLACK); //改字体
settextstyle(30, 0, _T("宋体"));
outtextxy(150,10, _T(" 2048 "));
TCHAR ss[10];
swprintf_s(ss, _T("当前得分:%d"), GetMark());
settextcolor(RED); // 改字体
outtextxy(600, 160, ss);
setlinestyle(4096, 10); // 改笔的颜色、状态
setlinecolor(RGB(0, 100, 0));
line(relx, rely, relx, rery); // 左竖1
line(relx + 100, rely, relx + 100, rery); // 左竖2
line(relx + 200, rely, relx + 200, rery); // 左竖3
line(relx + 300, rely, relx + 300, rery); // 左竖4
line(relx, rely, rerx, rely); // 上横1
line(relx, rely + 100, rerx, rely + 100); // 上横2
line(relx, rely + 200, rerx, rely + 200); // 上横3
line(relx, rely + 300, rerx, rely + 300); // 上横4
line(relx, rery, rerx, rery); // 下横
line(rerx, rery, rerx, rely); // 右竖
TCHAR str[40];
int a = 10;
int i, j;
setlinecolor(LIGHTBLUE); // 改笔颜色 状态
setlinestyle(PS_SOLID | PS_JOIN_BEVEL, 4);
// setlinestyle(PS_NULL); // 恢复笔
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (GetArray(i, j))//如果值不为0,则打印出来
{
swprintf_s(str, _T("%d"), GetArray(i, j));
settextcolor(BLUE); // 改字体
outtextxy(65 + i * 100, 80 + j * 100, str);
}
}
}
}
void Game::OnGameTime()
{
int i = 0;
char c = ' ';
SetNewPoint();
while (i<1000)
{
Sleep(400);/*设置暂停时间0.4秒,稀释掉函数跳转时长不定的影响*/
GameWindows();
c = _getch();
if(MoveToside(c) && (c == 'W' || c == 'w' ||
c == 'S' || c == 's' ||
c == 'A' || c == 'a' ||
c == 'D' || c == 'd'))
SetNewPoint();
/*
if(!IfFullArray())
SetNewPoint();
else
{
char sss[20];
outtextxy(600, 240, _T("游戏结束,按任意键退出!"));
_getch();
break;
}
*/
i++;
}
closegraph();
}
最后加上主源文件就可以了:
// 2048.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include "Game.h"
#include <iostream>
using namespace std;
int main()
{
Game newgame;/*创建新游戏*/
newgame.Start();
newgame.OnGameTime();
return 0;
}