如何使边界在海龟中发挥作用 - python

发布于 2025-01-10 07:57:37 字数 623 浏览 0 评论 0原文

因此,我正在制作一款游戏,其中我需要移动一个玩家,该玩家目前只是一个正方形,但如果我继续按该键,它可以离开屏幕。我想在屏幕末尾停止播放器。 这是我的代码,这不是完整的游戏:

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")

So, I was making a game in which I need to move a player which is just a square as of now but it can go out of the screen if I keep pressing the key. I want to stop the player at the end of the screen.
Here is my code this is not the complete game:

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")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不会写诗 2025-01-17 07:57:37

您只需要在 setx() 之前使用 if 检查位置并跳过它。就这样。

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)

You need only use if to check position before setx() and skip it. That's all.

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文