使用Pygame做一个乒乓球游戏

这篇具有很好参考价值的文章主要介绍了使用Pygame做一个乒乓球游戏。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

项目介绍

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

使用Pygame做一个乒乓球游戏,python,Pygame,pygame,游戏,python

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

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

1. 基础版本

使用Pygame做一个乒乓球游戏,python,Pygame,pygame,游戏,python

首先进行一些初始化,初始化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)

使用Pygame做一个乒乓球游戏,python,Pygame,pygame,游戏,python

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

  • 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() 获得时间。

使用Pygame做一个乒乓球游戏,python,Pygame,pygame,游戏,python

# 添加得分和计时器
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节的程序,你会发现有时候球的反弹有时很奇怪,比如有时候会在球拍上。
本节我们将文章来源地址https://www.toymoban.com/news/detail-853534.html

  • 优化碰撞逻辑:在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)

到了这里,关于使用Pygame做一个乒乓球游戏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Python 随练】乒乓球比赛名单

    两个乒乓球队进行比赛,各出三人。甲队为 a,b,c 三人,乙队为 x,y,z 三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a 说他不和 x 比,c 说他不和 x,z 比,请编程序找出三队赛手的名单。 在本篇博客中,我们将解决一个逻辑推理问题:乒乓球比赛名单。根据已知条件

    2024年02月09日
    浏览(26)
  • python+django高校体育乒乓球场地预约管理系统_s2409

    本系统提供给管理员对首页,个人中心,用户管理,乒乓球场管理,场地类型管理,场地预约管理,暂离申请管理,离开申请管理,管理员管理,留言反馈,系统管理等诸多功能进行管理。本系统对于用户输入的任何信息都进行了一定的验证,为管理员操作提高了效率,也使其数据安全

    2024年02月07日
    浏览(32)
  • 【脑筋急转弯系列】乒乓球称重问题

    💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学习,不断总结,共同进步,活到老学到老 导航 檀越剑指大厂系列:全面总

    2024年01月16日
    浏览(30)
  • 机器人制作开源方案 | 乒乓球自动拾取机器人

    作者:刘众森、王森、王绘东、崔岳震、宋维鑫 单位:山东农业工程学院 指导老师:潘莹月、廖希杰       我们小组选择项目的任务方向乒乓球的捡取与存放,针对此问题我们研发了一款乒乓球自动拾取机器人。众所周知,乒乓球是一种世界流行的球类体育项目,而我国是

    2024年02月01日
    浏览(37)
  • Pygame —— 一个好玩的游戏 Python 库

    在电子游戏的世界里,每一个精彩跳跃、每一个刺激冲刺、每一次动听的背景音乐,都是通过精心设计的代码和资源组合出来的奇幻体验。 想象一下,如果你能够制作自己的电子游戏,将内心的奇思妙想实现在屏幕上,那会是多么令人兴奋和自豪的事情。这个梦想,并不遥远

    2024年02月20日
    浏览(46)
  • 使用Pygame创建一个简单游戏界面

    首先需要安装Pygame 模块,在Python代码中添加引用。 1. 引用代码如下: 2. 定义初始化窗口函数: 在初始化窗口函数中,定义窗口大小和窗口标题。 3. 创建一个循环,不断更新界面和检测事件 加载背景图片,将背景图片对象放置在窗口上,位置(0,0) 最左角,图片有实际的

    2024年02月13日
    浏览(38)
  • 很合适新手入门使用的Python游戏开发包pygame实例教程-01[开发环境配置与第一个界面]

    我们假定你已经安装好了我们开发python程序的sublime text,如果不知道怎么安装的可以参照我前面的博文。这里只需要解决的是配置好Pygame的问题。本篇博文主要解决开发环境配置以及第一个游戏界面的显示问题。 文章原出处: https://blog.csdn.net/haigear/article/details/130173836 没有

    2024年01月25日
    浏览(79)
  • 基于Python+Pygame实现一个俄罗斯方块小游戏【完整代码】

    俄罗斯方块,一款起源于上世纪80年代的经典电子游戏,凭借简单的规则和独特的魅力,一跃成为全球家喻户晓的经典。你知道其实只需要一些基础的编程知识,就可以自己实现它吗?今天,我们将使用Python的Pygame库,一步步带你构建属于自己的俄罗斯方块小游戏! 游戏初始

    2024年02月04日
    浏览(34)
  • 使用Python编写游戏辅助脚本——Pygame详细教程

    Python是一种简单且强大的编程语言,在游戏开发中,它可以用来创建游戏辅助脚本。Pygame是Python编程语言的一个库,它提供了一组用于开发游戏的功能和工具。本教程将介绍如何使用Pygame库来编写一个简单的游戏辅助脚本。 在开始编写游戏辅助脚本之前,我们需要先安装Py

    2024年02月04日
    浏览(35)
  • 使用Python+pygame实现贪吃蛇小游戏

    使用第三方库pygame,关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520 给出两种实现。 第一种 运行效果如下: 游戏源码如下: 第二种 就不给出运行效果图了,你可以运行看看。 下面给出另一种实现源码: OK! 

    2024年01月16日
    浏览(49)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包