Sprite Texture不分割图像C ++中的片段

问题描述 投票:3回答:1

[好,我正在尝试使用SFML从头开始制作国际象棋游戏,我遇到的问题是,我最终得到的是下面附有的图片,而不是一堆一堆地下棋。现在,我不担心游戏的功能或用户所需的命令就是运行代码并查看普通的棋盘。

这是我的代码输出:

my problematic output

这是我的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;
}

我正在尝试使用的图片:

enter image description here

c++ textures sprite sfml chess
1个回答
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方法时,它会使您的位置混乱。

您的项目看起来很有希望!

© www.soinside.com 2019 - 2024. All rights reserved.