Reputation: 131
I am writing a chess game and I have encountered a problem.
I have created figure classes (Pawn, Tower, Jumper, Runner, King and Queen), now I am trying to make add some functionality so that the program recognizes when the mouse cursor is over a figure, and that's where my problems begin.
Obviously, I can make it work if by hand I write a check for each single instance of a class (for example 16 pawn), like so:
[Notice Pawn is my class name]
mouse_x, mouse_y = pygame.mouse.get_pos()
if pawn1.start_x <= mouse_x <= pawn1.start_x + 86 and pawn1.start_y + 84 >= mouse_y >= pawn1.start_y:
print('Pawn 1 was clicked')
This is tedious, I want to iterate through a list of all existing pawns;
pawn_list = [pawn1, pawn2, pawn3, pawn4, pawn5, pawn6, pawn7, pawn8, pawn9, pawn10, pawn11, pawn12, pawn12, pawn14, pawn15, pawn16]
MY QUESTION IS HOW CAN I DO THAT? Till now I have come up with the following:
mouse_x, mouse_y = pygame.mouse.get_pos()
for Pawn in pawn_list:
if pawn_list[Pawn].start_x <= pawn_list[Pawn].start_x + 86 and pawn_list[Pawn].start_y + 84 >= mouse_y >= pawn_list[Pawn].start_y:
print('The mouse is over the pawn no:' + str(Pawn))
But then I get a following error:
TypeError: list indices must be integers or slices, not Pawn
Nor does using a different variable name help me out:
for _ in range(len(pawn_list)):
if pawn_list[_].start_x <= pawn_list[_].start_x + 86 and pawn_list[_].start_y + 84 >= mouse_y >= pawn_list[_].start_y:
print('The mouse is over the pawn no:' + str(_))
All help is appreciated, thanks !!!
Upvotes: 2
Views: 76
Reputation: 79
You're already iterating through list, so why do you want to get the Pawn index from the list again? Potentially this is incorrect.
Correct statement would be:
for objPawn in pawn_list:
if objPawn.start_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
print('The mouse is over the pawn no:' + str(Pawn))
Upvotes: 2