[英]Blit object from a Class into a Function (Pygame)
你們中的一些人可能已經看過我以前有關我目前正在從事的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()
所以我的問題是試圖弄亂飛船並得分到MainInit()函數上,該函數調用游戲類對象,如上所示。 調用游戲類對象可以正常工作,因為背景圖像會更改並且控件可以正常工作。 但是,當我采用相同的方法進行評分時,它似乎不起作用。 在注釋掉的注釋中,您可以看到我嘗試了一些操作,但是遇到了各種錯誤,例如"NameError: global name 'direction' is not defined"
或NameError: global name 'update' is not defined
"NameError: global name 'direction' is not defined"
NameError: global name 'update' is not defined
有指針嗎? :)
非常感謝你。
問題是由范圍外的變量引起的-正是錯誤告訴您: global name 'direction' is not defined"
。
您可以使用direction
在您的def MainInit()
但direction
是從未在函數定義。 您定義/設置direction
可變的位置位於class MainGame.controls()
。
問題是,然而,該direction
在-variable創建class MainGame.controls()
僅局部的 。 它只會存在於該特定函數MainGame.controls()
。 當不再使用該函數時, direction
的值將不復存在-這就是為什么在def MainInit()
不存在諸如direction
這樣的東西的原因。 這超出范圍 。
若要解決此問題,您可以選擇將direction
用作全局變量。 它要求您在任何功能之外定義direction
值,因此一開始就應該起作用。
每當您要讀取/修改特定的全局變量時,都應該使用global
關鍵字,以告訴您的Python函數您要使用/修改全局變量,而不是局部變量。
global direction
您可能對此很感興趣: https : //stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them
我個人不會使用全局變量,而是將direction
成員變量存儲在Ship
類中並直接對其進行更改。
全局變量可能變得一團糟。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.