【发布时间】:2019-06-05 17:02:44
【问题描述】:
我想知道是否可以在 pygame 中将 pygame.draw.rect() 函数与类中的颜色变量一起使用。
这是我的代码,其中包含详细说明: (注意我只取有用的部分)
# consider pygame as 'pg' as I set with
# the line 'import pygame as pg'
class icon:
def __init__(self, picture, position, key):
self.icon = picture
self.position = position
self.p_x, self.p_y = position
self.size = 50
self.unlocked = False
self.key = key
self.status = 'off'
self.pulse_value = 0
self.pulse = 'down'
self.pulse_type = 'red'
self.c_icon = self.icon.get_rect()
self.c_icon.center = ( (self.p_x + 25), (self.p_y + 25))
def unlock(self):
self.unlocked = True
self.status = 'pulse'
self.pulse_type = 'grey'
def draw(self):
if self.unlocked == True :
if self.status == 'off':
pg.draw.rect(screen, color_passive, (*self.position, 50, 48))
elif self.status == 'on':
pg.draw.rect(screen, color_active, (*self.position, 50, 55))
elif self.status == 'pulse':
if self.pulse == 'down' :
self.pulse_value = self.pulse_value + 1
if self.pulse_value == 255 :
self.pulse = 'up'
elif self.pulse == 'up' :
self.pulse_value = self.pulse_value - 1
if self.pulse == 0 :
self.pulse = 'down'
if self.pulse_type == 'red' :
self.color_pulse = (self.pulse_value, 0, 0)
elif self.pulse_type == 'grey' :
self.color_pulse = (self.pulse_value, self.pulse_value, self.pulse_value )
pg.draw.rect(screen, *self.color_pulse, (*self.position, *self.size))
screen.blit(self.icon, self.c_icon)
world_2 = pg.image.load('ice_mountains.png').convert_alpha()
icon_1 = icon('world_2', (60, 60), K_1)
这是类图标,它显示屏幕上的任何选项卡图标并定义选项卡是否解锁。
如你所见,我在这里使用了一个函数pygame.draw.rect()
但是在这个函数中,颜色变量是一个“类变量”( self.color_pulse)。
变量self.color_pulse由上面一行的( self.pulse_value, self.pulse_value, self.pulse_value)定义。
而self.pulse_value 是一个类变量,每个icon_2.draw() 以每秒30 次的速度增加5。
基本上,我在主循环中使用函数icon_2.draw()。
elif exp >= 1000:
n_unlock = n_unlock + 1
icon_2.unlock()
print('world 2 unlocked')
这是解锁图标的代码。当主循环在这个解锁之后执行icon_2.draw()时,预期的结果是图标应该出现在屏幕上,defaul..ulse直到用户点击它。
但是,不幸的是,我得到了这个:
#----------*={ _MAD_ }=*----------#
May Avoid Destruction
by Edhyjox
#----------*={ _MAD_ }=*----------#
Loading...
========== Ok
custom setting succesfully imported
Window main not existing, redirect to game
World 2 unlocked
Traceback (most recent call last):
File "************************/___MAD___/script/MAD - The game.py", line 266, in <module>
icon_2.draw()
File "************************/___MAD___/script/MAD - The game.py", line 190, in draw
pg.draw.rect(screen, *self.color_pulse, (*self.position, *self.size))
TypeError: 'int' object is not iterable
我真的不知道为什么会出现这个错误。这意味着我在函数pg.draw.rect()中使用了'int',但变量self.color_pulse在程序的这一点上是(5, 5, 5)。
而且它似乎适用于不在类中的变量...... 有人知道这个问题的线索吗?
【问题讨论】:
-
对不起语言错误,我努力改进:D