首页 > 解决方案 > 当我进入循环时,它们似乎不起作用

问题描述

所需练习的教程视频参考

我一直在尝试按照海龟指南进行乒乓球比赛。这真的很简单,我完全理解。失败的一件事是球运动,有一个球的定义,然后是循环,当我进入循环时,我编写了相同的代码并且球没有移动

似乎我在弄乱一个我不知道的角色,我只是问是否有人可以帮我看看。我会切掉所有与物体相关的东西,只留下球

我已经下载了教程的.py,执行了它,它工作正常。我复制了具体的功能,它不会工作。

import turtle 
import os

#Aplication and screen setting
ventana = turtle.Screen()
ventana.title("A little pong game")
ventana.bgcolor("black")
ventana.setup(width=800, height=600)
ventana.tracer(0)

#This is the ball definition"
# pelota
pelota = turtle.Turtle()
pelota.speed(0)
pelota.shape("circle")
pelota.color("white")
pelota.penup()
pelota.goto(0, 0)
pelota.dx = 2
pelota.dy = 2


while True:
    ventana.update()

    # Move the ball (this should get the ball moving)
    pelota.setx(pelota.xcor() + pelota.dx)  #-> This isn't working for me
    pelota.sety(pelota.ycor() + pelota.dy)  #-> This isn't working for me

这是完整的工作代码(如果我复制粘贴就可以工作)

import turtle
import os

wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)


# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.2
ball.dy = 0.2

# Main game loop
while True:
    wn.update()

    # Move the ball
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)

我希望球会移动,但在我的代码中它不会开始移动。

标签: pythonpython-3.xturtle-graphics

解决方案


感谢 cdlane 测试代码!它让我调试其他东西,我找到了它。是这样的:

if pelota.xcor() > 390:
    pelota.goto(0, 0)
    pelota.dx *= -1

if pelota.xcor() > -390: # This little mistake was reseting the ball and I thought it wasn't moving at all
    pelota.goto(0, 0)
    pelota.dx *= -1

推荐阅读