使用Pygame做一个乒乓球游戏

news2024/11/25 2:26:24

项目介绍

使用Pygame做一个乒乓球游戏。左侧为电脑,右侧为玩家。

在这里插入图片描述

视频地址-YT
视频搬运-B站
视频教程约90分钟。
代码地址

环境:需要pygame库,可用pip安装:pip install pygame

1. 基础版本

v1-1

首先进行一些初始化,初始化pygame以及物体的初始状态。
然后是主循环,游戏的主循环主要包含3个内容

  1. 处理事件(这里主要是键盘按键)
  2. 更新物体的状态
  3. 在屏幕上绘制
# 基础 ping pang游戏
import sys
import random
import pygame

# 初始化
pygame.init()
clock = pygame.time.Clock()

screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("PingPang")
# 使用长方形表示球和球拍
ball = pygame.Rect(screen_width // 2 - 15, screen_height // 2 - 15, 30, 30)
player = pygame.Rect(screen_width - 20, screen_height // 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height // 2 - 70, 10, 140)

bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)

ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))    
player_speed = 0
opponent_speed = 7


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                player_speed += 7
            if event.key == pygame.K_UP:
                player_speed -= 7
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                player_speed -= 7
            if event.key == pygame.K_UP:
                player_speed += 7
    
    # update
    #ball_animation()
    #player_animation()
    #opponent_animation()
    
    # draw
    screen.fill(bg_color)
    pygame.draw.rect(screen, light_grey, player)
    pygame.draw.rect(screen, light_grey, opponent)
    pygame.draw.ellipse(screen, light_grey, ball)
    pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))
    pygame.display.flip()
    clock.tick(60)

v1-2

然后我们实现上面的三个更新逻辑,更新物体状态。

  • ball_animation()
  • player_animation()
  • opponent_animation()
def ball_animation():
    """更新球的运动"""
    global ball_speed_x, ball_speed_y
    ball.x += ball_speed_x
    ball.y += ball_speed_y

    if ball.top <= 0 or ball.bottom >= screen_height:
        ball_speed_y *= -1
    if ball.left <= 0 or ball.right >= screen_width:
        ball_speed_x *= -1
        ball_restart()
    if ball.colliderect(player) or ball.colliderect(opponent):
        ball_speed_x *= -1

def player_animation():
    """更新玩家的运动"""
    player.y += player_speed
    if player.top <= 0:
        player.top = 0
    if player.bottom >= screen_height:
        player.bottom = screen_height

def opponent_animation():
    """更新对手的运动"""
    if opponent.top < ball.y:
        opponent.top += opponent_speed
    if opponent.bottom > ball.y:
        opponent.bottom -= opponent_speed
    if opponent.top <= 0:
        opponent.top = 0
    if opponent.bottom >= screen_height:
        opponent.bottom = screen_height

def ball_restart():
    """重置球的位置"""
    global ball_speed_x, ball_speed_y
    ball.center = (screen_width // 2, screen_height // 2)
    ball_speed_y *= random.choice((1, -1))
    ball_speed_x *= random.choice((1, -1))

实现了这3个函数后,记得在主循环中的# update 处调用这个三个函数。

2. 添加分数和时间

  1. 为游戏添加分数显示:添加字体并渲染出分数。
  2. 发球时有3秒倒计时:通过pygame.time.get_ticks() 获得时间。

在这里插入图片描述

# 添加得分和计时器
import sys
import random
import pygame


pygame.init()
clock = pygame.time.Clock()

screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("PingPang")



ball = pygame.Rect(screen_width // 2 - 15, screen_height // 2 - 15, 30, 30)
player = pygame.Rect(screen_width - 20, screen_height // 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height // 2 - 70, 10, 140)

bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)

ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))    
player_speed = 0
opponent_speed = 7

# Text Variables
player_score = 0
opponent_score = 0
# 创建字体
game_font = pygame.font.Font("freesansbold.ttf", 32)

# Timer
score_time = True


def ball_animation():
    global ball_speed_x, ball_speed_y
    global player_score, opponent_score
    global score_time
    ball.x += ball_speed_x
    ball.y += ball_speed_y

    if ball.top <= 0 or ball.bottom >= screen_height:
        ball_speed_y *= -1
    if ball.left <= 0 or ball.right >= screen_width:    
        if ball.left <= 0:
            player_score += 1
        if ball.right >= screen_width:
            opponent_score += 1
        score_time = pygame.time.get_ticks()
        

    if ball.colliderect(player) or ball.colliderect(opponent):
        ball_speed_x *= -1

def player_animation():
    player.y += player_speed
    if player.top <= 0:
        player.top = 0
    if player.bottom >= screen_height:
        player.bottom = screen_height

def opponent_animation():
    if opponent.top < ball.y:
        opponent.top += opponent_speed
    if opponent.bottom > ball.y:
        opponent.bottom -= opponent_speed
    if opponent.top <= 0:
        opponent.top = 0
    if opponent.bottom >= screen_height:
        opponent.bottom = screen_height

def ball_restart():
    global ball_speed_x, ball_speed_y
    global score_time
    ball.center = (screen_width // 2, screen_height // 2)
	# 计算耗时,并显示剩余时间
	# 获得当前时间
    current_time = pygame.time.get_ticks()
	# 与上次得分时间比较
    if current_time - score_time < 700:
        number_three = game_font.render("3", False, light_grey)
        screen.blit(number_three, (screen_width // 2 - 10, screen_height // 2 + 20))
    if 700 < current_time - score_time < 1400:
        number_two = game_font.render("2", False, light_grey)
        screen.blit(number_two, (screen_width // 2 - 10, screen_height // 2 + 20))
    if 1400 < current_time - score_time < 2100:
        number_one = game_font.render("1", False, light_grey)
        screen.blit(number_one, (screen_width // 2 - 10, screen_height // 2 + 20))
    
    if current_time - score_time < 2100:
        ball_speed_x, ball_speed_y = 0, 0
    else:
        ball_speed_y = 7 * random.choice((1, -1))
        ball_speed_x = 7 * random.choice((1, -1))
        score_time = None

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                player_speed += 7
            if event.key == pygame.K_UP:
                player_speed -= 7
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                player_speed -= 7
            if event.key == pygame.K_UP:
                player_speed += 7

   
    
    ball_animation()
    player_animation()
    opponent_animation()
    # update
    # draw
    screen.fill(bg_color)
    pygame.draw.rect(screen, light_grey, player)
    pygame.draw.rect(screen, light_grey, opponent)
    pygame.draw.ellipse(screen, light_grey, ball)
    pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))
	# 显示得分
    player_text = game_font.render(f"{player_score}", False, light_grey)
    screen.blit(player_text, (660, 360))

    opponent_text = game_font.render(f"{opponent_score}", False, light_grey)
    screen.blit(opponent_text, (600, 360))
    if score_time:
        ball_restart()
   
    pygame.display.flip()
    clock.tick(60)

3. 优化碰撞逻辑、添加声音

如果你运行了第2节的程序,你会发现有时候球的反弹有时很奇怪,比如有时候会在球拍上。
本节我们将

  • 优化碰撞逻辑:在ball_animation()通过判断球与球拍的位置,修改球的运动。
  • 添加碰撞和得分音效: pygame.mixer.Sound
# 添加得分和计时器
# 基础 ping pang游戏
import sys
import random
import pygame

# setup
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 512)
clock = pygame.time.Clock()


screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("PingPang")


# Reactangles
ball = pygame.Rect(screen_width // 2 - 15, screen_height // 2 - 15, 30, 30)
player = pygame.Rect(screen_width - 20 , screen_height // 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height // 2 - 70, 10, 140)

bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)

ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))    
player_speed = 0
opponent_speed = 7

# Text Variables
player_score = 0
opponent_score = 0
game_font = pygame.font.Font("freesansbold.ttf", 32)

# Timer
score_time = True

# Sound
pong_sound = pygame.mixer.Sound("pong.ogg")
score_sound = pygame.mixer.Sound("score.ogg")

def ball_animation():
    global ball_speed_x, ball_speed_y
    global player_score, opponent_score
    global score_time
    ball.x += ball_speed_x
    ball.y += ball_speed_y

    if ball.top <= 0 or ball.bottom >= screen_height:
        pong_sound.play()
        ball_speed_y *= -1
    # score 
    if ball.left <= 0 or ball.right >= screen_width:    
        score_sound.play()
        if ball.left <= 0:
            player_score += 1
        if ball.right >= screen_width:
            opponent_score += 1
        score_time = pygame.time.get_ticks()
        

    if ball.colliderect(player) and ball_speed_x > 0: 
        pong_sound.play()
        if abs(ball.right - player.left) < 10 :
            ball_speed_x *= -1
        elif abs(ball.bottom - player.top) < 10 and ball_speed_y > 0:
            ball_speed_y *= -1
        elif abs(ball.top - player.bottom) < 10 and ball_speed_y < 0:
            ball_speed_y *= -1
        
    if ball.colliderect(opponent) and ball_speed_x < 0:
        pong_sound.play()
        if abs(ball.left - opponent.right) < 10:
            ball_speed_x *= -1
        elif abs(ball.bottom - opponent.top) < 10 and ball_speed_y > 0:
            ball_speed_y *= -1     
        elif abs(ball.top - opponent.bottom) < 10 and ball_speed_y < 0:
            ball_speed_y *= -1

def player_animation():
    player.y += player_speed
    if player.top <= 0:
        player.top = 0
    if player.bottom >= screen_height:
        player.bottom = screen_height

def opponent_animation():
    if opponent.top < ball.y:
        opponent.top += opponent_speed
    if opponent.bottom > ball.y:
        opponent.bottom -= opponent_speed
    if opponent.top <= 0:
        opponent.top = 0
    if opponent.bottom >= screen_height:
        opponent.bottom = screen_height

def ball_restart():
    global ball_speed_x, ball_speed_y
    global score_time
    ball.center = (screen_width // 2, screen_height // 2)

    current_time = pygame.time.get_ticks()

    if current_time - score_time < 700:
        number_three = game_font.render("3", False, light_grey)
        screen.blit(number_three, (screen_width // 2 - 10, screen_height // 2 + 20))
    if 700 < current_time - score_time < 1400:
        number_two = game_font.render("2", False, light_grey)
        screen.blit(number_two, (screen_width // 2 - 10, screen_height // 2 + 20))
    if 1400 < current_time - score_time < 2100:
        number_one = game_font.render("1", False, light_grey)
        screen.blit(number_one, (screen_width // 2 - 10, screen_height // 2 + 20))
    
    if current_time - score_time < 2100:
        ball_speed_x, ball_speed_y = 0, 0
    else:
        ball_speed_y = 7 * random.choice((1, -1))
        ball_speed_x = 7 * random.choice((1, -1))
        score_time = None

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                player_speed += 7
            if event.key == pygame.K_UP:
                player_speed -= 7
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                player_speed -= 7
            if event.key == pygame.K_UP:
                player_speed += 7

   
    
    ball_animation()
    player_animation()
    opponent_animation()
    # update
    # draw
    screen.fill(bg_color)
    pygame.draw.rect(screen, light_grey, player)
    pygame.draw.rect(screen, light_grey, opponent)
    pygame.draw.ellipse(screen, light_grey, ball)
    pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))

    player_text = game_font.render(f"{player_score}", False, light_grey)
    screen.blit(player_text, (660, 360))

    opponent_text = game_font.render(f"{opponent_score}", False, light_grey)
    screen.blit(opponent_text, (600, 360))
    if score_time:
        ball_restart()
   
    pygame.display.flip()
    clock.tick(60)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1531472.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL 多表查询与事务的操作

一,多表联查 有些数据我们已经拆分成多个表,他们之间通过外键进行连接.当我们要查询两个表的数据,各取其中的一列或者多列. 这时候就需要使用多表联查. 数据准备: # 创建部门表 create table dept(id int primary key auto_increment,name varchar(20) ) insert into dept (n…

MySQL 多表关系(介绍) 一对多/多对多

一对多 举例介绍 例子: 部门与员工 在常理上来说: 一个部门有多个员工&#xff0c;一个员工只对应一个部门实现方式: 在多的一方建立外键&#xff0c;指向一的一方的主键 多对多 举例介绍 例子: 学生与课程 在常理上来说: 一个学生可以有多个课程,一门课程可以有多个学生实…

热插拔技术(番外)

5、总线热插拔及系统解决方案 在实际运用中&#xff0c;总线上插入板卡时&#xff0c;由于新插入板卡电容的充电以及上电过程中一些低阻抗通道的存在&#xff0c;会产生极大的浪涌电流&#xff0c;拉低总线电平&#xff0c;对总线上其他设备产生干扰&#xff0c;影响总线上其他…

【机器学习】TinyML的介绍以及在运动健康领域的应用

&#x1f9d1; 作者简介&#xff1a;阿里巴巴嵌入式技术专家&#xff0c;深耕嵌入式人工智能领域&#xff0c;具备多年的嵌入式硬件产品研发管理经验。 &#x1f4d2; 博客介绍&#xff1a;分享嵌入式开发领域的相关知识、经验、思考和感悟,欢迎关注。提供嵌入式方向的学习指导…

前端基础篇-深入了解 Ajax 、Axios

&#x1f525;博客主页&#xff1a; 【小扳_-CSDN博客】 ❤感谢大家点赞&#x1f44d;收藏⭐评论✍ 文章目录 1.0 Ajax 概述 2.0 Axios 概述 3.0 综合案例 1.0 Ajax 概述 通过 Ajax 可以给服务器发送请求&#xff0c;并获取服务器响应的数据。异步交互是指&#xff0c;可以在不…

高效编写产品规格书的秘诀与注意事项

高效编写产品规格书的秘诀&#xff1a;学会利用简单的工具&#xff0c;写出效果最佳的产品规格书。比如&#xff0c;你可以使用HelpLook、Markdown编辑器、LaTeX、notion等。 在快节奏的商业环境中&#xff0c;产品规格书是企业向市场展示产品特性和优势的重要工具。一份清晰、…

Linux——进程通信(三)命名管道

前言 我们在之前学习了匿名管道与匿名管道的应用——进程池&#xff0c;但是匿名管道的通信&#xff0c;需要有血缘关系的进程&#xff08;通过fork创建的进程们&#xff09;&#xff0c;如果我想让两个毫不相干的进程进行通信&#xff0c;可以采样命名管道的方式&#xff08;…

如何在Windows系统使用VS Code制作游戏网页并实现无公网IP远程访问

文章目录 前言1. 编写MENJA小游戏2. 安装cpolar内网穿透3. 配置MENJA小游戏公网访问地址4. 实现公网访问MENJA小游戏5. 固定MENJA小游戏公网地址 前言 本篇教程&#xff0c;我们将通过VS Code实现远程开发MENJA小游戏&#xff0c;并通过cpolar内网穿透发布到公网&#xff0c;分…

提升Java编程安全性-代码加密混淆工具的重要性和应用

在Java编程领域中&#xff0c;保护代码安全性和知识产权至关重要。本文旨在探讨代码加密混淆工具在提升代码安全性和保护知识产权方面的重要性。我们将介绍几款流行的Java代码加密混淆工具&#xff0c;如ProGuard、DexGuard、Jscrambler、DashO和ipaguard&#xff0c;并分析它们…

【RabbitMQ】【Docker】基于docker-compose构建rabbitmq容器

本文通过docker-compose构建一个单体的rabbtimq容器。 1&#xff0c;docker、docker-compose环境 首先需要有docker和docker-compose环境&#xff0c;docker安装[1]&#xff0c;docker-compose安装[2]。 通过下列命令确定docker、docker-compose是否安装成功。 [root192 ge…

单片机LED灯闪烁

延时函数计算&#xff08;相关代码生成&#xff09;&#xff1a; #include "reg52.h" #include <INTRINS.H> void Delay500ms() //11.0592MHz {unsigned char i, j, k;_nop_();_nop_();i 22;j 3;k 227;do{do{while (--k);} while (--j);} while (--i); }vo…

利用Xinstall,实现安装页面快速拉起App,推广效果倍增!

在移动互联网时代&#xff0c;App推广已成为广告主和开发者的重要任务。然而&#xff0c;面对激烈的市场竞争&#xff0c;如何提升推广效率、洞悉推广效果并衡量广告ROI&#xff0c;成为摆在他们面前的难题。今天&#xff0c;我们将聚焦一个关键环节——安装页面拉起App&#x…

Grid数据增强算法

算法原理 class Grid(object):def __init__(self, d1, d2, rotate1, ratio0.5, mode0, prob0.8):self.d1 d1self.d2 d2self.rotate rotateself.ratio ratioself.mode modeself.st_prob self.prob probdef set_prob(self, epoch, max_epoch):self.prob self.st_prob …

Debezium vs OGG vs Tapdata:如何实时同步 Oracle 数据到 Kafka 消息队列?

随着信息时代的蓬勃发展&#xff0c;企业对实时数据处理的需求逐渐成为推动业务创新和发展的重要驱动力。在这个快速变化的环境中&#xff0c;许多企业选择将 Oracle 数据库同步到 Kafka&#xff0c;以满足日益增长的实时数据处理需求。本文将深入探讨这一趋势的背后原因&#…

Java并发基石ReentrantLock:深入解读其原理与实现

码到三十五 &#xff1a; 个人主页 心中有诗画&#xff0c;指尖舞代码&#xff0c;目光览世界&#xff0c;步履越千山&#xff0c;人间尽值得 ! 在Java的并发编程库中&#xff0c;ReentrantLock是一种非常重要的同步工具&#xff0c;它提供了一种比内置synchronized关键字更加…

基于ArcGIS等多技术融合提升环境、生态、水文、土地、农业、大气等领域科研技术应用

基于ArcGIS等多技术融合提升环境、生态、水文、土地、农业、大气等领域科研技术应用 原文链接https://mp.weixin.qq.com/s?__bizMzUyNzczMTI4Mg&mid2247667012&idx5&snd2c5af65851b06ff7ee14a744c16009e&chksmfa771279cd009b6f8beff1c61c6b3b73087bf93e7d440…

顺序表的动态分配基本操作

#include <stdio.h> #include <stdlib.h>// 顺序表存储空间动态分配 #define InitSize 10 // 顺序表初始长度 typedef int ElemType; // int类型重命名为ElemType&#xff0c;方便后续调整typedef struct { // 定义结构体ElemType *data; // 用静…

“垃圾不落地,捡跑来助力”学雷锋志愿服务暨党支部党日活动

指导思想 紧紧围绕建设和谐社会主题&#xff0c;以创建文明为契机&#xff0c;学习雷锋精神&#xff0c;为人民服务为宗旨&#xff0c;大力开展志愿捡跑活动&#xff0c;激发大家积极参与志愿活动的热情&#xff0c;大力弘扬奉献、友爱、互助、进步的志愿服务精神。 活动启动 …

维度建模理论之事实表

事实表概述 事实表作为数据仓库维度建模的核心&#xff0c;紧紧围绕着业务过程来设计。其包含与该业务过程有关的维度引用&#xff08;维度表外键&#xff09;以及该业务过程的度量&#xff08;通常是可累加的数字类型字段&#xff09;。 事实表特点 事实表通常比较“细长”…

N 皇后00

题目链接 N 皇后 题目描述 注意点 1 < n < 9 解答思路 首先想到的是使用深度优先遍历回溯找到所有的情况&#xff0c;基本思路是&#xff1a;逐行确定Q在该行的位置&#xff0c;且每一行Q都是从第0列到第n - 1列全部考虑&#xff0c;在确定Q在任意一行的某一列时&am…