[Tutor] misunderstanding "any"
col speed
ajarncolin at gmail.com
Wed Mar 7 04:24:22 CET 2012
Hello again
Hope you are all well.
I'm trying to make a "match 3" game, where you have a square grid and
have to put 3 matching shapes in a row.
I need a function that tells me if the game is playable, ie. it is
possible to match 3 shapes by only swapping 2 adjacent shapes.
I have looked at the co-ordinates and got a list of the "offset
co-ordinates" needed for the above.
I have a list of coordinates and a list of "lemons" and I want to see
if *any* lemon coordinate is in the list of coordinates.
I tried this:
if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1 ))) in fruit_type:
return True
Thinking that if *any* of the tuples is in fruit_type(a list of
tuples), then it should return True.
However, it always equates to False.
If I iterate through the tuples and see if any are in fruit_type, it
returns True (when it should).
I have tried many print statements to make sure what is happening, and
also to make sure that I am comparing type<tuples>.
I just wondered what it is that I'm misunderstanding, or what I've done wrong.
Here is the whole programme for completeness:
#!usr/bin/env python
import random
class Gem(object):
def __init__(self, x, y, fruit):
self.x = x
self.y = y
self.fruit = fruit
gems = []
x, y = 0, 0
fruits = ["lemon", "banana", "apple", "pineapple", "mango"]
for gem in range(81):
gems.append(Gem(x, y, random.choice(fruits)))
x += 1
if x >= 9:
x = 0
y += 1
def game_on(fruits):
for fruit in fruits:
fruit_type = [(gem.x, gem.y) for gem in gems if gem.fruit == fruit]
for x, y in fruit_type:
if (x-1, y+1) in fruit_type:
if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1
))) in fruit_type:
return True
elif (x-1, y-1) in fruit_type:
if any(((x+1, y-1), (x-2, y-1),(x-1, y+1),(x-1, y-2)))
in fruit_type:
return True
elif (x+1, y+1) in fruit_type:
if any(((x+2, y+1), (x+1, y-1),(x+1, y+2),(x-1, y+1)))
in fruit_type:
return True
elif (x+1, y-1) in fruit_type:
if any(((x+1, y+1), (x+1, y-2),(x+2, y-1),(x-1, y-1)))
in fruit_type:
return True
elif (x-2, y+1) in fruit_type:
if (x-1, y+1) in fruit_type:
return True
elif (x-2, y-1) in fruit_type:
if (x-1, y-1) in fruit_type:
return True
elif (x-1, y-2) in fruit_type:
if (x-1, y-1) in fruit_type:
return True
elif (x+1, y-2) in fruit_type:
if (x+1, y-1) in fruit_type:
return True
return False
print game_on(fruits)
And here;s a typical printout:
mango
[(3, 0), (0, 1), (3, 1), (5, 1), (6, 1), (8, 1), (1, 2), (2, 2), (5,
2), (1, 4), (4, 4), (6, 4), (2, 5), (4, 5), (5, 5), (2, 6), (3, 6),
(3, 8)] <type 'tuple'># fruit_type and type(fruit_type[2])
got (3, 1), and (2, 2)
(4, 2), (2, 3), (1, 2), (2, 0).If any of these are in fruit type, we
have a match
(1, 2) <type 'tuple'> It's in.# this is from iterating over the tuples
and making sure they are type tuple. We have a match.
##many more matches found###
False # the return from the function
Thanks a lot
Col
More information about the Tutor
mailing list