1
+ #include " Graphics.h"
2
+
3
+ namespace chesspp
4
+ {
5
+ namespace graphics
6
+ {
7
+
8
+
9
+ GraphicsHandler::GraphicsHandler ( sf::RenderWindow *_display ) : display(_display),
10
+ backgroundPath (file_path + " res/img/chessboard_640x640.png" ), // Hardcoded. Will change in the future.
11
+ piecePath(file_path + " res/img/chess_pieces_80x80_each.png" ), //
12
+ validMovePath(file_path + " res/img/valid_move.png" ) //
13
+ {
14
+ try
15
+ {
16
+ board = sf::Sprite (TextureManager::getInstance ().Load (backgroundPath));
17
+ pieces = sf::Sprite (TextureManager::getInstance ().Load (piecePath));
18
+ validMove = sf::Sprite (TextureManager::getInstance ().Load (validMovePath));
19
+ }
20
+ catch (chesspp::exception &e)
21
+ {
22
+ #ifdef _DEBUG
23
+ cout << " Error: " << e.what () << endl;
24
+ #endif
25
+ }
26
+ }
27
+
28
+ void GraphicsHandler::drawSpriteAtCell (sf::Sprite &s, const int x, const int y)
29
+ {
30
+ s.setPosition (x * cell_size, y * cell_size);
31
+ display->draw (s);
32
+ }
33
+ void GraphicsHandler::drawBackground ()
34
+ {
35
+ display->draw (board);
36
+ }
37
+ void GraphicsHandler::drawPiece (Piece *p)
38
+ {
39
+ pieces.setTextureRect (sf::IntRect (p->getType ()*cell_size, p->getColor ()*cell_size, cell_size, cell_size));
40
+ drawSpriteAtCell (pieces, p->getBoardPos ().getX (), p->getBoardPos ().getY ());
41
+ }
42
+ void GraphicsHandler::drawPieceAt (Piece *p, const sf::Vector2i &pos)
43
+ {
44
+ pieces.setTextureRect (sf::IntRect (p->getType ()*cell_size, p->getColor ()*cell_size, cell_size, cell_size));
45
+ pieces.setPosition (pos.x - (cell_size / 2 ), pos.y - (cell_size / 2 ));
46
+
47
+ display->draw (pieces);
48
+ }
49
+ void GraphicsHandler::drawValidMove (const int x, const int y)
50
+ {
51
+ drawSpriteAtCell (validMove, x, y);
52
+ }
53
+ void GraphicsHandler::drawBoard (const Board *b)
54
+ {
55
+ drawBackground ();
56
+
57
+ // Valid moves are drawn for the piece being hovered over
58
+ // Or the piece that is currently selected
59
+ Piece* pCurrent = b->getCurrent ();
60
+ Piece* pSelect = b->getSelected ();
61
+ if (pSelect)
62
+ for (posList::const_iterator iter = pSelect->getTrajectory ().begin (); iter != pSelect->getTrajectory ().end (); iter++)
63
+ {
64
+ if (!iter->isValid ()) continue ;
65
+ drawValidMove (iter->getX (), iter->getY ());
66
+ }
67
+ else if (pCurrent)
68
+ for (posList::const_iterator iter = pCurrent->getTrajectory ().begin (); iter != pCurrent->getTrajectory ().end (); iter++)
69
+ {
70
+ if (!iter->isValid ()) continue ;
71
+ drawValidMove (iter->getX (), iter->getY ());
72
+ }
73
+
74
+ // Draw the non-selected pieces
75
+ for (auto iter = b->pieces .begin (); iter != b->pieces .end (); iter++)
76
+ {
77
+ if (!*iter || *iter == b->getSelected ()) continue ;
78
+ drawPiece (*iter);
79
+ }
80
+
81
+ // Draw the selected piece
82
+ if (b->getSelected ())
83
+ drawPieceAt (b->getSelected (), sf::Mouse::getPosition (*display));
84
+ }
85
+ }
86
+ }
0 commit comments