你们中的一些人可能已经看过我之前关于Pygame项目的问题,但我决定进行重写并遵循适当的面向对象编程,因为它并没有真正解决。
这是我到目前为止所做的:
###### Import & Init ######
import pygame
import os, random, math, copy, sys
pygame.init()
###### Variables ######
displayWidth, displayHeight = 600, 600
shipWidth, shipHeight = 50, 50
# Variables that will be used to centre the ship.
startX = displayWidth / 2
startY = displayHeight - 40
screen = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Space Arcader')
####### Colours #######
# Colour list containing most common colours.
# Colour R G B
red = (255, 0, 0)
green = ( 0, 255, 0)
blue = ( 0, 0, 255)
grey = (100, 100, 100)
black = ( 0, 0, 0)
white = (255, 255, 255)
# Create a list from the colours in order to call it later.
colourList = [red, green, blue, black, white]
####### Classes #######
# Ship class
class Ship(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assets/ship.png").convert_alpha()
self.image = pygame.transform.scale(self.image,(shipWidth, shipHeight))
self.transform = self.image
self.rect = self.image.get_rect()
self.rect.centerx = startX
self.rect.centery = startY
# Where the arrow will be pointing on game start
self.angle = 90
def update(self, direction):
if direction == 'right' and self.angle > 20:
self.angle -= 4
elif direction == 'left' and self.angle < 160:
self.angle += 4
self.transform = pygame.transform.rotate(self.image, self.angle)
self.rect = self.transform.get_rect()
self.rect.centerx = startX
self.rect.centery = startY
def draw(self):
screen.blit(self.transform, self.rect)
# Score class
class Score(object):
def __init__(self):
self.total = 0
self.font = pygame.font.SysFont('Helvetica', 15)
self.render = self.font.render('Score: ' + str(self.total), True, white)
self.rect = self.render.get_rect()
self.rect.left = 5
self.rect.bottom = displayHeight - 2
self.render.set_colorkey((0,0,0))
def update(self, delete_scoreList):
self.total += ((len(delete_scoreList)) * 50)
self.render = self.font.render('Score: ' + str(self.total), True, white)
def draw(self):
screen.blit(self.render, self.rect)
# Game class
class MainGame(object):
def __init__(self):
self.score = 0
self.game_over = False
def controls(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
Menu.terminate()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = 'left'
elif event.key == pygame.K_RIGHT:
direction = 'right'
elif event.type == pygame.KEYUP:
direction = None
if event.key == pygame.K_SPACE:
bullet = Bullet()
bullet.rect.x = arrow.rect.x
bullet.rect.y = arrow.rect.y
all_sprites_list.add(bullet)
bulletList.add(bullet)
elif event.key == pygame.K_ESCAPE:
running = False
MenuInit()
def displayInit(self, screen):
# Set screen width and height.
display = pygame.display.set_mode((displayWidth, displayHeight))
# Set the background image of the window.
background = pygame.image.load("assets/background.jpg")
# Blit the background onto the screen.
screen.blit(background, (0, 0))
# Disable mouse visibility.
pygame.mouse.set_visible(False)
# Code to redraw changing/moving objects.
pygame.display.flip()
# Menu class
class Menu:
hovered = False
def __init__(self, text, pos):
self.text = text
self.pos = pos
self.set_rect()
self.draw()
def draw(self):
self.set_rend()
screen.blit(self.rend, self.rect)
def set_rend(self):
menu_font = pygame.font.SysFont('Helvetica', 40)
self.rend = menu_font.render(self.text, True, self.get_color())
def get_color(self):
if self.hovered:
return (white)
else:
return (grey)
def set_rect(self):
self.set_rend()
self.rect = self.rend.get_rect()
self.rect.topleft = self.pos
def terminate():
pygame.quit()
sys.exit()
####### Functions #######
def MenuInit():
# Set the background image of the window.
background = pygame.image.load("assets/menuBackground.jpg")
options = [Menu("Start game", (200, 250)), Menu("Quit", (265, 300))]
# Enable mouse visibility.
pygame.mouse.set_visible(True)
while True:
for option in options:
if option.rect.collidepoint(pygame.mouse.get_pos()):
option.hovered = True
else:
option.hovered = False
option.draw()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for option in options:
if option.hovered and option.text == "Start game":
MainInit()
elif option.hovered and option.text == "Quit":
Menu.terminate()
pygame.display.update()
screen.blit(background,(0,0))
def MainInit():
# Manage the refresh rate
clock = pygame.time.Clock()
# Loop the game until the user closes the application.
running = True
# Open an instance of the Game class
game = MainGame()
ship = Ship()
score = Score()
# Main Loop.
while running:
draw = ship.draw()
ship.update(direction)
# ship.update(direction)
# ship.draw()
controls = game.controls()
game.displayInit(screen)
# Refresh rate speed (frames per second).
clock.tick(60)
# Open the menuInit() function which brings up the main menu.
if __name__ == '__main__':
MenuInit()
所以我的问题是尝试blit the ship并打入MainInit()函数,该函数调用游戏类对象,如上所示。调用游戏类对象可以正常工作,因为背景图像更改并且控件完美地工作。但是,当我按照相同的方法进行发货和评分时,它似乎不起作用。在注释掉的评论中,您可以看到我尝试了一些内容,但我遇到了各种错误,例如"NameError: global name 'direction' is not defined"
或NameError: global name 'update' is not defined
任何指针? :)
非常感谢。
答案 0 :(得分:1)
问题是由超出范围的变量引起的 - 正如错误告诉您的那样:global name 'direction' is not defined"
。
您在direction
中使用def MainInit()
,但该函数中从未定义direction
。您定义/设置direction
- 变量的位置位于class MainGame.controls()
。
但问题是,direction
中创建的class MainGame.controls()
- 变量仅为本地。它只存在于该特定函数MainGame.controls()
中。当不再使用该函数时,direction
的值将不复存在 - 这就是direction
中没有def MainInit()
定义的原因。它超出范围。
要解决此问题,您可以选择将direction
用作全局变量。它要求您在任何函数之外定义direction
值,因此最初应该可以工作。
每当您想要读取/修改特定的全局变量时,您应该使用global
关键字来告诉您的Python函数您要使用/修改全局变量,而不是本地变量
global direction
个人我不会使用全局变量,而是在direction
类中存储Ship
成员变量并直接更改它。
全局变量可能变得非常混乱。