python - Itterating through a list of objects from custom made class
问题描述
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 !!!
解决方案
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))
推荐阅读
- clojurescript - Clojurscript:扩展一个 Javascript 类
- vba - 更新后如何使用来自两个组合框的 dlookup 填充文本框
- julia - 在 Julia 中模仿 Scala Option[T] 的最佳方式?
- javascript - 通过javascript创建新的div
- flutter - 有没有办法导航页面白色保持相同的背景颤动
- spring-boot - RolesAllowed 和 antMatchers.hasRole 正在返回由@Order 导致的访问被拒绝
- laravel - 来自关系 laravel 的 Groupby
- c++ - SetConsoleControlHandler 函数是如何工作的?如何将当前进程的属性继承给子进程?
- reactjs - React / Axios 使用带有客户端证书身份验证的 REST API
- json - 使用 Pandas 从包含多个工作表的 Excel 文件创建多个 .json 文件