I want the main character to continue to move in the specific direction I chose until I press another key. This is the code for what I did:
for event in pygame.event.get():
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_q:
pygame.quit()
elif event.key==pygame.K_w:
dir="Up"
elif event.key==pygame.K_s:
dir="Down"
elif event.key==pygame.K_d:
dir="Right"
if dir=="Up":
if valid_move((ChY-45)//size, (ChX)//size):
ChY-=15
if dir=="Down":
if valid_move((ChY 45)//size, (ChX)//size):
ChY =15
if dir=="Right":
if valid_move((ChY)//size, (ChX 45)//size):
ChX =15
if dir=="Left":
if valid_move((ChY)//size, (ChX-45)//size):
ChX-=15
CodePudding user response:
It is a matter of Indentation. You have to move Pacman continuously in the application loop instead of the event loop:
# application loop
run = True
while run:
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_q:
run = False
elif event.key==pygame.K_w:
dir="Up"
elif event.key==pygame.K_s:
dir="Down"
elif event.key==pygame.K_d:
dir="Right"
elif event.key==pygame.K_a:
dir="Left"
# INDENTATION
#<--|
if dir=="Up":
if valid_move((ChY-45)//size, (ChX)//size):
ChY-=15
if dir=="Down":
if valid_move((ChY 45)//size, (ChX)//size):
ChY =15
if dir=="Right":
if valid_move((ChY)//size, (ChX 45)//size):
ChX =15
if dir=="Left":
if valid_move((ChY)//size, (ChX-45)//size):
ChX-=15
# [...]