0

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!

kaktus_car
  • 986
  • 2
  • 11
  • 19
  • 1
    It just doesn't seem necessary; why don't you use a dictionary mapping piece and colour to the surface objects? `{('white', 'Pawn'): white_pawn, ...}`. Or maybe make it a property of the piece, so you can just `window.blit(field.surface, (field.x, field.y))`. – jonrsharpe Apr 29 '20 at 21:56
  • couldn't you just use `lambda` for that? – mapf Apr 29 '20 at 21:56
  • Thank you for responses. I thought of this and since I'm learning I've decided to ask for opinions. Dictionary is an excellent option, and I'm not sure how I would implement `lambda`. – kaktus_car Apr 29 '20 at 22:04
  • @mkrieger1 Actually it does, I searched but haven't found this one. Knew about security issues but wasn't aware it is slow. Thanks. – kaktus_car Apr 29 '20 at 22:06

0 Answers0