Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python turtle returning varibles from coords

Is there a way to recall preset lines of code depending on the turtle's position?

I've tried using turtle.pos() and xcor/ycor but I can't get it to recall the code.

I have tried: if turtle.pos == (0.00,50.00): combat()

I am new to Python turtle.

import turtle

GRID_UNIT = 50
GRID_SIZE = 5  # code below assumes this is an odd number

####################################################################
def Combat():
print('You encounter a raverous Spider! do you wish to fight it?')
Fight = str(input())
if Fight == 'Yes':
    #########Battle Code Warrior############
    import random
    import time


    While_Loop = 1
    ###########Battle 1############
    print('============================================')
    while While_Loop == 1:
            if Foe >= 0:
                time.sleep(1)
                print('You did', Player_Dmg,'Dmg')
                Foe = Foe - Player_Dmg # checks health remaining
                print('Your Foe has ',Foe,'Hp left')
                print('=============================')
                time.sleep(0.5)
                Player_Dmg = random.randrange(0,10)
                if Foe <= 0:
                    print('You killed it')
                    break

                else:
                    time.sleep(1)
                    if life >= 0:
                        life = life - Foe_Dmg
                        print('You took ', Foe_Dmg,'Dmg')
                        print('You Have', life, 'Hp left')
                        print('=============================')
                        time.sleep(0.5)
                        Foe_Dmg = random.randrange(0, 10)
                        if life <= 0:
                            print('You are dead')

            else:
                print('You die')
                life = 0
                break

elif Fight == 'No':
    print('You Sprint Frantically away from the spider while it chases  you down!')    
def Map_Starting_Area():

turtle.pu()
turtle.goto(-GRID_SIZE/2 * GRID_UNIT, -GRID_SIZE/2 * GRID_UNIT)
turtle.ht()
turtle.pd()

####### Grid ###########

for _ in range(GRID_SIZE // 2):
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.right(90)
    turtle.forward(GRID_UNIT)
    turtle.right(90)

turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.left(90)

for _ in range(GRID_SIZE // 2):
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.right(90)
    turtle.forward(GRID_UNIT)
    turtle.right(90)

turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.pu()
turtle.left(90)
turtle.fd(75)
turtle.left(90)
turtle.fd(25)
###############################################################
# Square = Town
# Circle = Fight
# Arrow = Quest Marker
# Turtle = Weapon Shops
# Triangle = Potion Shop
# Hollow Circle = Chest
turtle.shape('square')
turtle.stamp()
turtle.fd(50)
turtle.right(90)
turtle.fd(50)
turtle.shape('circle')
turtle.stamp()
turtle.back(50)
turtle.left(90)
turtle.fd(50)
turtle.left(90)
turtle.fd(50)
turtle.shape('circle')
turtle.stamp()
turtle.back(50)
turtle.right(90)
turtle.fd(50)
turtle.right(90)
turtle.fd(50)
turtle.shape('circle')
turtle.stamp()
turtle.fd(100)
turtle.shape('square')
turtle.stamp()
turtle.rt(90)
turtle.fd(140)
turtle.rt(90)
turtle.pd()
turtle.circle(10)
turtle.pu()
turtle.fd(150)
turtle.right(90)
turtle.back(10)



###############################################################    
turtle.st()
###############################################################

turtle.speed('fastest')

Map_Starting_Area()

turtle.color('orange')
turtle.shape('classic')

 print('You Continue with your Journey')
 print('You leave the protection of your farm and head into the open land')
print('You Come to a cross road')

while True:
    direction = input('Would you like to go North, South, East or West: ').lower()

if direction == 'north' and turtle.ycor() < GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.sety(turtle.ycor() + GRID_UNIT)
    turtle.update()
elif direction == 'south' and turtle.ycor() > -GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.sety(turtle.ycor() - GRID_UNIT)
    turtle.update()
elif direction == 'east' and turtle.xcor() < GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.setx(turtle.xcor() + GRID_UNIT)
    turtle.update()
elif direction == 'west' and turtle.xcor() > -GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.setx(turtle.xcor() - GRID_UNIT)
    turtle.update()
elif direction == 'quit':
    break
if turtle.pos == (0.00,50.00):
    combat()
like image 696
Luke Burton Avatar asked May 28 '26 08:05

Luke Burton


1 Answers

There were a number of problems in your code which I've hopefully fixed:

#the imports are now all at the start - this is generally considered the way to go
import turtle
import random
import time

#constant declarations
GRID_UNIT = 50
GRID_SIZE = 5

HALF_GRID = GRID_SIZE // 2

SPIDER_LOCATIONS = [(1, 1),
                    (-1, 0)]

TREASURE_LOCATIONS = [(1, -2),
                      (-2, -1)]

TOWN_LOCATIONS = [(-2, -2),
                  (2, -2),
                  (-2, 2),
                  (2, 2)]

#simplified event functions
def combat():
    print("You stepped on a spider!")

def treasure():
    print("You found treasure!")

def town():
    print("You entered a town")

#scaled setpos for use with int grid coords
def grid_setpos(x, y, scale):
    turtle.setpos((x - 0.5) * scale, (y - 0.5) * scale)

#draw a grid
def draw_grid(size, unit):
    for x in range(-size // 2, size // 2 + 1):
        turtle.pu()
        turtle.setpos(x * unit, -size // 2 * unit)
        turtle.pd()
        turtle.setpos(x * unit, size // 2 * unit)

        turtle.pu()
        turtle.setpos(-size // 2 * unit, x * unit)
        turtle.pd()
        turtle.setpos(size // 2 * unit, x * unit)

#draw the map, iterating over stored global coordinates
def map_starting_area(size, unit):
    draw_grid(size, unit)

    # square = town
    # circle = fight
    # arrow = quest marker
    # turtle = weapon shops
    # triangle = potion shop
    # hollow circle = chest

    turtle.shape("circle")
    turtle.pu()

    for x, y in SPIDER_LOCATIONS:
        grid_setpos(x, y, unit)
        turtle.stamp()

    for x, y in TREASURE_LOCATIONS:
        turtle.pu()
        grid_setpos(x, y - 0.25, unit)
        turtle.pd()
        turtle.circle(unit // 4)

    turtle.shape("square")
    turtle.pu()

    for x, y in TOWN_LOCATIONS:
        grid_setpos(x, y, unit)
        turtle.stamp()

turtle.speed('fastest')

map_starting_area(GRID_SIZE, GRID_UNIT)

turtle.color('orange')
turtle.shape('classic')

print('you continue with your journey')
print('you leave the protection of your farm and head into the open land')
print('you come to a cross road')

turtle.showturtle()

turtle_x, turtle_y = 0, 0

grid_setpos(0, 0, GRID_UNIT)

while True:
    direction = input('would you like to go north, south, east or west: ').lower()

    if direction == 'north':
        if turtle_y < HALF_GRID:
            turtle_y += 1
        else:
            print("You hit a wall")

    elif direction == 'south':
        if turtle_y > -HALF_GRID:
            turtle_y -= 1
        else:
            print("You hit a wall")

    elif direction == 'east':
        if turtle_x < HALF_GRID:
            turtle_x += 1
        else:
            print("You hit a wall")

    elif direction == 'west':
        if turtle_x > -HALF_GRID:
            turtle_x -= 1
        else:
            print("You hit a wall")

    elif direction == 'quit':
        break

    grid_setpos(turtle_x, turtle_y, GRID_UNIT)

    if (turtle_x, turtle_y) in SPIDER_LOCATIONS:
        combat()

    if (turtle_x, turtle_y) in TOWN_LOCATIONS:
        town()

    if (turtle_x, turtle_y) in TREASURE_LOCATIONS:
        treasure()

The main point being addressed: How to "trigger" an event when a turtle hits a certain location. I've approached this by a number of changes to your code:

Firstly, as your turtle will always be on a grid, I'm tracking turtle_x and turtle_y separately from the turtle, as integers. This is important, as integers can be properly tested for equality. When the turtle is at a floating point location, it might not actually be possible to check if it is at a specific point. Each cell in the grid is one coordinate in the range -HALF_GRID to HALF_GRID, and the position is discretely changed by 1 or -1. Now you also need to know where each "event" is. I've done this by storing the locations of a number of events in global constant lists at the start of the file. By the way, I've also changed your map-drawing methods to use iteration over these lists, and for-loops for the grid drawing, as this was a lot clearer (it made the code easier to read and therefore debug for me, as well as being shorter). I hope you'll agree that map_starting_area is now easier to follow. As the coordinates being tracked are now integers, they need to be 'scaled up' whenever setpos is called. I've done this by writing a helper function grid_setpos, for setting position in a grid.

In short, it now stores a pair of integers to use as the turtles position, so it can test if anything is equal to then. It then does some maths with the turtle (scales each coordinate up by GRID_UNIT) to map the integer coordinates back onto the grid.

Previously, the turtle's coordinates were floating point. This means they were 'decimal' numbers (this is close enough to correct that it doesn't matter). However, as you were on a grid, you don't actually need a decimal number. Co-ordinates on a grid are discrete (whole numbers). Therefore, the co-ordinates are now being stored as whole numbers. This means it's possible to test if they're exactly equal. It also uses a list of coordinates of spiders, and uses some quick Python to see if the current coordinates are in this list: if (turtle_x, turtle_y) in SPIDER_LOCATIONS:.

I've simplified your methods for dealing with events (combat(), town(), treasure()) to a point where they demonstrate they're working, as that was all that was necessary for this question. You can expand on each of them to expand your game.

I've also changed your variable names. In Python, it's generally convention to use underscore_case, or maybe camelCase for variables and functions, but never CapitalCase (as this is for classes), and Capital_Underscore_Case is almost never used, to my knowledge.

Minor changes:

  • Import statements are now all at the top
  • Separated grid logic from map logic
  • Some other bugs to do with when you were hiding/showing the turtle

If you want to generalise this more, and have different locations, different properties for events, etc I'd advise you to start writing some classes (with attributes such as x, y, and maybe instance methods like encounter. It's outside of the scope of this question (equality testing with turtle coordinates) to go into much, but there are many tutorials on Python classes and their uses. I'd advise you to start simple and build up to integration with this project. If you get really stuck with your class implementation, you can of course always ask another question.

In response to your comment: it is generally not advised to create separate variables for eg each town. Lists are for when you have lots of a thing that needs to behave the same. Imagine if you had 50 towns, all in separate variables. If you want each town to keep track of a name/have different events, etc, refer to my section about classes. You'll need a list of Town instances, after acquainting yourself better with OO programming. If you get really confused about classes after trying to use them, post a specific question about your problem together with what you've got so far

like image 161
Izaak van Dongen Avatar answered May 30 '26 22:05

Izaak van Dongen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!