相信大家都玩過俄羅斯方塊吧,應該是小時候的回憶吧,但是想不想了解一下這個程式是怎么寫出來的呢,自己寫出來的應該玩起來更有感覺吧!
感徑訓是蠻好玩吧!
接下來,我就分享一下這個游戲的原始碼程序啊!
先用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()
這樣就可以寫出來一個十分簡單的俄羅斯方塊啦,是不是覺得還不錯呢!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/242394.html
標籤:python
上一篇:LeetCode筆記:Biweekly Contest 42 比賽記錄
下一篇:pandas:缺失值處理
