我正在尝试学习python使用pygame创建一个小型视频游戏,当我决定将所有代码更改为OOP时,一切都会停止工作。我做了很多尝试,改变了整个设计模式两次,但仍然无法正常工作。
现在,我将代码减少到最低限度,但仍然找不到错误的地方
你们可以帮我吗?
import pygame
from pygame.locals import *
class App(pygame.sprite.Sprite):
def __init__(self):
self._WINDOW_WIDTH = 640
self._WINDOW_HEIGHT = 480
self._WINDOW_SIZE = (self._WINDOW_WIDTH, self._WINDOW_HEIGHT)
self._BGIMAGE = pygame.image.load("resources/misrecursos/fondo.jpg")
self.clock = pygame.time.Clock()
self._TITLE = "Space Invades"
self._run = True
self._fullSC = False
self._screen = None
def mainloop(self):
pygame.init()
pygame.display.set_caption(self._TITLE)
self._screen = pygame.display.set_mode(self._WINDOW_SIZE, 0, 32)
keys = pygame.key.get_pressed()
while self._run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._run = False
if keys[K_ESCAPE]:
self._run = False
if keys[K_f]:
self._screen = pygame.display.set_mode(self._WINDOW_SIZE, pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF, 32)
self._screen.blit(self._BGIMAGE, (0,0))
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
app = App()
app.mainloop()
答案 0 :(得分:0)
问题是您一开始只读取一次按键。您需要在主循环中反复进行操作。请参阅以下所有CAPS注释指示的更改:
import pygame
from pygame.locals import *
class App(pygame.sprite.Sprite):
def __init__(self):
self._WINDOW_WIDTH = 640
self._WINDOW_HEIGHT = 480
self._WINDOW_SIZE = (self._WINDOW_WIDTH, self._WINDOW_HEIGHT)
self._BGIMAGE = pygame.image.load("resources/misrecursos/fondo.jpg")
self.clock = pygame.time.Clock()
self._TITLE = "Space Invades"
self._run = True
self._fullSC = False
self._screen = None
def mainloop(self):
pygame.init()
pygame.display.set_caption(self._TITLE)
self._screen = pygame.display.set_mode(self._WINDOW_SIZE, 0, 32)
####### keys = pygame.key.get_pressed() # <---- NOT HERE!
while self._run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._run = False
keys = pygame.key.get_pressed() # <---- DOWN HERE INSIDE GAME LOOP.
if keys[K_ESCAPE]:
self._run = False
if keys[K_f]:
self._screen = pygame.display.set_mode(
self._WINDOW_SIZE,
pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF, 32)
self._screen.blit(self._BGIMAGE, (0,0))
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
app = App()
app.mainloop()
答案 1 :(得分:0)
啊...很简单。 您应该移动行:
keys = pygame.key.get_pressed()
self._run循环时在里面:)
例如:
def mainloop(self):
pygame.init()
pygame.display.set_caption(self._TITLE)
self._screen = pygame.display.set_mode(self._WINDOW_SIZE, 0, 32)
while self._run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._run = False
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
self._run = False
if keys[K_f]:
self._screen = pygame.display.set_mode(self._WINDOW_SIZE, pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF, 32)
self._screen.blit(self._BGIMAGE, (0,0))
pygame.display.update()
pygame.quit()