Skip to content Skip to sidebar Skip to footer

Get Coordinates Of "treasure" (turtles) In Maze Game That Uses Python Tkinter And Turtle

I am using Python 3 to make a maze using tkinter and turtle graphics. Most of the code works, except I cannot figure out how to 'destroy' the 'gold' in the game. Specifically, call

Solution 1:

Your immediate problem is this:

if player.collision(question):

defcollision(self, other):
    # ...
    a = tur2.xcor() - other.xcor()

You call collision() with question as it's second argument and the function assumes that the second argument is a turtle when it invokes .xcor() on it. But it isn't a turtle, it's a Question instance that contains a turtle.

The larger problem is that your program is a complete misunderstanding of classes, instances and globals. Consider the pen instance of the Pen class -- you create it and ignore it as it's work is done by the global tur you created as a side-effect! This sort of thing recurs throughout your program. And it's clear you don't understand the global keyword so I suggest your (re)read about that.

I've reworked your program below to fix many, but not all, of the problems I saw. The classes Pen, Player, and Question are now subclasses of RawTurtle, rather than containing one. And no globals are set via side-effect. Your gold now disappears when you reach it and your can use the arrow keys (just click on the window first.)

from turtle import RawTurtle, TurtleScreen
import tkinter

# Create Pen class to draw the maze.classPen(RawTurtle):
    def__init__(self):
        super().__init__(screen, shape='square')
        self.speed('fastest')
        self.color('white')
        self.penup()

    # Create setup so the maze will be drawn.defsetup(self, level):
        for y inrange(len(level)):
            screen_y = 288 - (y * 24)

            for x inrange(len(level[y])):
                if level[y][x] == 'X':
                    screen_x = (x * 24) - 288

                    self.goto(screen_x, screen_y)
                    self.stamp()

                    walls.append((screen_x, screen_y))

# Create player class to have a player.classPlayer(RawTurtle):
    def__init__(self):
        super().__init__(screen, shape='square')
        self.speed('fastest')
        self.color('blue')
        self.penup()

    # Create setup to create the player on the screen.defsetup(self, level):
        for y inrange(len(level)):
            for x inrange(len(level[y])):
                if level[y][x] == 'P':
                    screen_x = (x * 24) - 288
                    screen_y = 288 - (y * 24)

                    self.goto(screen_x, screen_y)

                    return# Define a function that will allow player to move up.defmove_up(self):
        # Calculate the spot to move to.
        movetoX = self.xcor()
        movetoY = self.ycor() + 24# Check if the space has a wall.if (movetoX, movetoY) notin walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Define a function that will allow player to move down.defmove_down(self):
        # Calculate the spot to move to.
        movetoX = self.xcor()
        movetoY = self.ycor() - 24# Check if the space has a wall.if (movetoX, movetoY) notin walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Define a function that will allow player to move left.defmove_left(self):
        # Calculate the spot to move to.
        movetoX = self.xcor() - 24
        movetoY = self.ycor()

        # Check if the space has a wall.if (movetoX, movetoY) notin walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Define a function that will allow player to move right.defmove_right(self):
        # Calculate the spot to move to.
        movetoX = self.xcor() + 24
        movetoY = self.ycor()

        # Check if the space has a wall.if (movetoX, movetoY) notin walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Check if player touches the question.defcollision(self, other):
        return self.distance(other) < 5# Create Question class to create the "gold" in the game.classQuestion(RawTurtle):
    def__init__(self, x, y):
        super().__init__(screen, shape='circle', visible=False)

        self.speed('fastest')
        self.color('gold')
        self.penup()
        self.goto(x, y)
        self.showturtle()

    # Define function that will remove gold when collided with.defdestroy(self):
        self.hideturtle()

# Define function to setup the "gold" in the game.defsetup(level):
    for y inrange(len(level)):
        for x inrange(len(level[y])):
            char = level[y][x]

            screen_x = -288 + (x * 24)
            screen_y = 288 - (y * 24)

            if char == 'Q':
                questions.append(Question(screen_x, screen_y))

# Define a function for the quit button.defquitPlaying():
    root.destroy()
    root.quit()

# Game loop in regards to the gold.defgold_encounter():
    # Check for player collision with a question.# Iterate through the questions list.for question in questions:
        if player.collision(question):
            # Destroy the question.
            question.destroy()
            # Remove question from questions list.
            questions.remove(question)

# Create window and canvas using tkinter.
root = tkinter.Tk()
root.title("Language Labyrinth")

canvas = tkinter.Canvas(root, width=600, height=600)
canvas.pack()

screen = TurtleScreen(canvas)
screen.bgcolor('black')

# Create frame where button(s) will be.
frame = tkinter.Frame(root)
frame.pack()

# Add questions list.
questions = []

# Wall coordinate list.
walls = []

# Create a levels list.
levels = []

# Define first level.
level_1 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XP XXXXXXX          XXXXX",
"X  XXXXXXX  XXXXXX  XXXXX",
"X       XX  XXXXXX  XXXXX",
"X       XX  XXX        XX",
"XXXXXX  XX  XXX   Q    XX",
"XXXXXX  XX  XXXXXX  XXXXX",
"XXXXXX  XX    XXXX  XXXXX",
"X  XXX Q      XXXX  XXXXX",
"X  XXX  XXXXXXXXXXXXXXXXX",
"X         XXXXXXXXXXXXXXX",
"X     Q          XXXXXXXX",
"XXXXXXXXXXXX     XXXXX  X",
"XXXXXXXXXXXXXXX  XXXXX  X",
"XXX  XXXXXXXXXX         X",
"XXX               Q     X",
"XXX         XXXXXXXXXXXXX",
"XXXXXXXXXX  XXXXXXXXXXXXX",
"XXXXXXXXXX              X",
"XX   XXXXX        Q     X",
"XX   XXXXXXXXXXXXX  XXXXX",
"XX    XXXXXXXXXXXX  XXXXX",
"XX    Q     XXXX        X",
"XXXX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

# Add the level(s) to the levels list.
levels.append(level_1)

# Class instances.
pen = Pen()
pen.setup(level_1)
player = Player()
player.setup(level_1)
setup(level_1)

# Creation of quit button.
quitButton = tkinter.Button(frame, text='Quit', command=quitPlaying)
quitButton.pack()

screen.onkeypress(player.move_up, 'Up')
screen.onkeypress(player.move_down, 'Down')
screen.onkeypress(player.move_left, 'Left')
screen.onkeypress(player.move_right, 'Right')

screen.listen()

# Call main game loop.
screen.mainloop()

You seem to get very little out of embedding turtle in tkinter and this might have been cleaner left a standalone turtle program. And since your various setup*() methods/functions never got called, your posted code doesn't really do anything.

Post a Comment for "Get Coordinates Of "treasure" (turtles) In Maze Game That Uses Python Tkinter And Turtle"