编译环境:pycharm
1.创建背景
import turtle as t#turtle还是直接可以用的
game=t.Screen()
game.title("边看奥运边打乒乓")
game.bgcolor("black")
game.setup(800,600)
2.创建球拍
p1=t.Turtle()
p1.ht()#先隐藏
p1.up()
p1.speed(0)
p1.color('yellow')
p1.shape('square')
p1.shapesize(5,1)
p1.goto(-350,0)
p1.st()#再显示
3.移动球拍
def p1up():
y=p1.ycor()
y=y+5
p1.sety(y)
def p1down():
y=p1.ycor()
y=y-5
p1.sety(y)
game.listen()
game.onkey(p1up,'w')
game.onkey(p1down,'s')
4.添加第二个球拍
p2=t.Turtle()
p2.ht()#先隐藏
p2.up()
p2.speed(0)
p2.color('white')
p2.shape('square')
p2.shapesize(5,1)
p2.goto(350,0)
p2.st()#再显示
def p2up():
y=p2.ycor()
y=y+5
p2.sety(y)
def p2down():
y=p2.ycor()
y=y-5
p2.sety(y)
game.onkey(p2up,'Up')
game.onkey(p2down,'Down')
5.创建乒乓球
pp=t.Turtle()
pp.up()
pp.speed(0)
pp.color('white')
pp.shape('circle')
6.乒乓球会动
pp.dx=2
pp.dy=2
while True:
pp.setx(pp.xcor()+pp.dx)
pp.sety(pp.ycor()+pp.dy)
7.防止上下出界
if(pp.ycor()>290) or (pp.ycor()<-290):
pp.dy*=-1
8.接球
y_up=p2.ycor()+50
y_down=p2.ycor()-50
if (pp.ycor()<y_up and pp.ycor()>y_down and pp.xcor()>330):
pp.dx*=-1
if (pp.ycor()<p1.ycor()+50 and pp.ycor()>p1.ycor()-50 and pp.xcor()<-330):
pp.dx*=-1
9.球出界
if(pp.xcor()>380):
pp.goto(0,0)
p1_score+=1
print("小明得分!")
if(pp.xcor()<-380):
pp.goto(0, 0)
p2_score += 1
print("如花得分!")
10.添加分数
def write_score():
pen.clear()
score_text = "选手1:{},选手2:{}".format(p1_score, p2_score)
pen.write(score_text, align='center', font=("Arial", 20, 'bold'))
后记:完整代码
import turtle as t#turtle还是直接可以用的
game=t.Screen()
game.title("边看奥运边打乒乓")
game.bgcolor("black")
game.setup(800,600)
# game.tracer(0)
#创建球拍
p1=t.Turtle()
p1.ht()#先隐藏
p1.up()
p1.speed(0)
p1.color('yellow')
p1.shape('square')
p1.shapesize(5,1)
p1.goto(-350,0)
p1.st()#再显示
def p1up():
y=p1.ycor()
y=y+20
p1.sety(y)
def p1down():
y=p1.ycor()
y=y-20
p1.sety(y)
def p2up():
y=p2.ycor()
y=y+20
p2.sety(y)
def p2down():
y=p2.ycor()
y=y-20
p2.sety(y)
game.listen()
game.onkey(p1up,'w')
game.onkey(p1down,'s')
game.onkey(p2up,'Up')
game.onkey(p2down,'Down')
#创建第二个球拍
p2=t.Turtle()
p2.ht()#先隐藏
p2.up()
p2.speed(0)
p2.color('white')
p2.shape('square')
p2.shapesize(5,1)
p2.goto(350,0)
p2.st()#再显示
#添加乒乓球
pp=t.Turtle()
pp.up()
pp.speed(0)
pp.color('white')
pp.shape('circle')
p1_score=0
p2_score=0
pen=t.Turtle()
pen.ht()
pen.up()
pen.color('white')
pen.goto(-10,250)
def write_score():
pen.clear()
score_text = "选手1:{},选手2:{}".format(p1_score, p2_score)
pen.write(score_text, align='center', font=("Arial", 20, 'bold'))
write_score()
#乒乓球会动
pp.dx=2
pp.dy=2
while True:
# game.update()
pp.setx(pp.xcor()+pp.dx)
pp.sety(pp.ycor()+pp.dy)
#防止上下出界
if(pp.ycor()>290) or (pp.ycor()<-290):
pp.dy*=-1
#接球
y_up=p2.ycor()+50
y_down=p2.ycor()-50
if (pp.ycor()<y_up and pp.ycor()>y_down and pp.xcor()>330):
pp.dx*=-1
if (pp.ycor()<p1.ycor()+50 and pp.ycor()>p1.ycor()-50 and pp.xcor()<-330):
pp.dx*=-1
#球出界
if(pp.xcor()>380):
pp.goto(0,0)
p1_score+=1
print("小明得分!")
write_score()
if(pp.xcor()<-380):
pp.goto(0, 0)
p2_score += 1
print("如花得分!")
write_score()
game.mainloop()
t.done()#解决一闪而过的问题