Juego Tetris - ejemplo en Python (Pygame)
Ejemplo de código y notas.
# tetris_minimal.py - requiere pygame
import pygame, random
pygame.init()
WIDTH, HEIGHT = 200, 400
CELL=20; COLS=10; ROWS=20
screen=pygame.display.set_mode((WIDTH,HEIGHT))
clock=pygame.time.Clock()
SHAPES=[[[1,1,1,1]], [[1,1],[1,1]], [[0,1,1],[1,1,0]], [[1,1,0],[0,1,1]], [[1,1,1],[0,1,0]]]
def new_piece(): return [random.choice(SHAPES), (COLS//2-1, 0)]
grid=[[0]*COLS for _ in range(ROWS)]
piece, (px,py) = new_piece()
def collide(shape,x,y):
for r,row in enumerate(shape):
for c,val in enumerate(row):
if val:
gx=x+c; gy=y+r
if gx<0 or gx>=COLS or gy>=ROWS or (gy>=0 and grid[gy][gx]): return True
return False
running=True; drop_timer=0
while running:
dt=clock.tick(10); drop_timer+=dt
for e in pygame.event.get():
if e.type==pygame.QUIT: running=False
if e.type==pygame.KEYDOWN:
if e.key==pygame.K_LEFT and not collide(piece[0], px-1, py): px-=1
if e.key==pygame.K_RIGHT and not collide(piece[0], px+1, py): px+=1
if e.key==pygame.K_DOWN and not collide(piece[0], px, py+1): py+=1
if e.key==pygame.K_UP: piece[0]=list(zip(*piece[0][::-1])) # rotar
if drop_timer>500:
drop_timer=0
if not collide(piece[0], px, py+1): py+=1
else:
for r,row in enumerate(piece[0]):
for c,val in enumerate(row):
if val and py+r>=0: grid[py+r][px+c]=1
piece, (px,py)=new_piece()
if collide(piece[0], px, py): running=False
screen.fill((0,0,0))
for r in range(ROWS):
for c in range(COLS):
if grid[r][c]: pygame.draw.rect(screen,(100,200,100),(c*CELL,r*CELL,CELL-1,CELL-1))
for r,row in enumerate(piece[0]):
for c,val in enumerate(row):
if val and py+r>=0:
pygame.draw.rect(screen,(200,100,100),((px+c)*CELL,(py+r)*CELL,CELL-1,CELL-1))
pygame.display.flip()
pygame.quit()
Notas finales
Adapte rutas, credenciales y pruebe en entorno controlado antes de usar en producción.