我正在尝试创建一个电子游戏,但我被卡住了

问题描述

我是创建电子游戏的初学者,我被困在我不明白的事情上。我正在创建的游戏包括移动桨和击球,如下所示:

enter image description here

我正在使用乌龟,我试图写出桨和球之间的碰撞,但我不明白它是如何工作的。这是脚本:

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