1. 程式人生 > 實用技巧 >童年的記憶——如何用python寫一個俄羅斯方塊小遊戲!

童年的記憶——如何用python寫一個俄羅斯方塊小遊戲!

談到記憶裡的小遊戲,俄羅斯方塊是大家一定會想到的一款遊戲,自己寫出來的應該玩起來更有感覺,然後就寫了一個俄羅斯方塊的遊戲
給大家分享一下這個遊戲的原始碼

先用python建立一個py檔案

定義這次程式所需要的類

import sys

import time

import pygame

from pygame.localsimport *

import blocks

然後寫出它所需要的模組

SIZE =30 # 每個小方格大小

BLOCK_HEIGHT =25  # 遊戲區高度

BLOCK_WIDTH =10  # 遊戲區寬度

BORDER_WIDTH =4  # 遊戲區邊框寬度

BORDER_COLOR = (40, 40, 200)# 遊戲區邊框顏色

SCREEN_WIDTH = SIZE * (BLOCK_WIDTH +5)# 遊戲螢幕的寬

SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT# 遊戲螢幕的高

BG_COLOR = (40, 40, 60)# 背景色

BLOCK_COLOR = (20, 128, 200)#

BLACK = (0, 0, 0)

RED = (200, 30, 30)# GAME OVER 的字型顏色


# 畫背景

```python

```python
def _draw_background(screen):
    # 填充背景色
    screen.fill(BG_COLOR)
    # 畫遊戲區域分隔線
    pygame.draw.line(screen, BORDER_COLOR,
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)

# 畫網格線

```python
def _draw_gridlines(screen):
    # 畫網格線 豎線
    for x in range(BLOCK_WIDTH):
        pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
    # 畫網格線 橫線
    for y in range(BLOCK_HEIGHT):
        pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)

畫已經落下的方塊

def _draw_game_area(screen, game_area):
    if game_area:
        for i, row in enumerate(game_area):
            for j, cell in enumerate(row):
                if cell != '.':
                    pygame.draw.rect(screen, BLOCK_COLOR, (j * SIZE, i * SIZE, SIZE, SIZE), 0)

畫單個方塊

def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
    if block:
        for i in range(block.start_pos.Y, block.end_pos.Y + 1):
            for j in range(block.start_pos.X, block.end_pos.X + 1):
                if block.template[i][j] != '.':
                    pygame.draw.rect(screen, BLOCK_COLOR,
                                     (offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)

畫得分等資訊

def _draw_info(screen, font, pos_x, font_height, score):
    print_text(screen, font, pos_x, 10, f'得分: ')
    print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
    print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
    print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
    print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一個:')

if __name__ == '__main__':
    main()

這樣就可以寫出來一個十分簡單的俄羅斯方塊啦,是不是覺得還不錯呢!


image.png

總結

以上就是俄羅斯方塊的原始碼過程,大家可以寫一下玩一玩
我是白白,一個喜歡學習喜歡程式設計的年輕人
想學習python的可以關注私信我哦~
歡迎小白、萌新、大佬加入我們
小白學習交流基地【(九七四)(七二四)(八九四)】