【问题标题】:How come my pygame code isn't drawing this circle?为什么我的 pygame 代码没有画出这个圆圈?
【发布时间】:2015-06-28 16:41:27
【问题描述】:

http://pastebin.com/PLdiNg9d

首先,我对 Python 还很陌生,很抱歉我的代码很草率!无论如何,关于我的问题。我制作了一个类单元格,在它的 init 函数中,它接受了几个用于绘制圆的变量。然后我这样做:

self.image = pygame.Surface([size, size])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
pygame.draw.circle(self.image, color, [posx, posy], size)
self.rect = self.image.get_rect()
print('Cell initialized.')

问题是,它不会在我的屏幕上绘制任何内容。它不会输出错误消息,但仍会打印“Cell initialized”。所以我知道它一直通过 init 函数。

真正让我感到困惑的是,有一种方法可以让它发挥作用。如果我移动

cell_list = pygame.sprite.Group()
a = Cell(5, GREEN, 2, 200, 200)
cell_list.add(a)

进入我的while循环,然后改变

pygame.draw.circle(self.image, ...)

pygame.draw.circle(screen, ...)

然后它将绘制我的单元格。任何帮助都将不胜感激,因为我完全被难住了。

【问题讨论】:

    标签: python pygame surface


    【解决方案1】:

    这是使用pygame 时使用的简单模板。此演示在屏幕中心绘制了一个圆圈。

    from pygame import *
    screen = display.set_mode((500,500))
    # Fill screen white
    screen.fill((255,255,255))
    
    # Draw a red circle at the center
    # Remove the 1 to make it a filled circle
    draw.circle(screen, (255,0,0), (250,250), 250, 1)
    
    # Game loop
    running = True
    while running:
        # Properly quit (pygame will crash without this)
        for e in event.get():
            if e.type == QUIT:
                running = False
    
        display.flip()
    quit()
    

    【讨论】:

      【解决方案2】:

      代替:

      pygame.draw.circle(self.image, color, [posx, posy], size)
      

      使用:

      pygame.draw.circle(self.image, color, [size, size], size)
      

      说明:在您的表面 (self.image) 上,您在坐标 0, 0 上画圆,但因为 pygamen.draw.circle 需要居中,所以 size, size 在这里。

      如果您希望size 是半径,请在绘图圆中使用size//2 而不是size,如果您希望它是直径,请在image 初始化中使用size*2 而不是size

      你还需要指定rect的位置,所以把它放在Cell.__init__()的某个地方:

      self.rect.x = self.posx
      self.rect.y = self.posy
      

      几点说明:

      • 使用self.variable 而不是variable例如:self.size 而不是仅仅size),因为你可以在课堂上的任何地方使用它
      • pygame.quit()放在程序的最后(while循环之后)

      【讨论】:

        猜你喜欢
        • 2013-12-15
        • 2016-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 1970-01-01
        • 2011-07-26
        • 2013-07-07
        相关资源
        最近更新 更多