📅  最后修改于: 2023-12-03 15:18:37.319000             🧑  作者: Mango
Pong是一个经典的游戏,玩家控制一个移动的条形板以击打一个跳来跳去的球,直到有一方得分或游戏结束。这是一个有趣的游戏,可以用Python编写。
以下是使用Python编写的Pong游戏代码片段:
import turtle
import os
# 创建游戏窗口
window = turtle.Screen()
window.title("Pong游戏")
window.bgcolor("black")
window.setup(width=600, height=400)
# 创建左方玩家的板
left_pad = turtle.Turtle()
left_pad.speed(0)
left_pad.shape("square")
left_pad.color("white")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-250, 0)
# 创建右方玩家的板
right_pad = turtle.Turtle()
right_pad.speed(0)
right_pad.shape("square")
right_pad.color("white")
right_pad.shapesize(stretch_wid=6, stretch_len=2)
right_pad.penup()
right_pad.goto(250, 0)
# 创建球
ball = turtle.Turtle()
ball.speed(40)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2
# 设置得分标签
left_player_score = 0
right_player_score = 0
score = turtle.Turtle()
score.speed(0)
score.color("white")
score.penup()
score.hideturtle()
score.goto(0, 170)
score.write("Left Player: {} Right Player: {}".format(left_player_score, right_player_score), align="center", font=("Courier", 14, "normal"))
# 定义用户控制函数
def left_pad_up():
y = left_pad.ycor()
y += 20
left_pad.sety(y)
def left_pad_down():
y = left_pad.ycor()
y -= 20
left_pad.sety(y)
def right_pad_up():
y = right_pad.ycor()
y += 20
right_pad.sety(y)
def right_pad_down():
y = right_pad.ycor()
y -= 20
right_pad.sety(y)
# 绑定键盘事件
window.listen()
window.onkeypress(left_pad_up, "w")
window.onkeypress(left_pad_down, "s")
window.onkeypress(right_pad_up, "Up")
window.onkeypress(right_pad_down, "Down")
# 游戏循环
while True:
window.update()
# 球的移动
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# 碰撞检测
if ball.ycor() > 190 or ball.ycor() < -190:
ball.dy *= -1
# 球撞板检测
if (ball.xcor() > 240 and ball.xcor() < 250) and (ball.ycor() < right_pad.ycor() + 60 and ball.ycor() > right_pad.ycor() - 60):
ball.dx *= -1
right_player_score += 1
score.clear()
score.write("Left Player: {} Right Player: {}".format(left_player_score, right_player_score), align="center", font=("Courier", 14, "normal"))
os.system("afplay pong.wav&")
if (ball.xcor() < -240 and ball.xcor() > -250) and (ball.ycor() < left_pad.ycor() + 60 and ball.ycor() > left_pad.ycor() - 60):
ball.dx *= -1
left_player_score += 1
score.clear()
score.write("Left Player: {} Right Player: {}".format(left_player_score, right_player_score), align="center", font=("Courier", 14, "normal"))
os.system("afplay pong.wav&")
# 游戏结束
if left_player_score == 5 or right_player_score == 5:
score.clear()
score.write("Game Over", align="center", font=("Courier", 14, "normal"))
ball.goto(0, 0)
ball.dx = 0
ball.dy = 0
break
要运行该游戏,只需将上述代码粘贴到Python文件中,并运行该文件即可。
以上即是使用Python编写Pong游戏的介绍。