OOP游戏圈

2024-09-28 22:10:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个游戏,我需要在角色周围制作一个戒指。我已经编写了用于创建墙的OOP,如下所示,但我不知道如何修改此代码,以便它可以在我的播放器周围创建一个环

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x

另外,我要传递的变量是颜色、半径、宽度/厚度和x&;y坐标,例如

circle = Circle(colour, radius, width, x, y)

图形精灵编辑:

spriteList.add(wallList)
spriteList.draw(screen)

非常感谢您的帮助, 干杯


Tags: 代码rectimageself游戏角色init播放器
1条回答
网友
1楼 · 发布于 2024-09-28 22:10:33

可以用^{}画一个圆

pygame.draw.circle(surface, color, center, radius)

如果只想绘制圆形精灵,只需指定圆的半径和宽度(线宽):

class Circle(pygame.sprite.Sprite):

    def __init__(self, circleColor, radius, width, x, y):
        super().__init__()
        
        self.image = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA)
        pygame.draw.circle(self.image, circleColor, (radius, radius), radius, width)
        self.rect = self.image.get_rect(center = (x, y))

使用此解决方案,需要在同一位置分别绘制两个对象:精灵和圆

但是,如果要创建一个周围有圆的单个精灵对象,则需要创建一个大于精灵图像的透明曲面blit将精灵放在表面上,并在其周围画一个圆圈。在下面的image中有一个^{}对象:

import math
class MyPlayer(pygame.sprite.Sprite):

    def __init__(self, x, y, image, circleColor, width):
        super().__init__()
        
        diameter = math.hypot(*image.get_size())
        radius = diameter // 2

        self.image = pygame.Surface((diameter, diameter), pygame.SRCALPHA)
        self.image.blit(image, image.get_rect(center = (radius, radius))
        pygame.draw.circle(self.image, circleColor, (radius, radius), radius, width)
        self.rect = self.image.get_rect(center = (x, y))

相关问题 更多 >