I want to move the ball to square one and limit the number of repetitions to five

Asked 2 years ago, Updated 2 years ago, 128 views

import turtle

screen=turtle.Screen()

image1="D:\\ball.gif"

screen.addshape(image1)

ball=turtle.Turtle()

ball.shape(image1)

ball.pensize(0)

ball.penup()

ball.goto(0, 0)

ball.left(90)



def go_left():
       b1 = 0
       ball.left(45)
       ball.forward(220)

def go_up():
       b1= 1
       ball.forward(190)

def go_right():
       b1 = 2
       ball.right(45)
       ball.forward(220)


screen.onkeypress(go_left,"Left")

screen.onkeypress(go_right,"Right")

screen.onkeypress(go_up,"Up")

screen.listen()

When you run it, the ball moves, and then it moves in that position, not back to square one How can I start from scratch? And I want to stop when the number of games reaches 5, but I don't know how to make a repeat statement Help!

python loops turtle

2022-09-21 19:04

1 Answers

At this point, of course, the ball doesn't come back to square one. There is no definition of "back to square one" in the source.

First of all, if you want to do something, you might want to define this function as an additional definition:

def return_to_origin() :
    ball.goto(0, 0)

Use this appropriately in function definitions such as go_left() and go_up(). For example, if the user moves the ball and then has to move again within 5 seconds:

# I haven't tested it. Just refer to the idea.
import time

# "The last time the user moved the ball". Set the program execution point as the default.
last_time_user_moved = time.time()

# If you want to move the ball to the left...
def go_left():
    # It should not be more than 5 seconds since the last time the user moved the ball
    now = time.time()
    if now - last_time_user_moved < 5 :
        b1 = 0
        ball.left(45)
        ball.forward(220)
        Last_time_user_moved = now # Don't forget to fix the 'last time the user moved the ball' after finishing the ball's movement
    # If five seconds have passed, it will be returned to square one without any effort.
    else :
        return_to_origin()

I don't know what the number of runs is, but I think you can do it roughly with these flag variable ideas. Good luck.


2022-09-21 19:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.