美好的一天,我正在尝试使用 SFML 从头开始创建一个国际象棋游戏,但我遇到的问题是我最终得到了下面所附的图片,而不是一个接一个的国际象棋。现在我并不担心游戏的功能或用户命令,我想要的只是运行我的代码并看到正常的棋盘。
这是我的代码输出:
这是我的main.cpp
#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;
int size = 56;
Sprite f[32];
int board[8][8] =
{ -1,-2,-3,-4,-5,-3,-2,-1,
-6,-6,-6,-6,-6,-6,-6,-6,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
6, 6, 6, 6, 6, 6, 6, 6,
1, 2, 3, 4, 5, 3, 2, 1 };
void loadPosition() {
int num = 0 ;
for(int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) {
int n = board[i][j];
if (!n)continue;
int x = abs(n) - 1;
int y = n > 0 ? 1 : 0;
f[num].setTextureRect(IntRect(size * x, size * y, size, size));
f[num].setPosition(size * j, size * i);
num++;
}
}
int main()
{
RenderWindow game(VideoMode(453, 453), "Suhaib-Chess");
Texture t1,t2;
t1.loadFromFile("img/pieces.png");
t2.loadFromFile("img/board0.png");
Sprite s;
Sprite sBoard(t2);
s.setTexture(t1);
for (int i = 0; i < 32; i++)f[i].setTexture(t1);
loadPosition;
bool isMove = false;
float dx = 0;
float dy = 0;
while (game.isOpen()) {
Vector2i position = Mouse::getPosition(game);
Event e;
while (game.pollEvent(e)) {
if (e.type == Event::Closed)
game.close();
if(e.type == Event::MouseButtonPressed)
if(e.key.code == Mouse::Left)
if (s.getGlobalBounds().contains(position.x, position.y)) {
isMove = true;
dx = position.x - s.getPosition().x;
dy = position.y - s.getPosition().y;
}
if (e.type == Event::MouseButtonReleased)
if (e.key.code == Mouse::Left)
isMove = false;
}
if (isMove == true) s.setPosition(position.x - dx, position.y - dy);
game.clear();
game.draw(sBoard);
for (int i = 0; i < 32; i++)game.draw(f[i]);
game.display();
}
return 0;
}
我尝试使用的图片:
最佳答案
board
数组初始化似乎错误。用这样的东西再试一次:
int board[8][8] = {
{ -1,-2,-3,-4,-5,-3,-2,-1 },
{ -6,-6,-6,-6,-6,-6,-6,-6 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 6, 6, 6, 6, 6, 6, 6, 6 },
{ 1, 2, 3, 4, 5, 3, 2, 1 }
};
说明:显然,您试图声明一个二维数组,但您使用一个包含 64 个项目的巨大数组而不是一个包含 8 个项目的 8 个数组的数组来初始化它。它稍后会在 loadPosition
方法中弄乱您的位置。
你的项目看起来很有前途!
关于c++ - Sprite 纹理不从图像中划分碎片 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837036/