当前位置:   article > 正文

使用pygame 编写俄罗斯方块游戏

使用pygame 编写俄罗斯方块游戏

项目地址:https://gitee.com/wyu_001/mypygame/tree/master/game
可执行程序

这个游戏主要使用pygame库编写俄罗斯方块游戏,demo主要演示了pygame开发游戏的主要设计方法和实现代码

下面是游戏界面截图
在这里插入图片描述
游戏主界面:

在这里插入图片描述
直接上代码:

# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
  @author: spring.wang
  @license: 
  @contact: wyu_01@163.com
  @software: tetris
  @file: tetris1.py
  @time: 2024/2/20 17:26
  @description:

  pyinstaller.exe  -F -w --distpath D:\myproject\python\pygame\bin\tetris  --workpath D:\myproject\python\pygame\bin\temp --specpath D:\myproject\python\pygame\bin\temp D:\myproject\python\pygame\game\tetris.py
  
  '''

import pygame
import random
import time
import sys

# 游戏窗口尺寸
WINDOW_WIDTH = 200
WINDOW_HEIGHT = 400

# 方块尺寸
BLOCK_SIZE = 20

# 初始化 Pygame
pygame.init()

# 初始化窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

class Block:
    def __init__(self, shape, color):
        self.shape = shape
        self.color = color
        self.x = WINDOW_WIDTH // 2 - BLOCK_SIZE
        self.y = 0
        self.timer = 0
        self.fall_speed = 10
        self.move_speed = 1
        self.max_speed = 3

    def set_speed(self):

        self.move_speed += 1
        if self.move_speed > self.max_speed:
            self.move_speed = self.max_speed

    def reset_speed(self):
        self.move_speed = 1

    def move_up(self):
        self.y -= BLOCK_SIZE

    def move_down(self):
        self.y += BLOCK_SIZE

    def move_left(self):
        self.x -= BLOCK_SIZE

    def move_right(self):
        self.x += BLOCK_SIZE

    def rotate(self):
        self.shape = [[row[i] for row in self.shape][::-1] for i in range(len(self.shape[0]))]
        # print(self.shape)

    def draw(self):
        for i in range(len(self.shape)):
            for j in range(len(self.shape[i])):
                if self.shape[i][j] == 1:
                    pygame.draw.rect(window, self.color,
                                     (self.x + j * BLOCK_SIZE, self.y  + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))



class Tetris:

    # 方块颜色
    BLACK = (0, 0, 0)
    CYAN = (0, 255, 255)
    YELLOW = (255, 255, 0)
    PURPLE = (255, 0, 255)
    GREEN = (0, 255, 0)
    RED = (255, 0, 0)
    ORANGE = (255, 165, 0)
    BLUE = (0, 0, 255)
    WHITE = (255, 255, 255)
    # 定义方块形状
    SHAPES = [
      [[1, 1, 1, 1]],
      [[1, 1], [1, 1]],
      [[1, 1, 0], [0, 1, 1]],
      [[0, 1, 1], [1, 1, 0]],
      [[1, 1, 1], [0, 1, 0]],
      [[1, 1, 1], [1, 0, 0]],
      [[1, 1, 1], [0, 0, 1]]
    ]

    # 定义方块颜色
    COLORS = [CYAN, YELLOW, PURPLE, GREEN, RED, ORANGE, BLUE]

    def __init__(self):
        self.score = 0
        self.timer = 0
        self.fall_speed = 1
        self.FPS = 60
        self.game_running = True

        pygame.display.set_caption("俄罗斯方块")
        self.clock = pygame.time.Clock()

        self.grid = [[self.BLACK] * (WINDOW_WIDTH // BLOCK_SIZE) for _ in range(WINDOW_HEIGHT // BLOCK_SIZE)]
        self.block = Block(random.choice(self.SHAPES), random.choice(self.COLORS))

        self.key_down_time = None
        self.key_left_time = None
        self.key_right_time = None

        self.down_flag = True
        self.direction = 0
    def draw_grid(self):
        for x in range(0, WINDOW_WIDTH, BLOCK_SIZE):
            pygame.draw.line(window, self.BLACK, (x, 0), (x, WINDOW_HEIGHT))
        for y in range(0, WINDOW_HEIGHT, BLOCK_SIZE):
          pygame.draw.line(window, self.BLACK, (0, y), (WINDOW_WIDTH, y))

    def check_collision(self):
        for i in range(len(self.block.shape)):
            for j in range(len(self.block.shape[i])):
                if self.block.shape[i][j] == 1:
                    if self.block.y + (i + 1) * BLOCK_SIZE >= WINDOW_HEIGHT or \
                            self.block.x + j * BLOCK_SIZE < 0 or \
                            self.block.x + j * BLOCK_SIZE >= WINDOW_WIDTH or \
                            self.grid[self.block.y // BLOCK_SIZE + i + 1][self.block.x // BLOCK_SIZE + j] != self.BLACK:
                        return True
        return False

    def event_handler(self):
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.game_running = False
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.key_left_time = time.time()
                    self.block.move_left()
                    if self.check_collision():
                        self.block.move_right()
                elif event.key == pygame.K_RIGHT:
                    self.key_right_time = time.time()
                    self.block.move_right()
                    if self.check_collision():
                        self.block.move_left()
                elif event.key == pygame.K_DOWN:
                    if not self.check_collision():
                        self.key_down_time = time.time()
                        self.block.move_down()
                elif event.key == pygame.K_UP:
                    self.block.rotate()
                    if self.check_collision():
                        for _ in range(3):
                            self.block.rotate()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    self.key_left_time = None
                    self.down_flag = True
                    self.timer = 0
                    self.direction = 0
                if event.key == pygame.K_RIGHT:
                    self.key_right_time = None
                    self.down_flag = True
                    self.timer = 0
                    self.direction = 0
                if event.key == pygame.K_DOWN:
                    self.key_down_time = None
                    self.timer=0
    def update(self):
        if self.timer >= 1 / self.fall_speed:
            self.timer -= 1 / self.fall_speed

            if not self.check_collision() and self.down_flag:
                self.block.move_down()
            elif not self.check_collision():
                if self.direction == 1:
                    self.block.move_left()
                    if self.check_collision():
                        self.block.move_right()
                if self.direction == 2:
                    self.block.move_right()
                    if self.check_collision():
                        self.block.move_left()
            else:
                for i in range(len(self.block.shape)):
                    for j in range(len(self.block.shape[i])):
                        if self.block.shape[i][j] == 1:
                            # print(block.y // BLOCK_SIZE + i, block.x // BLOCK_SIZE + j,i,j)
                            self.grid[self.block.y // BLOCK_SIZE + i][self.block.x // BLOCK_SIZE + j] = self.block.color

                self.score += self.clear_rows()

                if self.score%20 == 0 and self.score != 0 :
                    self.fall_speed += 1
                self.block = Block(random.choice(self.SHAPES), random.choice(self.COLORS))

                if self.check_collision():
                    self.game_running = False

        current_time = time.time()
        if self.key_down_time is not None and (current_time - self.key_down_time) > 0.1:  # 假设0.1秒后开始加速
            self.key_down_time = current_time
            self.timer += 1 / self.fall_speed*2

        if self.key_left_time is not None and (current_time - self.key_left_time) > 0.1:  # 假设0.1秒后开始加速
            self.key_left_time = current_time
            self.down_flag = False
            self.direction = 1
            self.timer += 1 / self.fall_speed*20

        if self.key_right_time is not None and (current_time - self.key_right_time) > 0.1:  # 假设0.1秒后开始加速
            self.key_right_time = current_time
            self.down_flag = False
            self.direction = 2
            self.timer += 1 / self.fall_speed*20
        # 绘制
        window.fill(self.BLACK)

        for i in range(len(self.grid)):
            for j in range(len(self.grid[i])):
                pygame.draw.rect(window, self.grid[i][j], (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)

        self.block.draw()
        self.draw_grid()
        self.draw_score()
        pygame.display.flip()

    def clear_rows(self):
        full_rows = []
        for i in range(len(self.grid)):
            if not self.BLACK in self.grid[i]:
                full_rows.append(i)

        for row in full_rows:
            del self.grid[row]
            self.grid.insert(0, [self.BLACK] * (WINDOW_WIDTH // BLOCK_SIZE))

        return len(full_rows)

    def draw_score(self):
        font = pygame.font.Font('resource/font/simfang.ttf', 12)
        font.set_bold(True)
        text = font.render("SCORE: " + str(self.score), True, self.WHITE)
        window.blit(text, (10, 10))

    def game_over(self):
        font = pygame.font.Font('resource/font/COOPBL.TTF', 24)
        text = font.render("GAME OVER", True, self.RED)
        window.blit(text, (WINDOW_WIDTH // 2 - text.get_width() // 2, WINDOW_HEIGHT // 2 - text.get_height() // 2))

        pygame.display.flip()
        pygame.time.wait(2000)

    def play_music(self):
        pygame.mixer.init()
        pygame.mixer.music.load('resource/music/gotime.mp3')
        pygame.mixer.music.play(-1)

    def run(self):
        self.play_music()
        self.game_running = True

        while self.game_running:
            dt = self.clock.tick(self.FPS) / 1000
            self.timer += dt
            self.event_handler()
            self.update()
        self.game_over()

class ImageButton():
    def __init__(self, x, y, image_normal, image_hover=None):
        self.rect = image_normal.get_rect(topleft=(x, y))
        self.normal_image = image_normal
        self.hover_image = image_hover if image_hover is not None else image_normal
        self.image = self.normal_image
        self.clicked = False

    def draw(self):
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.image = self.hover_image
        else:
            self.image = self.normal_image

        window.blit(self.image, self.rect)

    def check_click(self):
        mouse_pressed = pygame.mouse.get_pressed()[0]
        if self.rect.collidepoint(pygame.mouse.get_pos()) and mouse_pressed:
            self.clicked = True
            return True
        else:
            self.clicked = False
            return False

def draw_title():

    font = pygame.font.Font('resource/font/COOPBL.TTF', 40)
    text = font.render("TETRIS", True, (11, 161, 225))
    window.blit(text, (WINDOW_WIDTH // 2 - text.get_width() // 2, WINDOW_HEIGHT // 4 - text.get_height() // 2))


if __name__ == "__main__":

    # 创建开始按钮
    # 加载开始按钮图片(确保图片文件路径正确)
    start_button_img_normal = pygame.image.load('resource/icon/start.png')
    start_button_img_hover = pygame.image.load('resource/icon/start_hover.png')  # 可选:如果需要鼠标悬停效果

    background_image = pygame.image.load('resource/icon/back.png')

    start_button = ImageButton(WINDOW_WIDTH // 2 - start_button_img_normal.get_width() // 2,
                               WINDOW_HEIGHT // 2 - start_button_img_normal.get_height() // 2,
                               start_button_img_normal,
                               start_button_img_hover)
    # 游戏主循环
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if start_button.check_click():
                    Tetris().run()
        window.fill((0, 0, 0))  # 填充背景色
        window.blit(background_image, (0, 0))  # 绘制背景图片
        draw_title()
        start_button.draw()  # 绘制按钮
        pygame.display.flip()

    pygame.quit()

  • 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
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/278060
推荐阅读
相关标签
  

闽ICP备14008679号