参数1必须是pygame.Surface,而不是Window

时间:2016-11-15 17:27:57

标签: python-2.7

不确定我尝试做的是错还是不可能。这是我的代码:

import pygame

class Window(object):
    def __init__(self, (width, height), color, cap=' '):
        self.width = width
        self.height = height
        self.color = color
        self.cap = cap
        self.screen = pygame.display.set_mode((self.width, self.height))
    def display(self):
        self.screen
        #screen = 
        pygame.display.set_caption(self.cap)
        self.screen.fill(self.color)

class Ball(object):
    def __init__(self, window, (x, y), color, size, thick=None):
        self.window = window
        self.x = x
        self.y = y
        self.color = color
        self.size = size
        self.thick = thick
    def draw(self):
        pygame.draw.circle(self.window, self.color, (self.x, self.y),
                           self.size, self.thick)

def main():
    black = (0, 0, 0)
    white = (255, 255, 255)
    screen = Window((600, 600), black, 'Pong')
    screen.display()
    ball = Ball(screen, (300, 300), white, 5)
    ball.draw()

    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        pygame.display.flip()
    pygame.quit()
main()

这是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\acmil\Desktop\Team 7\newPongLib.py", line 47, in <module>
    main()
  File "C:\Users\acmil\Desktop\Team 7\newPongLib.py", line 36, in main
    ball.draw()
  File "C:\Users\acmil\Desktop\Team 7\newPongLib.py", line 28, in draw
self.size, self.thick)

TypeError:参数1必须是pygame.Surface,而不是Window

我不明白我是否制作一个Window对象为什么它不会将球画到屏幕上。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

Ball 课程更改为以下内容:

class Ball(object):
    def __init__(self, window, (x, y), color, size, thick=0):
        self.window = window
        self.x = x
        self.y = y
        self.color = color
        self.size = size
        self.thick = thick
    def draw(self):
        pygame.draw.circle(self.window.screen, self.color, (self.x, self.y),
                           self.size, self.thick)

我对您的代码进行了两次修改。

  • 首先,对于您所获得的错误,您传递的是您定义的自定义Window对象,而不是pygame期望的pygame的Screen对象。查看有关此功能here的文档。
  • 其次,您的原始构造函数默认定义thick=None,但pygame函数需要int,因此我将其更改为thick=0

这两个变化后应该可以工作。如果您还有问题,请告诉我们!