[SOLVED] How to check if turtle is on stamp position

Issue

This Content is from Stack Overflow. Question asked by Yfreet

I am new to python and trying to build a simple game. In the game is just one ant and this ant follows simple rules: if ant is on white field, he paints the tile black( or other color), turns right, moves forward. If ant is on colored tile – remove color, turn left, move forward.
Currently I am trying to do this with turtle and stamps. Stamp ID and coordinates are stored in a dict, a loop is checking if ant position is in dict keys and there is the problem: when the ant moves to the same position, where the first stamp is, this check return False and the ant never escape the loop.

from turtle import Turtle, Screen

screen = Screen()
screen.setup(height=900, width=1000)
screen.title("The Ant")
ant = Turtle()
ant.color("brown")
ant.pencolor("black")
ant.penup()
kleks_liste = {}
game_running = True

ant.shape("square")
ant.setpos(5, 5)
kleks_liste[ant.pos()] = ant.stamp()
ant.shape("classic")
ant.forward(20)


while game_running:
    pos_key = ant.pos()
    if pos_key in kleks_liste.keys():
        ant.clearstamp(kleks_liste[pos_key])
        kleks_liste.pop(pos_key)
        ant.left(90.00)
        ant.forward(20.00)
    else:
        ant.right(90.00)
        ant.shape("square")
        kleks_liste[pos_key] = ant.stamp()
        ant.shape("classic")
        ant.forward(20.00)

screen.exitonclick()

What am I doing wrong? If I comment out “ant.forward” in the “else” section, the check works and returns True. Can someone explain the behavior?



Solution

The Vec2D returned by pos() contains floats which need to be compared with an epsilon. One workaround is to cast these values to integers, either with int or round. This shouldn’t lose accuracy since you’re working on a grid.

Instead of pos_key = ant.pos(), try pos_key = tuple(map(int, ant.pos())). Don’t forget to change the first stamp key outside the loop too.

As an aside, you can use if pos_key in kleks_liste: without .keys().


This Question was asked in StackOverflow by Yfreet and Answered by ggorlen It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?