大家还记得小时候玩的游戏——“Pong”吗?
今天,我们使用Python还原这个经典游戏。
整活!
from turtle import Screen
import turtle as t
import time
t.tracer(0) #加速画图
#屏幕左边
side = 400
top = 300
#创建小球
ball = t.Turtle()
ball.penup()#抬笔,移动中不留下痕迹
ball.shape("circle")
ball.color("darkorange")
ball_x = 0
ball_y = 0
speed_x = 4
speed_y = 2
#左边的笔
p1 = t.Turtle()
p1.fillcolor("red")
p1.ht() #隐藏画笔
p1_x = -side+50
p1_y = 0
#画出左边球拍
def p_left(x,y):
p1.clear() #先清除图像
p1.penup()
p1.goto(x, y)
p1.pendown()
p1.begin_fill() #填充红色
for _ in range(2):
p1.fd(20)
p1.left(90)
p1.fd(100)
p1.left(90)
p1.end_fill()
t.update()
#右边的笔
p2 = t.Turtle()
p2.fillcolor("blue")
p2.ht() #隐藏画笔
p2_x = side-50
p2_y = 0
#画出右边球拍
def p_right(x,y):
p2.clear() #先清除图像
p2.penup()
p2.goto(x, y)
p2.pendown()
p2.begin_fill() #填充蓝色
for _ in range(2):
p2.fd(20)
p2.left(90)
p2.fd(100)
p2.left(90)
p2.end_fill()
t.update()
#左边球拍向上移动10步
def up_left():
y = p1.ycor()
if y < top:
y +=10
p_left(p1_x, y)
#左边球拍向下移动10步
def down_left():
y = p1.ycor()
if y > -top:
y -= 10
p_left(p1_x, y)
#右边球拍向上移动10步
def up_right():
y = p2.ycor()
if y < top:
y +=10
p_right(p2_x, y)
#右边球拍向下移动10步
def down_right():
y = p2.ycor()
if y > -top:
y -= 10
p_right(p2_x, y)
#设定键盘监听
screen = Screen()
#按键控制左边球拍
screen.onkey(up_left, "w")
screen.onkey(down_left, "s")
#按键控制右边球拍
screen.onkey(up_right,"p")
screen.onkey(down_right,"l")
screen.listen()#启动键盘监听机器人
#调用函数,画出左右球拍
p_left(p1_x, p1_y)
p_right(p2_x,p2_y)
"""游戏开始"""
while True:
ball_x =ball.xcor()+speed_x
ball_y = ball.ycor()+speed_y
ball.goto(ball_x,ball_y)
#左右边界判断
if ball_x >side or ball_x < -side:
#设置x轴方向 为相反数。
speed_x = - speed_x
#上下边界判断
if ball_y >top or ball_y <-top:
speed_y = - speed_y
""" 判断小球是否碰到球拍 """
#左球拍碰撞检测
p1_y = p1.ycor() #获取球拍y坐标
p1_x = p1.xcor() #获取球拍x坐标
if p1_x < ball_x < p1_x + 20:
if p1_y < ball_y < p1_y +100 :
speed_x = -speed_x
p2_y =p2.ycor()
p2_x =p2.xcor()
if p2_x < ball_x < p2_x + 20:
if p2_y < ball_y < p2_y + 100:
speed_x = -speed_x
t.update()
time.sleep(0.01)
都有注释,自己看吧。
完毕!!!!!



