【发布时间】:2019-10-17 17:30:47
【问题描述】:
我知道如何加载精灵表、剪辑图像并返回这些图像的列表,但我喜欢按名称而不是索引来引用我的精灵,以保持代码的可读性和可管理性,但有时它很长而且繁琐的写出精灵名称列表。
我通常创建一个字典,并通过名称引用我需要的精灵,但我想知道我是否应该对名称进行硬编码?
这是我通常做的:
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
以这些按钮精灵为例,我还有一个按钮类,并为每个按钮创建一个新实例,传入精灵的名称。
这很好,但我想找到更好的方法。我是否创建一个 .txt 文件来伴随我的精灵表并从中获取名称?或者我是否使用分配给每个精灵的关键字 + 索引号(例如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
【问题讨论】:
标签: python python-3.x pygame sprite-sheet