Use the arrow keys to control the movement of the fat chicken.
1. Respond to the button (taking right as an example)
update: \game_functions.py:
import...
def check_events(chicken):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
# 向右移动
chicken.rect.centerx += 1
...
Update: \FatChickenWars.py:
...
# 监视键盘和鼠标事件
gf.check_events(chicken)
...
2. It is allowed to move continuously (taking the movement to the right as an example)
while holding down the arrow keys, the fat chicken should move continuously.
Implementation method: add moving_right attribute and update() method to Chicken class
Update: \chicken.py-Class Chicken():
...
#移动标志
self.moving_right = False
def update(self):
"""根据移动标志调整肥鸡位置"""
if self.moving_right:
self.rect.centerx += 1
Update: \game_functions.py:
def check_events(chicken):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
chicken.moving_right = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
chicken.moving_right = False
Update: \FatChickenWars.py:
...
while True:
# 监视键盘和鼠标事件
gf.check_events(chicken)
# 更新肥鸡状态
chicken.update()
# 更新画面
gf.update_screen(fcw_settings, screen, chicken)
...
The effect is good.
2021.1.21