如何在 turtle 中设置边界 - python
How to make boundaries work in turtle - python
所以,我正在制作一个游戏,我需要移动一个玩家,这个玩家现在只是一个正方形,但如果我一直按下这个键,它就会离开屏幕。我想在屏幕末尾停止播放器。
这是我的代码,这不是完整的游戏:
import turtle
sc=turtle.Screen()
sc.title("Math fighter")
sc.bgcolor("black")
sc.setup(width=1000, height=600)
player=turtle.Turtle()
player.speed(0)
player.shape("square")
player.color("white")
player.shapesize(stretch_wid=2, stretch_len=3)
player.penup()
player.goto(0, -250)
def playerleft():
x = player.xcor()
x -= 20
player.setx(x)
def playerright():
y = player.xcor()
y += 20
player.setx(y)
sc.listen()
sc.onkeypress(playerright, "Right")
sc.onkeypress(playerleft, "Left")
您只需要使用if
检查setx()
之前的位置并跳过它。就这些了。
def playerleft():
x = player.xcor()
x -= 20
if x > -500:
player.setx(x)
def playerright():
x = player.xcor()
x += 20
if x < 500:
player.setx(x)
所以,我正在制作一个游戏,我需要移动一个玩家,这个玩家现在只是一个正方形,但如果我一直按下这个键,它就会离开屏幕。我想在屏幕末尾停止播放器。 这是我的代码,这不是完整的游戏:
import turtle
sc=turtle.Screen()
sc.title("Math fighter")
sc.bgcolor("black")
sc.setup(width=1000, height=600)
player=turtle.Turtle()
player.speed(0)
player.shape("square")
player.color("white")
player.shapesize(stretch_wid=2, stretch_len=3)
player.penup()
player.goto(0, -250)
def playerleft():
x = player.xcor()
x -= 20
player.setx(x)
def playerright():
y = player.xcor()
y += 20
player.setx(y)
sc.listen()
sc.onkeypress(playerright, "Right")
sc.onkeypress(playerleft, "Left")
您只需要使用if
检查setx()
之前的位置并跳过它。就这些了。
def playerleft():
x = player.xcor()
x -= 20
if x > -500:
player.setx(x)
def playerright():
x = player.xcor()
x += 20
if x < 500:
player.setx(x)