Speed function doesn't change the turtles position regardless of any parameters I put in

前端 未结 1 640
野的像风
野的像风 2021-01-27 01:46

The program I made has two turtles one being the user(player) and the other being player 2 which are run through a function called checkcollision which determines if the turtles

相关标签:
1条回答
  • 2021-01-27 02:02

    Your code has multiple problems and I'm surprised it runs at all as presented above. (It should just fall through the bottom of the code, close the turtle window and return to the console.) For example, it doesn't seem to understand it's own coordinate system -- the x coordinates go from -425 to +425 but we're testing if the turtle's x coordinate is <= -625. Below is my rework to address your question and these other issues:

    from turtle import Screen, Turtle
    from random import randint
    
    def up():
        y = player.ycor() + 5
    
        if y < 200:
            player.sety(y)
            checkcollision()
    
    def down():
        y = player.ycor() - 5
    
        if y > -200:
            player.sety(y)
            checkcollision()
    
    def left():
        x = player.xcor() - 5
    
        if x > -200:
            player.setx(x)
            checkcollision()
    
    def right():
        x = player.xcor() + 5
    
        if x < 200:
            player.setx(x)
            checkcollision()
    
    def checkcollision():
        if player.distance(player2) < 20:
            player2.setpos(randint(-200, 200), randint(-200, 200))
    
    screen = Screen()
    screen.setup(width=450, height=450)
    screen.bgcolor('green')
    
    player = Turtle()
    player.shape('square')
    player.speed('fastest')
    player.penup()
    
    player2 = Turtle()
    player2.shape('square')
    player2.speed('slowest')
    player2.color('yellow')
    player2.penup()
    
    checkcollision()
    
    screen.onkeypress(up, 'Up')
    screen.onkeypress(left, 'Left')
    screen.onkeypress(right, 'Right')
    screen.onkeypress(down, 'Down')
    screen.listen()
    
    screen.mainloop()
    
    0 讨论(0)
提交回复
热议问题