童年的記憶——如何用python寫一個(gè)俄羅斯方塊小游戲!

談到記憶里的小游戲,俄羅斯方塊是大家一定會想到的一款游戲,自己寫出來的應(yīng)該玩起來更有感覺,然后就寫了一個(gè)俄羅斯方塊的游戲
給大家分享一下這個(gè)游戲的源碼

先用python創(chuàng)建一個(gè)py文件

定義這次程序所需要的類

import sys

import time

import pygame

from pygame.localsimport *

import blocks

然后寫出它所需要的模塊

SIZE =30 # 每個(gè)小方格大小

BLOCK_HEIGHT =25  # 游戲區(qū)高度

BLOCK_WIDTH =10  # 游戲區(qū)寬度

BORDER_WIDTH =4  # 游戲區(qū)邊框?qū)挾?
BORDER_COLOR = (40, 40, 200)# 游戲區(qū)邊框顏色

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)
    # 畫游戲區(qū)域分隔線
    pygame.draw.line(screen, BORDER_COLOR,
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)

# 畫網(wǎng)格線

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

畫已經(jīng)落下的方塊

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)

畫單個(gè)方塊

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'下一個(gè):')

if __name__ == '__main__':
    main()

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

image.png

總結(jié)

以上就是俄羅斯方塊的源碼過程,大家可以寫一下玩一玩
我是白白,一個(gè)喜歡學(xué)習(xí)喜歡編程的年輕人
想學(xué)習(xí)python的可以關(guān)注私信我哦~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容