我是Python的新手,正在从事太空入侵者游戏。我想让飞船发射子弹,但是当我按下发射键时,没有子弹被射击。多次按下后,程序关闭。
AlienGame.py
import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("TemplAReeb's First Game")
ship = Ship(ai_settings, screen)
bullets = Group()
bg_color = (230, 230, 230)
while True:
gf.check_events(ship, bullets)
ship.update()
bullets.update()
gf.update_screen(ai_settings, screen, ship, bullets)
screen.fill(bg_color)
ship.blitme()
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
screen.fill(bg_color)
ship.blitme()
pygame.display.flip()
run_game()
gamefunctions.py
import sys
import pygame
from bullet import Bullet
def check_keydown_events (event, bullets):
if event.key == pygame.K_SPACE:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def check_events(ship, bullets):
keys = pygame.key.get_pressed()
ship.moving_right = keys[pygame.K_RIGHT]
ship.moving_left = keys[pygame.K_LEFT]
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
check_keydown_events(event, bullets)
def update_screen(ai_settings, screen, ship, bullets):
bg_color = (230, 230, 230)
screen.fill(bg_color)
ship.blitme()
for bullet in bullets.sprites():
bullet.draw_bullet()
pygame.display.flip()
我收到ai_settings未定义的错误
Traceback (most recent call last):
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 32, in <module>
run_game()
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 19, in run_game
gf.check_events(ship, bullets)
File "C:\Users\Areeb Irfan\.PyCharmCE2018.3\config\scratches\game_functions.py", line 16, in check_events
check_keydown_events(event, bullets)
File "C:\Users\Areeb Irfan\.PyCharmCE2018.3\config\scratches\game_functions.py", line 7, in check_keydown_events
new_bullet = Bullet(ai_settings, screen, ship)
NameError: name 'ai_settings' is not defined
答案 0 :(得分:1)
您的错误来自check_keydown_events
中的这一行:
new_bullet = Bullet(ai_settings, screen, ship)
您正试图将ai_settings
传递给Bullet
构造函数,但未在当前check_keydown_events
函数的名称空间中定义。与update_screen
不同,您不会传入ai_settings
作为参数。
您可能需要修复该问题。您已经知道怎么做,因为您已经将ai_settings
传递到update_screen
(当前未使用它,您是否可能将它添加到错误的位置?)。您只需要将其扩展到check_events
和check_keydown_events
。