简体   繁体   中英

Trying to get borders to my python turtle module game

I am trying to make this game where once you hit the borders of the box the turtle will return to the position it was at directly before it hit the border of the box. I am pretty new so any help would be appreciated. So far I have if y cord is greater than the box it goes back to right before it hit but it doesn't seem to be working.

import turtle
wn = turtle.Screen()
wn.bgcolor('black')
line = turtle.Turtle()

line.goto(-450,-15)
line.speed(9999)
line.pendown
line.color('white')
line.forward(850)
line.left(90)
line.forward(400)
line.left(90)
line.forward(850)
line.left(90)
line.forward(410)
line.color('black')


fred = turtle.Turtle()
fred.penup()
fred.goto(-430, 0)
fred.shape('square')
fred.color('white')
fred.penup()
fred.delay = 0.1
fred.direction = "Stop"


#Set Up (Controls)
wn.listen()


def ahead():
    fred.forward(10)


def behind():
    fred.backward(10)


if fred.ycor() < -500:
    fred.goto(0, -500)

if fred.ycor() > 500:
    fred.goto(0, 500)


wn.onkey(behind,"a")
wn.onkey(ahead,"d")
wn.mainloop()

You should use if inside functions - and values in if you may have to calculate manually.

def ahead():
    fred.forward(10)
    #print(fred.xcor())

    if fred.xcor() > 430 - 50: # minus turtle width
        fred.backward(10)

def behind():
    fred.backward(10)
    #print(fred.xcor())

    if fred.xcor() < -430 :
        fred.forward(10)

But problem will be if you will have more elements which should stop turtle.

turtle doesn't have function to detect collisions and you may have to access tkinter functions for this or you would have to create own function which checks xcor , ycor with coordinates from some list. And list should have coordinates for all objects. And this may need to calculate coordinates manually.


turtle is nice for drawing figures but not for games. There are better modules - like PyGame , Arcade , PGzero ( PyGame Zero )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM