samedi 12 juin 2021

How to make the object bounce back with turtle

I want to make the yellow block jump on the line when there are other shapes. Also, how could I make the screen to close when the yellow block touches the other blocks.

I have though about using the time module and put time.sleep for 1 seconds after blockself.goto(0,30) then make the block go down to (0,0). However, when I did that the whole screen frozed for 1 second. This means that the time.sleep was not aimed for the blockself(yellow block) it self. Is there any way to fix this.

from turtle import Screen, Turtle
import random

WIDTH, HEIGHT = 800, 400
CURSOR_SIZE = 20
BASELINE = -CURSOR_SIZE/2

def move_block(block):
    block.x -= CURSOR_SIZE/2
    block.setx(block.x)

if block.x <= CURSOR_SIZE/2 - WIDTH/2:
    block.x += WIDTH + CURSOR_SIZE
    block.setx(block.x)

screen.update()
screen.ontimer(lambda: move_block(block), 40)  # delay in milliseconds

screen = Screen()
screen.title("Jump over!")
screen.setup(WIDTH, HEIGHT)
screen.tracer(False)

marker = Turtle()
marker.hideturtle()
marker.penup()
marker.goto(WIDTH/2, BASELINE)
marker.pendown()
marker.goto(-WIDTH/2, BASELINE)

#three blocks
shape1=["square","triangle","circle"]
block_1 = Turtle(shape=(random.choice(shape1)))
block_1.up()
block_1.color('black')
block_1.x = WIDTH/2 + CURSOR_SIZE  # user defined property
block_1.setx(block_1.x)

shape2=["square","triangle","circle"]
block_2 = Turtle(shape=(random.choice(shape2)))
block_2.up()
block_2.color('black')
block_2.x = block_1.x + 300
block_2.setx(block_2.x)

shape3=["square","triangle","circle"]
block_3 = Turtle(shape=(random.choice(shape3)))
block_3.up()
block_3.color('black')
block_3.x = block_2.x + 300
block_3.setx(block_3.x)

move_block(block_1)
move_block(block_2)
move_block(block_3)

# self
blockself= Turtle(shape="square")
blockself.color('yellow')
blockself.setx(0)

blockself.direction="Stop"
def goup():
    blockself.up()
    blockself.goto(0,30)

screen.listen ()
screen.onkey ( goup , "w" )

screen.mainloop()

Aucun commentaire:

Enregistrer un commentaire