I am working on a chess game in pygame, and I came up with an idea to blit
chess piece images onto the screen with following "logic":
for field in fields:
window.blit(eval(f"{field.get_piece().get_colour()}_{field.get_piece().__class__.__name__.lower()}"), (field.x, field.y))
where get_piece()
and get_colour()
are just simple get methods to return Piece object
and colour
respectfully. Piece
can be Pawn
, King
, Queen
, etc.
Pygame surface
objects are named using pattern piece_colour
+ _
+ class_name
. So eval()
gets the job done.
And this way I've avoided writing multiple if statements.
Now I'm interested if this is acceptable (good) solution and ofcourse what are better ways to do this. Thanks!