用c++写双人对战小游戏
时间: 2023-07-19 11:47:59 浏览: 62
好的,这里是一个简单的双人对战小游戏的 C++ 代码示例,使用了 SFML 游戏引擎:
```c++
#include <SFML/Graphics.hpp>
int main()
{
// 创建游戏窗口
sf::RenderWindow window(sf::VideoMode(800, 600), "双人对战小游戏");
// 创建两个玩家的精灵
sf::RectangleShape player1(sf::Vector2f(50, 50));
player1.setFillColor(sf::Color::Red);
player1.setPosition(50, 50);
sf::RectangleShape player2(sf::Vector2f(50, 50));
player2.setFillColor(sf::Color::Blue);
player2.setPosition(700, 500);
// 游戏循环
while (window.isOpen())
{
// 处理事件
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
// 玩家1控制
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
player1.move(-5, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
player1.move(5, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
player1.move(0, -5);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
player1.move(0, 5);
}
// 玩家2控制
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
player2.move(-5, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
player2.move(5, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
player2.move(0, -5);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
player2.move(0, 5);
}
// 渲染画面
window.clear();
window.draw(player1);
window.draw(player2);
window.display();
}
return 0;
}
```
此示例中,我们创建了一个窗口和两个玩家精灵,然后在游戏循环中处理玩家控制和渲染画面。您可以根据自己的需求对代码进行修改和扩展,添加更多的游戏元素和功能,以实现更丰富的游戏体验。