fork download
  1. # your code goes here
Success #stdin #stdout 0.04s 62936KB
stdin
import pygame
import random

# 設定
SCREEN_WIDTH, SCREEN_HEIGHT = 300, 600
BLOCK_SIZE = 30
COLUMNS, ROWS = SCREEN_WIDTH // BLOCK_SIZE, SCREEN_HEIGHT // BLOCK_SIZE

# ミノの形(座標)
SHAPES = [
    [[1, 1, 1, 1]], # I
    [[1, 1], [1, 1]], # O
    [[0, 1, 0], [1, 1, 1]], # T
    [[1, 1, 0], [0, 1, 1]], # S
    [[0, 1, 1], [1, 1, 0]], # Z
]

class Tetris:
    def __init__(self):
        self.grid = [[0 for _ in range(COLUMNS)] for _ in range(ROWS)]
        self.new_piece()

    def new_piece(self):
        self.shape = random.choice(SHAPES)
        self.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
        self.x, self.y = COLUMNS // 2 - len(self.shape[0]) // 2, 0

    def move(self, dx, dy):
        if not self.check_collision(self.x + dx, self.y + dy):
            self.x += dx
            self.y += dy
            return True
        return False

    def check_collision(self, nx, ny):
        for r, row in enumerate(self.shape):
            for c, val in enumerate(row):
                if val:
                    if nx + c < 0 or nx + c >= COLUMNS or ny + r >= ROWS or self.grid[ny + r][nx + c]:
                        return True
        return False

    def freeze(self):
        for r, row in enumerate(self.shape):
            for c, val in enumerate(row):
                if val: self.grid[self.y + r][self.x + c] = self.color
        self.clear_rows()
        self.new_piece()

    def clear_rows(self):
        self.grid = [row for row in self.grid if any(v == 0 for v in row)]
        while len(self.grid) < ROWS:
            self.grid.insert(0, [0 for _ in range(COLUMNS)])

def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    clock = pygame.time.Clock()
    game = Tetris()
    drop_time = 0

    while True:
        screen.fill((0, 0, 0))
        drop_time += clock.get_rawtime()
        clock.tick()

        if drop_time > 500: # 0.5秒ごとに落下
            if not game.move(0, 1): game.freeze()
            drop_time = 0

        for event in pygame.event.get():
            if event.type == pygame.QUIT: return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT: game.move(-1, 0)
                if event.key == pygame.K_RIGHT: game.move(1, 0)
                if event.key == pygame.K_DOWN: game.move(0, 1)

        # 描画
        for r, row in enumerate(game.grid):
            for c, val in enumerate(row):
                if val: pygame.draw.rect(screen, val, (c*BLOCK_SIZE, r*BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1))
        for r, row in enumerate(game.shape):
            for c, val in enumerate(row):
                if val: pygame.draw.rect(screen, game.color, ((game.x+c)*BLOCK_SIZE, (game.y+r)*BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1))
        
        pygame.display.flip()

if __name__ == "__main__":
    main()
stdout
Standard output is empty