前言
本系列是根据《游戏课程设计》李老师讲授的过程写成,基本上为课堂上所涉及到的代码
前几周做了贪吃蛇游戏,可惜没有记录下来,这次就完整的记录一下学习的过程
功能实现
- 游戏框架确定
- 游戏窗口显示
- 鼠标事件响应
确定游戏主要框架
我们使用c++的类来实现对游戏中各种数据的操作
新建一个sfml项目,并新建Game类,项目目录如下所示
在Game.h
中确定游戏基本数据与框架
#pragma once
#include <SFML/Graphics.hpp>
#include <windows.h>
#include <iostream>
class Game {
public:
sf::RenderWindow window; //定义游戏窗口
Game();
~Game();
bool gameOver, gameQuit; //游戏结束 游戏退出
int windowWidth, windowHeight, stageWidth, stageHeight; //窗口大小 游戏舞台大小
sf::Clock mouseClickTimer; //鼠标双击计时器
void Initial(); //初始化函数
void Input(); //键盘,鼠标输入函数
void Logic(); //逻辑判断
void Draw(); //界面绘制函数
void Run(); //游戏运行
};
在Game.cpp
中写具体操作
#include "Game.h"
Game::Game() {
windowWidth = 860; //根据游戏美术素材设定宽高度
windowHeight = 600;
window.create(sf::VideoMode(windowWidth, windowHeight), "mineClearance by legroft");//建立游戏窗口
}
Game::~Game() {
}
void Game::Initial() {
window.setFramerateLimit(60); //设置游戏帧数
gameOver = gameQuit = false;
}
void Game::Input() {
sf::Event event; //定义事件
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close(); //点击窗口关闭按钮关闭窗口
gameQuit = true;
}
if (event.type == sf::Event::EventType::KeyReleased && event.key.code == sf::Keyboard::Escape) {
window.close(); //按esc键关闭窗口
gameQuit = true;
}
if (event.type == sf::Event::EventType::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) {
if (mouseClickTimer.getElapsedTime().asMilliseconds() > 500) {
std::cout << "mouse left press" << std::endl;
} else {
std::cout << "mouse left double click" << std::endl;
}
}
if (event.type == sf::Event::EventType::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left) {
mouseClickTimer.restart();
std::cout << "mouse left release" << std::endl;
}
if (event.type == sf::Event::EventType::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Right) {
std::cout << "mouse right press" << std::endl;
}
if (event.type == sf::Event::EventType::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Right) {
std::cout << "mouse right release" << std::endl;
}
}
}
void Game::Logic() {
}
void Game::Draw() {
}
void Game::Run() {
do {
Initial();
while (window.isOpen() && !gameOver) {
Input();
Draw();
Logic();
}
}
while (!gameQuit);
}
在mineClearance.cpp
中
#include<iostream>
#include "Game.h"
int main() {
Game mineClearance;
while (mineClearance.window.isOpen()) {
mineClearance.Run();
}
return 0;
}
运行测试
运行一下看看效果
可以看到游戏窗口可以相应对应的鼠标事件,也可以被正常关闭