我正在为一群超级聪明的年轻爱好者教授每两周一次的编码课程。我们已经介绍了 OOP 并使用 OOP 创建了一个基于文本的冒险。现在我打算教 PyGame 并继续使用对象,我想知道是否可以以这样一种方式构建游戏,即每个对象的代码都在一个单独的文件中?这将非常简洁且易于构建。那么对于下面的代码,我尝试为每个对象制作单独的文件。这只是部分成功,因为绘制方法从来没有很好地工作,我相信我不能有单独的文件引用同一个 pygame 屏幕的问题。import pygameimport randomimport time# Define some colorsBLACK = (0, 0, 0)WHITE = (255, 255, 255)BLUE = (0,0,255)SCREEN_WIDTH = 700SCREEN_HEIGHT = 500pygame.init()class Paddle: '''Class to keep players location''' def __init__(self,x=350, y=480, width =70,height=20): self.x = x self.y = y self.change_x = 0 self.change_y = 0 self.width = width self.height = height self.score = 0 def move(self): self.x += self.change_x self.y += self.change_y def draw(self): pygame.draw.rect(screen, BLUE, [self.x,self.y, self.width, self.height]) def check_collision(self,ball): if ball.y>460: if abs(35+ self.x - ball.x) < 30: self.score += 1 ball.draw(BLUE) ball.y = 0 ball.x = random.randint(0,650) ball.change_y = random.randint(2,3+int(self.score/5))class Ball: """Class to keep track of a ball's location and vector.""" def __init__(self,x=350,y=250,size=25): self.x = x self.y = y self.change_x = 0 self.change_y = 0 self.size = size def move(self): self.x += self.change_x self.y += self.change_y def draw(self,colour = WHITE): pygame.draw.circle(screen,WHITE, [self.x, self.y], self.size)# Set the height and width of the screensize = [SCREEN_WIDTH, SCREEN_HEIGHT]screen = pygame.display.set_mode(size)pygame.display.set_caption("Bouncing Balls")done = Falseclock = pygame.time.Clock()screen.fill(BLACK)ball = Ball()player = Paddle()ball.change_y = 2ball.draw()当我有单独的文件时,这是我遇到的与屏幕相关的错误line 20, in draw pygame.draw.circle(screen,WHITE, [self.x, self.y], self.size)NameError: name 'screen' is not defined
1 回答
鸿蒙传说
TA贡献1865条经验 获得超7个赞
向类的方法添加一个surface参数,并在传递给该方法的表面上绘制对象:draw()PaddleBall
class Paddle:
# [...]
def draw(self, surface):
pygame.draw.rect(surface, BLUE, [self.x,self.y, self.width, self.height])
class Ball:
# [...]
def draw(self, surface, colour = WHITE):
pygame.draw.circle(surface, colour, [self.x, self.y], self.size)
pygame.Surface现在您可以在任何您想要的对象上绘制对象,例如screen:
ball.draw(screen)
player.draw(screen)
添加回答
举报
0/150
提交
取消