生成一个乒乓球小游戏代码
以下是一个简单的乒乓球小游戏的代码,使用Python语言编写:
import turtle
import time
# 设置窗口大小和背景颜色
win = turtle.Screen()
win.title("Pong Game")
win.bgcolor("black")
win.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=5, stretch_len=1)
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=5, stretch_len=1)
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 # 球的x方向移动速度
ball.dy = 2 # 球的y方向移动速度
# 设置计分板
left_score = 0
right_score = 0
score = turtle.Turtle()
score.speed(0)
score.color("white")
score.penup()
score.hideturtle()
score.goto(0, 170)
score.write("Player 1: {} Player 2: {}".format(left_score, right_score), align="center", font=("Courier", 16, "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)
# 将键盘事件绑定到球拍移动函数上
win.listen()
win.onkeypress(left_pad_up, "w")
win.onkeypress(left_pad_down, "s")
win.onkeypress(right_pad_up, "Up")
win.onkeypress(right_pad_down, "Down")
# 循环游戏
while True:
win.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() > 290:
ball.goto(0, 0)
ball.dx *= -1
left_score += 1
score.clear()
score.write("Player 1: {} Player 2: {}".format(left_score, right_score), align="center", font=("Courier", 16, "normal"))
if ball.xcor() < -290:
ball.goto(0, 0)
ball.dx *= -1
right_score += 1
score.clear()
score.write("Player 1: {} Player 2: {}".format(left_score, right_score), align="center", font=("Courier", 16, "normal"))
# 碰到球拍
if ball.xcor() > 240 and ball.xcor() < 250 and ball.ycor() < right_pad.ycor() + 50 and ball.ycor() > right_pad.ycor() - 50:
ball.dx *= -1
if ball.xcor() < -240 and ball.xcor() > -250 and ball.ycor() < left_pad.ycor() + 50 and ball.ycor() > left_pad.ycor() - 50:
ball.dx *= -1
# 判断胜负
if left_score >= 10 or right_score >= 10:
score.clear()
score.write("Game Over", align="center", font=("Courier", 16, "normal"))
time.sleep(2)
win.bye() # 关闭游戏窗口
运行代码后,即可开始游戏。玩家1使用"W"和"S"键控制左侧球拍的上下移动,玩家2使用上下箭头键控制右侧球拍的上下移动。每当球碰到一个球拍时,它的x方向速度将被反转。当一方得分达到10分时,游戏结束。
原文地址: https://www.cveoy.top/t/topic/bsWd 著作权归作者所有。请勿转载和采集!