【发布时间】:2017-09-27 22:48:07
【问题描述】:
这部分是gamefunction.py文件
import sys
import pygame
def check_keydown_events(event,ship):
"""Respond to the keypressess."""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
ship.moving_down = True
def check_keyup_events(event, ship):
"""Respond to the keyreleases."""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
elif event.key == pygame.K_UP:
ship.moving_up = False
elif event.key == pygame.K_DOWN:
ship.moving_down = False
def check_events(ship):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event,ship)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
这被命名为 ship.py
import pygame
class Ship():
def __init__(self,ai_settings,screen):
"""Initialize the ship and set its starting position."""
self.screen = screen
self.ai_settings = ai_settings
#Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#Start each new ship at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#Store a decimal value for the ship's center.
self.center = float(self.rect.centerx)
#Movement Flags
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
def update(self):
"""Update the ship's position based on the movement flag."""
#Update the ship's center value, not the rect
if self.moving_right and self.rect.right<self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left>0:
self.center -= self.ai_settings.ship_speed_factor
#Up-dwon motion added ***Please check the logic for 1200x800 screen***
if self.moving_up and self.rect.top<self.screen_rect.top:
self.center += self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom>800:
self.center -= self.ai_settings.ship_speed_factor
#Update rect object from self.center.
self.rect.centerx = self.center
【问题讨论】:
-
您的问题是什么?你有错误吗?代码没有按您的预期运行吗?您需要在正文中定义问题并解释问题所在,您希望它做什么,并提供minimal reproducible example。确保您的代码格式正确,以便更容易阅读代码。
-
代码在上下移动时未按预期执行
-
当你问一个问题时,你必须确保它的格式正确以便它可读(不过我现在已经为你做了)。您还必须解释代码在做什么(正在发生什么)并解释您试图做什么。由于您没有提供minimal reproducible example,我们无法测试代码以找出问题所在。当您编写“代码未按预期执行”时,我们只能猜测问题所在。如果你改为写“这艘船的移动方向与我希望它移动的方向相反”我们就会知道要寻找什么。
标签: python python-2.7 pygame