乒乓球小游戏——第1部分(python源代码)
import turtle
import os
wn = turtle.Screen()
wn.title("PingPong")
wn.bgcolor("black")
wn.setup(width=800,height=600)
#wn.tracer(0) #stop the window from updating
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5,stretch_len=1)
paddle_a.up()
paddle_a.goto(-350,0)
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5,stretch_len=1)
paddle_b.up()
paddle_b.goto(350,0)
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.up()
ball.goto(0,0)
ball.dx = 3
ball.dy = -3
#动作函数
def paddle_a_up():
y = paddle_a.ycor()
y = y + 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y = y - 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor()
y = y + 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor()
y = y - 20
paddle_b.sety(y)
#监听
wn.listen()
#绑定键盘上的键
wn.onkeypress(paddle_a_up,"w")
wn.onkeypress(paddle_a_down,"s")
wn.onkeypress(paddle_b_up,"Up")
wn.onkeypress(paddle_b_down,"Down")
while True:
wn.update()
#移动球球
ball.setx(ball.xcor()+ball.dx)
ball.sety(ball.ycor()+ball.dy)
#边界检测
if ball.ycor() > 290:
ball.sety(290)
ball.dy = ball.dy * -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy = ball.dy * -1
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1