pygame: ValueError: too many values to unpack(expected 2)

Viewed 75

I'm currently studying Python and pygame, trying to make a sample simulation for a shooting game.

Usually, when dealing with a missile or bullet projection, I heard using list is the most common way to control the movement.

like

missile = []
missile1X = fighterx + fighterWidth
missile1Y = fightery + fighterHeight / 2
missile.append([missile1X, missile1Y])

I'm trying to put additional information about a bullet like 'kind of weapons', but only to have a result of

ValueError: too many values to unpack(expected 2).

This is what I was trying to do: adding more information on elements of the list, I want to change the kind of weapons that fighters use.

The code below is what I thought would work...

missile1 = pygame.image.load('missile1.png')
missile2 = pygame.image.load('missile2.png')
missileX = 100
missileY = 100
if weapon_num % 2 == 1:
    missile = missile1
if weapon_num % 2 == 0:
    missile = missile2
missileXY.append([missile1X, missile1Y, missile])

Question is,

  1. Would it be possible to put additional one like above?

  2. Is there any other way to execute what I want?

  3. Any other caution I might face?

1 Answers

As the exception says, there is an issue with unpacking your list. Only two elements in the inner list are expected, but you're providing three. As mentioned in the last paragraph of this section of the Python documentation:

Sequence unpacking requires that there be as many variables on the left side of the equals sign as there are elements in the sequence.

In this line of code...

for bx, by in missile1XY:

... you're attempting to unpack the inner list (in this case the [missile1X, missile1Y, missile], which contains three elements). The interpreter expects the list to contain exactly two elements, hence the exception thrown.

Would it be possible to put additional one like above?

Yes, you'll just need to modify the code unpacking the list, e.g.:

for bx, by, type in missile1XY:
    drawObject(type, bx, by)

Is there any other way to execute what I want?

If needed, you could in theory iterate over the inner list in the same manner you iterate over the top list. That way you'll be able to accept an arbitrary number of elements, but it will require further changes to the program logic and I believe it'll make things more complicated, than anything.

Any other caution I might face?

I'd recommend reading through the Python documentation on data structures. Also if you're taking your code from elsewhere while learning, it's good to try to read and understand it completely before using it - might save you a headache when trying to solve an unexpected behavior. Good luck in your studies!

Related