談到記憶里的小游戲,俄羅斯方塊是大家一定會想到的一款游戲,自己寫出來的應(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)注私信我哦~