猫史档案馆


【Python作品分享】乒乓球备注【作业帖】

用户:我会修拖拉机TsKl我会修拖拉机TsKl查看:0 回复:0 评论:0 创建时间:2022-05-07T13:26:43


【作品展示】

center_image

 

【作品介绍】

从吧VS大V

 

【作品源代码】

# 导入工具包
import pygame
import time
import random
#2个玩家的初始分数为
p1_score = 0
p2_score = 0
playing=True


# 游戏窗口的值
S_W = 800
S_H = 600   
WHITE = (255, 255, 255)

# 小球的值
b_x = S_W//2
b_y = S_H//2
b_xv = 2
b_yv = 2
b_r = 20

# 球拍1和2的值
P_H = 100
P_W = 25
p1_x = 10
p1_y = (S_H-P_H)//2
p2_x = (S_W-P_W-10)
p2_y = (S_H-P_H)//2

# 初始化及设定大小标题
pygame.init()
screen = pygame.display.set_mode((S_W, S_H))
pygame.display.set_caption('乒乓球')
#函数 等待游玩
def wait_for_replay():
    waiting=True
    while waiting:
        for event in pygame.event.get():
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_SPACE:
                    waiting=False
    global playing, p1_score, p2_score
    p1_score = p2_score = 0
    playing = True
#重置得分
def refresh_screen():
    global playing
    if p1_score>10:
        playing=False
        print("p1 win")
    if p2_score>10:
        playing=False
        print("p2 win")
    
# 刷黑色

    screen.fill((0, 0, 0))
    # 绘制球和球拍
    pygame.draw.circle(screen, WHITE, (b_x, b_y), b_r)
    pygame.draw.rect(screen, WHITE, (p1_x, p1_y, P_W, P_H))
    pygame.draw.rect(screen, WHITE, (p2_x, p2_y, P_W, P_H))
    # 更新屏幕
    pygame.display.update()

#重新发球
def reset_ball():
    print(p1_score, ":", p2_score)
    global b_x,b_y,b_xv,b_yv
    refresh_screen()
#小球放回中心
    b_x=S_W//2
    b_y=S_H//2
#随机方向发射
    if random.randint(0,1):
        b_xv=2
    else:
        b_xv=-2
    if random.randint(0,1):
        b_yv=2
    else:
        b_yv=-2
    time.sleep(0.1)
# 开始循环
while True:
    pygame.time.Clock().tick(120)
    for event in pygame.event.get():    # 检查事件for循环
        if event.type == pygame.QUIT:   # 检查到点击关闭按键
            pygame.quit()   # 关闭窗口界面
    if not playing:
        wait_for_replay()
        refresh_screen()
#碰壁就加分并重发球
    if b_xS_W:
        p1_score+=1
        reset_ball()
    
    # 检查是否y轴超出边界
    if b_y < b_r or b_y+b_r > 600:
        b_yv *= -1
    # 小球移动
    b_x += b_xv
    b_y += b_yv
    # 获取键盘按键
    pressed=pygame.key.get_pressed()
    # 根据键盘状态移动球拍1
    if pressed[pygame.K_w]:
        if p1_y > 0:
            p1_y -= 5
    if pressed[pygame.K_s]:
        if p1_y 0:
            p2_y -= 5
    if pressed[pygame.K_DOWN]:
        if p2_y < S_H-P_H:
            p2_y += 5

    #游戏循环内部-拍1
    if b_xp2_x:
        if p2_y <=b_y <= p2_y+P_H:
            b_xv *= -1

    refresh_screen()

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页