Can't compare tuples in 'if statement'
Posted by Foxington_the_First@reddit | learnprogramming | View on Reddit | 4 comments
Hi all,
I am writing a simple game in Python using the turtle library.
I want things to happen when a turtle I set to move randomly comes into contact with the turtle the player can manually control.
I was hoping to compare positions and say things like:
"if difference between x values is less than [amount] and difference between y values is less than [amount]:
then thing will happen."
The problem is turtle.pos() spits out a tuple (0.0, 0.0), so I can't directly compare them to find the difference. When I write this line of code:
difference = dragon.pos() - enemy.pos()
Error
TypeError: unsupported operand type(s) for Sub: 'tuple' and 'tuple' on line 44 in main.py
What is the best way to unpack the tuple so it can be compared? I tried using square bracket indexing to little avail.
Thanks!
hennipasta@reddit
aqua_regis@reddit
You could just as well unpack the tuples. Consider the following:
Think about how you could use that in your code.
teraflop@reddit
Square bracket indexing is exactly what you need.
You said what you want to do is:
The x values are
dragon.pos()[0]
andenemy.pos()[0]
, so you can just subtract them to find the difference. And likewise for the y values which are at index 1.Foxington_the_First@reddit (OP)
Oh great! I see the issue, I was putting the square brackets as an argument in the method for some reason. I will try with this syntax. Much appreciated!