我知道如何加载 Sprite 表,剪辑图像并返回这些图像的列表,但我喜欢通过名称而不是索引来引用我的 Sprite ,以保持代码的可读性和可管理性,但它有时很长并且写出 Sprite 名称列表很乏味。
我通常创建一个字典,并通过名称引用我需要的 Sprite ,但我想知道是否应该对名称进行硬编码?
这是我通常做的事情:
sprites = load_spritesheet('spr_buttons.png', (64, 64))
BUTTON_NAMES = ['start', 'start_hover', 'start_click', 'back', 'back_hover',
'back_click', 'skip', 'skip_hover', 'skip_click', 'exit',
'exit_hover', 'exit_click', 'check', 'check_hover',
'check_click', 'blank']
spr_buttons = {}
for index, sprite in enumerate(sprites):
spr_buttons[BUTTON_NAMES[index]] = sprite
以这些按钮 Sprite 为例,我还有一个按钮类,并为每个按钮创建一个新实例,并传入 Sprite 的名称。
这很好用,但我想找到更好的方法。我是否创建一个 .txt 文件来伴随我的 Sprite 表并从中获取名称?或者我是否使用分配给每个 Sprite 的关键字+索引号(例如 button_1
、button_2
等)?
这是我的 NewButton
类:
import pygame
class NewButton:
"""Create and maintain a new button."""`
def __init__(self, name, sprites, x_pos, y_pos, size):
"""Initialise a new button instance.
:param name: The name of the button from the dictionary.
:param sprites: A dictionary of button sprite images.
:param x_pos: The x position of the button image.
:param y_pos: The y position of the button image.
:param size: The squared size of the button image.
"""
self.img_normal = sprites[name]
self.img_hover = sprites[name + '_hover']
self.img_click = sprites[name + '_click']
self.rect = pygame.Rect(x_pos, y_pos, size, size)
self.image = self.img_normal
self.hover = False
self.clicked = False
self.execute = False
self.max_timer = 20
self.click_timer = 0
def update(self, delta):
"""Update the button instance.
:param delta: A multiplier based on real time between updates.
"""
if self.clicked:
self.click_timer += delta
if self.click_timer < self.max_timer / 2:
self.image = self.img_click
elif self.click_timer >= self.max_timer:
self.clicked = False
self.click_timer = 0
self.image = self.img_normal
self.execute = True
else:
self.image = self.img_normal
else:
mx, my = pygame.mouse.get_pos()
if self.rect.collidepoint(mx, my):
self.image = self.img_hover
self.hover = True
else:
self.image = self.img_normal
self.hover = False
def click(self):
"""Set the button as being clicked."""
self.clicked = True
def reset(self):
"""Reset the execute status of the button."""
self.execute = False
最佳答案
您可以使用 zip()
以更简单的方式完成此操作创建字典的函数:
sprites = load_spritesheet('spr_buttons.png', (64, 64))
BUTTON_NAMES = ['start', 'start_hover', 'start_click',
'back', 'back_hover', 'back_click',
'skip', 'skip_hover', 'skip_click',
'exit', 'exit_hover', 'exit_click',
'check', 'check_hover', 'check_click',
'blank']
spr_buttons = dict(zip(BUTTON_NAMES, sprites))
关于python - 我应该如何为 Sprite 表中的 Sprite 指定名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56405694/