正在学习俄罗斯方块(Tetris Game)游戏, 主要参考Tetris with PyGame | Python Assets,不过有所修改,原作的class 太复杂, 不好理解, 试图用自己习惯的方法的完成。 第一步画5个方块,原文用Tuples, 不过本人喜欢list:
import pygame
import random
import numpy as np
WINDOW_WIDTH, WINDOW_HEIGHT = 500, 601
GRID_WIDTH, GRID_HEIGHT = 300, 600
TILE_SIZE = 30
class SquareBlock():
struct = [
[1, 1],
[1, 1]
]
color=(250,0,0)
class TBlock():
struct = [
[1, 1, 1],
[0, 1, 0]
]
color=(0,250,0)
class IBlock():
struct = [
[1],
[1],
[1],
[1]
]
color=(0,0,250)
class LBlock():
struct = [
[1, 1],
[1, 0],
[1, 0],
]
color=(200,0,100)
class ZBlock():
struct = [
[0, 1],
[1, 1],
[1, 0],
]
color=(200,200,0)
def block_draw(screen,block,x=0,y=0,draw_mask=None):
width = len(block.struct[0]) * TILE_SIZE
height = len(block.struct) * TILE_SIZE
image = pygame.surface.Surface([width, height])
rect = pygame.Rect(x, y, width, height) #for .blit(image,rect)
image.set_colorkey((0, 0, 0))
for y, row in enumerate(block.struct):
for x, col in enumerate(row):
if col:
pygame.draw.rect(image,block.color,
pygame.Rect(x*TILE_SIZE+1, y*TILE_SIZE+1 ,
TILE_SIZE-2, TILE_SIZE-2))
mask = pygame.mask.from_surface(image)
screen.blit(image,rect)
def checkEvents():
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pygame.init()
screen=pygame.display.set_mode((800,600))
blocks=[SquareBlock(),TBlock(),IBlock(),LBlock(),ZBlock()]
run=True
while run:
checkEvents()
screen.fill((0,0,0))
for i in range(len(blocks)):
block_draw(screen,blocks[i],50+i*100,100)
pygame.display.update()