简体   繁体   中英

I'm trying to create a videogame but I'm stuck

I'm a very beginner to creating videogames and I'm stuck at a thing that I don't understand. The game that I'm creating consists in moving a paddle and hit a ball, like this:

在此处输入图像描述

I'm using turtle and I'm trying to write the collision between the paddle and the ball, but I don't understand how does it works. This is the script:

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), align='center', font=('Courier', 24, 'normal'))

    # Paddle and ball collision

Can somebody write the last lines of code for me and explain them to me - how does it works? Thank you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM