python - Pygame环境下如何绘制矩形和圆形
问题描述
我正在尝试使用各种形状的精灵创建一个 pygame 环境,但我的代码似乎无法正常工作。这是我所拥有的:
class Object(pygame.sprite.Sprite):
def __init__(self, position, color, size, type):
# create square sprite
pygame.sprite.Sprite.__init__(self)
if type == 'agent':
self.image = pygame.Surface((size, size))
self.image.fill(color)
self.rect = self.image.get_rect()
else:
red = (200,0,0)
self.image = pygame.display.set_mode((size, size))
self.image.fill(color)
self.rect = pygame.draw.circle(self.image, color,(), 20)
# initial conditions
self.start_x = position[0]
self.start_y = position[1]
self.state = np.asarray([self.start_x, self.start_y])
self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
有人注意到 Object 类有什么问题吗?
解决方案
您必须创建一个pygame.Surface
, 而不是创建一个新窗口 ( pygame.display.set_mode
)。Surface
的像素格式必须包含每个像素的 alpha ( )。圆的中心点必须是Surface的中心。半径必须是Surface大小的一半:SRCALPHA
self.image = pygame.Surface((size, size), pygame.SRCALPHA)
radius = size // 2
pygame.draw.circle(self.image, color, (radius, radius), radius)
类Object
:
class Object(pygame.sprite.Sprite):
def __init__(self, position, color, size, type):
# create square sprite
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((size, size), pygame.SRCALPHA)
self.rect = self.image.get_rect()
if type == 'agent':
self.image.fill(color)
else:
radius = size // 2
pygame.draw.circle(self.image, color, (radius, radius), radius)
# initial conditions
self.start_x = position[0]
self.start_y = position[1]
self.state = np.asarray([self.start_x, self.start_y])
self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
推荐阅读
- angular - 使用复选框获取动态生成的 Ionic 列表中所选项目的值
- z3 - 我们能否解决 Z3 中的一组约束,其中 ForAll 量词下的一些变量具有一系列值?
- file - UNIX 'ls' 命令排除不需要的文件
- pandas - 如何将多个镶木地板文件附加到 Pandas 中的一个数据框
- javascript - 如何使 for 循环等待/异步?
- sql - SQL 查询/过程根据最匹配的列在两个表之间找到最佳匹配
- mysql - 选择具有多个 id 的内部 JOIN
- php - 已编辑:PHP 代码无法识别表单提交
- javascript - 有两个条件的三元运算符
- node.js - 将 Lambda 函数更新到新的运行时。为什么 cURL 不再在 AWS Lambda 上的节点 10 中工作?