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

談到記憶裏的小遊戲,俄羅斯方塊是你們必定會想到的一款遊戲,本身寫出來的應該玩起來更有感受,而後就寫了一個俄羅斯方塊的遊戲
給你們分享一下這個遊戲的源碼python

先用python建立一個py文件編程

定義此次程序所須要的類markdown

import sys

import time

import pygame

from pygame.localsimport *

import blocks
123456789
複製代碼

而後寫出它所須要的模塊學習

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 的字體顏色
123456789101112131415161718192021

# 畫背景

```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)
12345678910111213

# 畫網格線

```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)
12345678910
複製代碼

畫已經落下的方塊

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)
123456
複製代碼

畫單個方塊

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)
1234567
複製代碼

畫得分等信息

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()
12345678910
複製代碼

這樣就能夠寫出來一個十分簡單的俄羅斯方塊啦,是否是以爲還不錯呢!字體

總結

以上就是俄羅斯方塊的源碼過程,你們能夠寫一下玩一玩
我是海海,一個喜歡學習喜歡編程的年輕人
想學習python的能夠關注私信我哦~spa

相關文章
相關標籤/搜索