• 使用Pygame做一个乒乓球游戏(2)使用精灵重构


    本节没有添加新的功能,而是将前面的功能使用精灵类(pygame.sprite.Sprite) 重构。
    顺便我们使用图片美化了一下程序。
    在这里插入图片描述

    看到之前的代码,你会发现代码有点混乱,很多地方使用了全局变量(global)。

    本节我们将使用类进行重构。

    • Block(Sprite):基类,用于创建一个带图像的长方形。
    • Player(Block):玩家。
    • Ball(Block):球。
    • Opponent(Block): 对手。
    • GameManager: 绘制/更新元素。我们将游戏的主要逻辑移到了这个类中。

    键盘的输入还是在主循环中处理,这样搞还是有些混乱。

    在主程序中,需要创建pygame.sprite.Group(),并将精灵加入其中。

    import sys 
    import random
    import pygame
    
    class Block(pygame.sprite.Sprite):
        def __init__(self,path,x_pos,y_pos):
            super().__init__()
            self.image = pygame.image.load(path)
            self.rect = self.image.get_rect(center = (x_pos,y_pos))
    
    class Player(Block):
        def __init__(self,path,x_pos,y_pos,speed):
            super().__init__(path,x_pos,y_pos)
            self.speed = speed
            self.movement = 0
    
        def screen_constrain(self):
            if self.rect.top <= 0:
                self.rect.top = 0
            if self.rect.bottom >= screen_height:
                self.rect.bottom = screen_height
    
        def update(self,ball_group):
            self.rect.y += self.movement
            self.screen_constrain()
    
    class Ball(Block):
        def __init__(self,path,x_pos,y_pos,speed_x,speed_y,paddles):
            super().__init__(path,x_pos,y_pos)
            self.speed_x = speed_x * random.choice((1,-1))
            self.speed_y = speed_y * random.choice((1,-1))
            self.paddles = paddles
            self.active = False
            self.score_time = 0
        
        def update(self):
            if self.active:
                self.rect.x += self.speed_x
                self.rect.y += self.speed_y
                self.collisions()
            else:
                self.restart_counter()
        
        def collisions(self):
            if self.rect.top <= 0 or self.rect.bottom >= screen_height:
                pygame.mixer.Sound.play(pong_sound)
                self.speed_y *= -1
    
            if pygame.sprite.spritecollide(self,self.paddles,False):
                pygame.mixer.Sound.play(pong_sound)
                collision_paddle = pygame.sprite.spritecollide(self,self.paddles,False)[0].rect
                if abs(self.rect.right - collision_paddle.left) < 10 and self.speed_x > 0:
                    self.speed_x *= -1
                if abs(self.rect.left - collision_paddle.right) < 10 and self.speed_x < 0:
                    self.speed_x *= -1
                if abs(self.rect.top - collision_paddle.bottom) < 10 and self.speed_y < 0:
                    self.speed_y *= -1
                if abs(self.rect.bottom - collision_paddle.top) < 10 and self.speed_y > 0:
                    self.speed_y *= -1
    
        def reset_ball(self):
            self.active = False
            self.speed_x *= random.choice((1,-1))
            self.speed_y *= random.choice((1,-1))
            self.score_time = pygame.time.get_ticks()
            self.rect.center = (screen_width/2,screen_height/2)
            pygame.mixer.Sound.play(score_sound)
        
        def restart_counter(self):
            current_time = pygame.time.get_ticks()
            countdown_number = 3
    
            if current_time - self.score_time <= 700:
                countdown_number = 3
            if 700 < current_time - self.score_time <= 1400:
                countdown_number = 2
            if 1400 < current_time - self.score_time <= 2100:
                countdown_number = 1
            if current_time - self.score_time >= 2100:
                self.active = True
    
            time_counter = basic_font.render(str(countdown_number),True,accent_color)
            time_counter_rect = time_counter.get_rect(center = (screen_width/2,screen_height/2 + 50))
            pygame.draw.rect(screen,bg_color,time_counter_rect)
            screen.blit(time_counter,time_counter_rect)
        
    
    class Opponent(Block):
        def __init__(self,path,x_pos,y_pos,speed):
            super().__init__(path,x_pos,y_pos)
            self.speed = speed
    
        def update(self,ball_group):
            if self.rect.top < ball.rect.y:
                self.rect.y += self.speed
            if self.rect.bottom > ball.rect.y:
                self.rect.y -= self.speed
            self.constrain()
    
        def constrain(self):
            if self.rect.top <= 0: self.rect.top = 0
            if self.rect.bottom >= screen_height: self.rect.bottom = screen_height
    
    class GameManager:
        def __init__(self,ball_group,paddle_group):
            self.player_score = 0
            self.opponent_score = 0
            self.ball_group = ball_group
            self.paddle_group = paddle_group
    
        def run_game(self):
            self.paddle_group.draw(screen)
            self.ball_group.draw(screen)
    
            self.paddle_group.update(self.ball_group)
            self.ball_group.update()
            self.reset_ball()
            self.draw_score()
    
        def reset_ball(self):
            if self.ball_group.sprite.rect.right >= screen_width:
                self.opponent_score += 1
                self.ball_group.sprite.reset_ball()
            if self.ball_group.sprite.rect.left <= 0:
                self.player_score += 1
                self.ball_group.sprite.reset_ball()
    
        def draw_score(self):
            player_score = basic_font.render(str(self.player_score),True,accent_color)
            opponent_score = basic_font.render(str(self.opponent_score),True,accent_color)
    
            player_score_rect = player_score.get_rect(midleft = (screen_width / 2 + 40,screen_height/2))
            opponent_score_rect = opponent_score.get_rect(midright = (screen_width / 2 - 40,screen_height/2))
    
            screen.blit(player_score,player_score_rect)
            screen.blit(opponent_score,opponent_score_rect)
    
    
    # General setup
    pygame.mixer.pre_init(44100, -16, 2, 512)
    pygame.init()
    clock = pygame.time.Clock()
    
    # Main Window
    screen_width = 980
    screen_height = 720
    screen = pygame.display.set_mode((screen_width,screen_height))
    pygame.display.set_caption('Pong')
    
    # Global Variables
    bg_color = pygame.Color('#2F373F')
    accent_color = (27,35,43)
    basic_font = pygame.font.Font('freesansbold.ttf', 32)
    pong_sound = pygame.mixer.Sound("pong.ogg")
    score_sound = pygame.mixer.Sound("score.ogg")
    middle_strip = pygame.Rect(screen_width/2 - 2,0,4,screen_height)
    
    # Game Objects
    player = Player('Paddle.png',screen_width - 20,screen_height/2,5)
    opponent = Opponent('Paddle.png',20,screen_width/2,5)
    paddle_group = pygame.sprite.Group()
    paddle_group.add(player)
    paddle_group.add(opponent)
    
    ball = Ball('Ball.png',screen_width/2,screen_height/2,4,4,paddle_group)
    ball_sprite = pygame.sprite.GroupSingle()
    ball_sprite.add(ball)
    
    game_manager = GameManager(ball_sprite,paddle_group)
    
    # Game Loop
    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.movement += player.speed
                if event.key == pygame.K_UP:
                    player.movement -= player.speed
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_DOWN:
                    player.movement -= player.speed
                if event.key == pygame.K_UP:
                    player.movement += player.speed
    
        # Background Stuff
        screen.fill(bg_color)
        pygame.draw.rect(screen,accent_color,middle_strip)
    
        # Run Game
        game_manager.run_game()
    
        # Rendering
        pygame.display.flip()
        clock.tick(120)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
  • 相关阅读:
    运维:记一次寻找定时任务并删除的经历
    Metabase学习教程:入门-2
    Postman:API测试之Postman使用完全指南
    另辟蹊径者 PoseiSwap:背靠潜力叙事,构建 DeFi 理想国
    springboot+vue学习用品商店商城系统java毕业设计ucozu
    大脑神经网络图高清,图神经网络 图像
    【学习笔记】AGC008
    AVL 树
    如何实现用拼音查询数据库字段
    Python面向对象
  • 原文地址:https://blog.csdn.net/qq_41068877/article/details/136694353