[英]Ball bounce in pong
我写了一些代码,但不能让球自然地在地板或天花板上弹跳。 请帮忙!
我已经尝试过使用 ball_heading = ball.heading 获得球头,但这没有用
#Python 3.6.3
from turtle import *
import math
import random
#Screen Setup
bgcolor("black")
wn = Screen()
wn.title("Pong")
#Drawing Border
bd = Turtle()
bd.pencolor("white")
bd.pensize(3)
bd.hideturtle()
bd.penup()
bd.setposition(-400, -300)
bd.pendown()
bd.speed(0)
bd.pendown()
for line in range(2):
bd.forward(800)
bd.left(90)
bd.forward(600)
bd.left(90)
bd.penup()
bd.setposition(0, 300)
bd.setheading(270)
bd.pendown()
for dash in range(30):
bd.forward(10)
bd.penup()
bd.forward(10)
bd.pendown()
#Creating Paddles
#Paddle 1
player1 = Turtle()
player1.color("white")
player1.shape("square")
player1.shapesize(stretch_wid=5, stretch_len=1)
player1.penup()
player1.setposition(-370, 0)
#Paddle 2
player2 = Turtle()
player2.color("white")
player2.shape("square")
player2.shapesize(stretch_wid=5, stretch_len=1)
player2.penup()
player2.setposition(370, 0)
#Creating the ball
ball = Turtle()
ball.color("white")
ball.shape("square")
ball.speed(0)
ball.penup()
ball.setposition(0, 0)
ball.setheading(random.randint(0, 360))
#Moving the player
playerspeed = 15
#p1
def move_up():
y = player1.ycor()
y += playerspeed
#Setting the boundries
if y > 245:
y = 245
player1.sety(y)
def move_down():
y = player1.ycor()
y -= playerspeed
#Setting the boundries
if y < -245:
y = -245
player1.sety(y)
#p2
def move_up2():
y = player2.ycor()
y += playerspeed
#Setting the boundries
if y > 245:
y = 245
player2.sety(y)
def move_down2():
y = player2.ycor()
y -= playerspeed
#Setting the boundries
if y < -245:
y = -245
player2.sety(y)
#Ball movement
def ball_fd():
ball.forward(3)
#Ball ceiling / floor bounce
def ball_bounce():
by = ball.ycor()
if by > 279:
by = 279
ball.sety(by)
bx = ball.ycor()
if bx < -279:
bx = -279
ball.setx(bx)
#binding
listen()
onkey(move_up, "Up")
onkey(move_down, "Down")
onkey(move_up2, "w")
onkey(move_down2, "s")
#Making the ball move / main game loop
while True:
ball_fd()
ball_bounce()
抱歉,代码有点长,但可以随意将其复制并粘贴到 IDLE 或其他任何内容中。 谢谢
你的反弹功能看起来很奇怪 - 你正在重置y
值,而不是真正处理x
(可能是第二个ycor
一个诚实的错误),最重要的是 - 你没有改变运动的方向 - 标题。 这是一个从以下开始更好的版本:
bheading = random.randint(0, 360)
ball.setheading(bheading)
def ball_bounce():
global bheading
if abs(ball.ycor()) >= 279 :
bheading = -bheading
ball.setheading(bheading)
if abs(ball.xcor()) >= 379:
#Or change this to a player fail/scoring event
bheading-=45
ball.setheading(bheading)
现在的标题被保存在全球bheading
所以我们可以相对方向随时调整我们的一个标题。 另请注意我使用abs
来同时检查两个边界,包括负面和正面。 您可能希望稍后使用失败/评分事件替换x
反弹。
仍然可能存在边缘问题,例如球可能卡在角落里 - 边界检查将从中省去,虽然这不会经常发生,所以很难调试。
当球击中地板或天花板时,您没有转动球。
while True:
ball.fd(3)
by = ball.ycor()
if abs(by) > 279:
ball.setheading(-ball.heading())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.