我一直在尝试使用python编写小型2D游戏的代码。
checkp_list[0]=head_pos pressed_key= pygame.key.get_pressed() if pressed_key[pygame.K_ESCAPE]: running=False if pressed_key[pygame.K_UP]: if dir_ not in ["up", "down"]: dir_= "up" checkp_no= checkp_no+1 #head_pos_next=head_move(head_pos, dir_) checkp_list.insert(checkp_no,head_pos) log_file_obj.write("chekp_list {}, checkp_no {} after append dir {}\n".format(checkp_list,checkp_no,dir_)) if pressed_key[pygame.K_DOWN]: if dir_ not in ["up", "down"]: dir_= "down" checkp_no= checkp_no+1 #head_pos_next = head_move(head_pos, dir_) checkp_list.insert(checkp_no,head_pos) log_file_obj.write("chekp_list {}, checkp_no {} after append dir {}\n".format(checkp_list,checkp_no,dir_)) if pressed_key[pygame.K_RIGHT]: if dir_ not in ["left", "right"]: dir_= "right" checkp_no= checkp_no+1 #head_pos_next = head_move(head_pos, dir_) checkp_list.insert(checkp_no,head_pos) log_file_obj.write("chekp_list {}, checkp_no {} after append dir {}\n".format(checkp_list,checkp_no,dir_)) if pressed_key[pygame.K_LEFT]: if dir_ not in ["left", "right"]: dir_= "left" checkp_no= checkp_no+1 #head_pos_next = head_move(head_pos, dir_) checkp_list.insert(checkp_no,head_pos) log_file_obj.write("chekp_list {}, checkp_no {} after append dir {}\n".format(checkp_list,checkp_no,dir_))
所有这些都在while True:循环内运行。基本上,每按一次箭头键,方向指示器dir_就会更改,它将在检查点编号上加1checkp_no并将当前head_pos对象的当前头部位置(在checkp_no索引位置插入该头部对象。)但是,不幸的是,所有这些checkp_list点都是最新的head_pos。该列表checkp_list是实现我的逻辑的重要因素。
while True:
checkp_no
head_pos
checkp_list
chekp_list在start时[[325, 791], [325, 791], [325, 791]],这是checkp_listwhencheckp_no是2,whenwhile循环正在开始另一个迭代(取自创建的日志文件)。所有checkp_list要附加的点都在上面。请帮助我确定问题。
chekp_list
[[325, 791], [325, 791], [325, 791]]
while
pygame.key.get_pressed()返回包含键当前状态的列表。按住某个键时,该键的状态为True,否则为False。使用pygame.key.get_pressed()评估是否一个键被连续按下。
pygame.key.get_pressed()
True
False
while True: pressed_key= pygame.key.get_pressed() if pressed_key[pygame.K_UP]: # the code in this condition is executed as long UP is hold down # [...]
当键的状态更改时,键盘事件(请参阅pygame.event模块)仅发生一次。KEYDOWN每次按下一个键,事件就会发生一次。KEYUP每次释放钥匙时发生一次。
KEYDOWN
KEYUP
while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # The following code is executed once, every time when ESC is pressed. # [...] if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: # The following code is executed once, every time when ESC is released. # [...]