本文主要是介绍Let's make 16 games in C++(七):Fifteen_Puzzle,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、准备游戏需要的背景
2、游戏源码
#include<SFML/Graphics.hpp>
#include<time.h>using namespace sf;int main()
{RenderWindow app(VideoMode(256, 256), "15-Puzzle!");app.setFramerateLimit(60);Texture t;t.loadFromFile("./Resources/images/15.png");int w = 64;int grid[6][6] = { 0 };Sprite sprite[20];int n = 0;for (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){n++;sprite[n].setTexture(t);sprite[n].setTextureRect(IntRect(i*w, j*w, w, w));grid[i + 1][j + 1] = n;}}while (app.isOpen()){Event e;while (app.pollEvent(e)){if (e.type == Event::Closed){app.close();}if (e.type == Event::MouseButtonPressed){if (e.key.code == Mouse::Left){Vector2i pos = Mouse::getPosition(app);int x = pos.x / w + 1;int y = pos.y / w + 1;int dx = 0;int dy = 0;if (grid[x+1][y] == 16){dx = 1;dy = 0;}if (grid[x][y+1] == 16){dx = 0;dy = 1;}if (grid[x][y-1] == 16){dx = 0;dy = -1;}if (grid[x-1][y] == 16){dx = -1;dy = 0;}int n = grid[x][y];grid[x][y] = 16;grid[x + dx][y + dy] = n;//animationsprite[16].move(-dx * w, -dy * w);float speed = 3;for (int i = 0; i < w; i+=speed){sprite[n].move(speed*dx, speed*dy);app.draw(sprite[16]);app.draw(sprite[n]);app.display();}}}}app.clear();for (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){int n = grid[i + 1][j + 1];sprite[n].setPosition(i*w, j*w);app.draw(sprite[n]);}}app.display();}return 0;
}
结果图:
这篇关于Let's make 16 games in C++(七):Fifteen_Puzzle的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!