Reputation: 187
I'm developing a game in pygame where enemy ships will begin off screen then move vertically on the Y-axis towards the player.
However, I'm having a bit of trouble accessing the location of the enemy since it's all relative to a range. I'm not exactly too sure of how to explain it, but here's what I have for the Enemy Class:
class EnemyActive(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
enemy_img_list = ['enemyshipone.png', 'enemyshiptwo.png',
'enemyshipthree.png','enemyshipfour.png']
enemy_img = random.choice(enemy_img_list)
self.image = pygame.image.load(enemy_img)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0,400)
self.rect.y = random.randrange(-200,-10)
self.speed = random.randrange(1,3)
def update(self):
self.rect.y += self.speed
def getCoord(self):
return (self.rect.x, self.rect.y)
So, when I try to access the position using another function, which takes in an (x,y) coordinate:
particle_list = particles.create_particles(particle_list,enemy.getCoord())
It comes back with an error stating:
numbers = range(-5, -1) + range(1, 5)
TypeError: unsupported operand type(s) for +: 'range' and 'range'
I'm not going to lie and say that I fully understand the error, but I do see logic behind the reasoning for it. How can I actually get my 'getCoord' function to send the appropriate coordinates?
Upvotes: 1
Views: 686
Reputation: 498
In python 3, range
is an lazy sequence, not a list. That is, it produces the values one at a time like a generator(lazy), when asked for, rather than storing them all in memory at once (eageR).
You can't add ranges together because they don't have the method for + defined. list
does: it concatenates.
We can convert range to a list by calling the list class on it. I.e, list(range(1, 5))
.
You can either construct two lists and then concatenate them with +, or you can chain together the generators and then create a single list. This is considered better style since it avoids creating an intermediate list.
Eg:
from itertools import chain
my_list = list(chain(range(-5, -1), range(1, 5)))
Upvotes: 3