【问题标题】:how to gfxdraw in a subclass of pygame.Surface?如何在 pygame.Surface 的子类中绘制 gfxdraw?
【发布时间】:2015-03-21 23:13:53
【问题描述】:

我是否以错误的方式继承 Surface?错误提示 gfxdraw.aacircle() 需要 Surface 作为第一个参数,但我不知道该怎么做。

下面的可运行代码和异常:

import pygame, sys, os
from pygame.locals import *
from pygame import gfxdraw

BLACK = (0,0,0)
WHITE = (255,255,255)

class basicButton(pygame.Surface): # basic surface for buttons
    def __init__(self, size, radius):
        pygame.Surface.__init__(self, size=(size, size))
        self.fill(BLACK)
        # anti-aliased outline
        pygame.gfxdraw.aacircle(self, radius, radius, radius, WHITE)
        # color filled circle
        pygame.gfxdraw.filled_circle(self, radius, radius, radius, WHITE)
        # set black to be transparent
        self.set_colorkey(BLACK)

# make an instance
quitButtonSurf = basicButton(25, 12)

pygame.init()
screen = pygame.display.set_mode((800, 600))

while True:
    screen.blit(quitButtonSurf)
    pygame.display.flip()

抛出异常:

pygame.gfxdraw.aacircle(self, radius, radius, radius,  WHITE)
  TypeError: surface must be a Surface

【问题讨论】:

  • 我没有制作表面类型的类对象的经验,我通常使用精灵。话虽如此,您是否考虑过将其视为普通对象并简单地为其分配图像表面?然后你可以传入该表面用于绘图功能。
  • 感谢您的回答。我考虑了你所说的,我会尝试一下,但仍然不明白为什么这不起作用。我也使用精灵,但我正在从 Surface 构造函数中制作所有 sprite.image ,因为所有图形都是相似的并且是代码生成的,这是不好的做法吗?
  • 我是一个自学成才的独立开发者,没有同行评审的优势,所以我不会评论某件事是否是不好的做法。我认为您最好使用调用 pygame 的表面类的函数。不是因为你所做的事情必然是一个坏主意,而是因为我们知道这是可行的。唯一真正改变的是当前类代码的前几行。您可以在您创建的表面类的实例上执行所有其他功能。

标签: python python-2.7 pygame


【解决方案1】:

很遗憾,这不是您想要的,但它应该可以工作。

import pygame, sys, os
from pygame.locals import *
from pygame import gfxdraw

pygame.init()


BLACK = (0,0,0)
WHITE = (255,255,255)

class basicButton: 
    def __init__(self, size, radius):
        self.image = pygame.Surface((size,size)) # as per your example, assuming a square
        self.image.fill(BLACK)
        pygame.gfxdraw.aacircle(self.image, radius, radius, radius,  WHITE)
        pygame.gfxdraw.filled_circle(self.image, radius, radius, radius,  WHITE)
        self.image.set_colorkey(BLACK)


quitButtonSurf = basicButton(25, 12)

screen = pygame.display.set_mode((800, 600))

while True:
    screen.blit(quitButtonSurf.image,(0,0)) # you'll have to assign a location for this object, I set it to 0,0 simply for testing
    pygame.display.flip()

希望对你有帮助

【讨论】:

  • 这很好用,我最终这样做了,因为也许 Surface 不能像子类化 Sprite 那样被子类化。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 2011-09-07
  • 1970-01-01
  • 2017-06-29
相关资源
最近更新 更多