如何解决我正在尝试创建一个电子游戏,但我被卡住了
我是创建电子游戏的初学者,我被困在我不明白的事情上。我正在创建的游戏包括移动桨和击球,如下所示:
我正在使用乌龟,我试图写出桨和球之间的碰撞,但我不明白它是如何工作的。这是脚本:
import turtle
width,height = 800,600
score = 0
wn = turtle.Screen()
wn.title('Breakout')
wn.bgcolor('black')
wn.setup(width,height)
wn.tracer()
# Paddle
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape('square')
paddle.shapesize(stretch_wid=5,stretch_len=1)
paddle.color('white')
paddle.penup()
paddle.left(90)
paddle.goto(0,-290)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.goto(0,0)
ballx = 3
bally = -3
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write('score: 0',align='center',font=('Courier',24,'normal'))
# Paddle movement
def paddle_right():
x = paddle.xcor()
x -= 20
paddle.setx(x)
def paddle_left():
x = paddle.xcor()
x += 20
paddle.setx(x)
wn.listen()
wn.onkeypress(paddle_right,'a')
wn.onkeypress(paddle_left,'d')
while True:
wn.update()
ball.setx(ball.xcor() + ballx)
ball.sety(ball.ycor() + bally)
# Borders
if ball.xcor() > 390:
ball.setx(390)
ballx *= -1
if ball.xcor() < -390:
ball.setx(-390)
ballx *= -1
if ball.ycor() > 290:
ball.sety(290)
bally *= -1
if ball.ycor() < -290:
ball.goto(0,0)
bally *= -1
score -= 1
pen.clear()
pen.write('score: {}'.format(score),'normal'))
# Paddle and ball collision
有人可以为我编写最后几行代码并向我解释它们 - 它是如何工作的?谢谢
解决方法
if (ball.ycor() == paddle.ycor() # first check if they're on the same level
and ((paddle.xcor() + 2) >
ball.xcor() > (paddle.xcor() + 2)): # then check if the ball collided with the paddle
# then count it as a collision and mirror the ball's y direction
# as in "bounce it off"
bally *= -1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。