我正在尝试通过复制和检查以下内容来学习pygame:https://www.wikihow.com/Program-a-Game-in-Python-with-Pygame#Adding_a_Player_Object_sub
但是,当我运行上述原始版本(第4步)或我的代码时 它带给我黑屏和此错误:
Traceback (most recent call last):
File "C:/Users/Mohamed/Desktop/mopy/pys/first pycharm.py", line 77, in <module>
game().gameloo()
File "C:/Users/Mohamed/Desktop/mopy/pys/first pycharm.py", line 60, in gameloo
self.handle()
File "C:/Users/Mohamed/Desktop/mopy/pys/first pycharm.py", line 74, in handle
for event in pygame.event.get():
pygame.error: video system not initialized
这是我的代码:
import pygame
from pygame.locals import *
pygame.init()
resolution = (400, 350)
white = (250, 250, 250)
black = (0, 0, 0)
red = (250, 0, 0)
green = (0, 250, 0)
screen = pygame.display.set_mode(resolution)
class Ball:
def __init__(self, xPos=resolution[0] / 2, yPos=resolution[1] / 2, xVel=1, yVel=1, rad=15):
self.x = xPos
self.y = yPos
self.dx = xVel
self.dy = yVel
self.radius = rad
self.type = "ball"
def draw(self, surface):
pygame.draw.circle(surface, black, (int(self.x), int(self.y)), self.radius)
def update(self):
self.x += self.dx
self.y += self.dy
if (self.x <= 0 or self.x >= resolution[0]):
self.dx *= -1
if (self.y <= 0 or self.y >= resolution[1]):
self.dy *= -1
class player:
def __init__(self, rad=20):
self.x = 0
self.y = 0
self.radius = rad
def draw(self, surface):
pygame.draw.circle(surface, red, (self.x, self.y))
ball = Ball()
class game():
def __init__(self):
self.screen = pygame.display.set_mode(resolution)
self.clock = pygame.time.Clock()
self.gameobjct = []
self.gameobjct.append(Ball())
self.gameobjct.append(Ball(100))
def handle(self):
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
def gameloo(self):
self.handle()
for gameobj in self.gameobjct:
gameobj.update()
screen.fill(green)
for gameobj in self.gameobjct:
gameobj.draw(self.screen)
pygame.display.flip()
self.clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
game().gameloo()
答案 0 :(得分:1)
您已经两次pygame.display.set_mode()
初始化了窗口。删除全局窗口初始化,但保留并使用设置为类.screen
的{{1}}属性的窗口。
方法game
仅应执行事件循环,而方法handle
应包含主循环。在主循环内,事件必须由gameloo
处理:
self.handle()
screen = pygame.display.set_mode(resolution)