简体   繁体   English

试图为我的 python 乌龟模块游戏设置边界

[英]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.我正在尝试制作这个游戏,一旦你碰到盒子的边界,乌龟就会返回到它到达盒子边界之前的 position。 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.到目前为止,如果 y 线大于盒子,它会在击中之前返回到正确位置,但它似乎不起作用。

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.您应该使用if内部函数 - 以及if中的值,您可能必须手动计算。

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. turtle没有 function 来检测碰撞,您可能必须为此访问tkinter函数,或者您必须创建自己的 function 来检查xcorycor与某些列表中的坐标。 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. turtle很适合画人物,但不适合玩游戏。 There are better modules - like PyGame , Arcade , PGzero ( PyGame Zero )有更好的模块 - 比如PyGame , Arcade , PGzero ( PyGame Zero )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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