Загрузка данных
import pygame
import random
# Инициализация Pygame
pygame.font.init()
# Параметры окна и сетки
s_width = 800
s_height = 700
play_width = 300 # 10 столбцов по 30px
play_height = 600 # 20 строк по 30px
block_size = 30
top_left_x = (s_width - play_width) // 2
top_left_y = s_height - play_height - 50
# Формы тетрамино и их цвета
SHAPES = [
[['.....',
'.....',
'..00.',
'.00..',
'.....'],
['.....',
'..0..',
'..00.',
'...0.',
'.....']],
[['.....',
'.....',
'.00..',
'..00.',
'.....'],
['.....',
'..0..',
'.00..',
'.0...',
'.....']],
[['.....',
'..0..',
'..0..',
'..0..',
'..0..'],
['.....',
'0000.',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'.00..',
'.00..',
'.....']],
[['.....',
'.0...',
'.000.',
'.....',
'.....'],
['.....',
'..00.',
'..0..',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'...0.',
'.....'],
['.....',
'..0..',
'..0..',
'.00..',
'.....']],
[['.....',
'...0.',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..0..',
'..00.',
'.....'],
['.....',
'.....',
'.000.',
'.0...',
'.....'],
['.....',
'.00..',
'..0..',
'..0..',
'.....']],
[['.....',
'..0..',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..00.',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'..0..',
'.....'],
['.....',
'..0..',
'.00..',
'..0..',
'.....']]
]
SHAPE_COLORS = [
(0, 255, 0), # S
(255, 0, 0), # Z
(0, 255, 255), # I
(255, 255, 0), # O
(255, 165, 0), # L
(0, 0, 255), # J
(128, 0, 128) # T
]
class Piece(object):
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0
def create_grid(locked_pos={}):
grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j, i) in locked_pos:
c = locked_pos[(j, i)]
grid[i][j] = c
return grid
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((shape.x + j - 2, shape.y + i - 4))
return positions
def valid_space(shape, grid):
accepted_pos = [[(j, i) for j in range(10) if grid[i][j] == (0, 0, 0)] for i in range(20)]
accepted_pos = [j for sub in accepted_pos for j in sub]
formatted = convert_shape_format(shape)
for pos in formatted:
if pos not in accepted_pos:
if pos[1] > -1:
return False
return True
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
return Piece(5, 0, random.choice(SHAPES))
def draw_text_middle(surface, text, size, color):
font = pygame.font.SysFont("comicsans", size, bold=True)
label = font.render(text, 1, color)
surface.blit(label, (top_left_x + play_width / 2 - (label.get_width() / 2),
top_left_y + play_height / 2 - (label.get_height() / 2)))
def draw_grid(surface, grid):
for i in range(len(grid)):
pygame.draw.line(surface, (128, 128, 128), (top_left_x, top_left_y + i * block_size),
(top_left_x + play_width, top_left_y + i * block_size))
for j in range(len(grid[i])):
pygame.draw.line(surface, (128, 128, 128), (top_left_x + j * block_size, top_left_y),
(top_left_x + j * block_size, top_left_y + play_height))
def clear_rows(grid, locked):
inc = 0
ind = len(grid) - 1
for i in range(len(grid) - 1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
inc += 1
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
for key in sorted(list(locked), key=lambda x: x[1], reverse=True):
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
return inc
def draw_window(surface, grid, score=0):
surface.fill((0, 0, 0))
pygame.font.init()
font = pygame.font.SysFont("comicsans", 60)
label = font.render("ТЕТРИС", 1, (255, 255, 255))
surface.blit(label, (top_left_x + play_width / 2 - (label.get_width() / 2), 30))
font = pygame.font.SysFont("comicsans", 30)
label = font.render("Счет: " + str(score), 1, (255, 255, 255))
surface.blit(label, (top_left_x + play_width + 50, top_left_y + 150))
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
(top_left_x + j * block_size, top_left_y + i * block_size, block_size, block_size), 0)
draw_grid(surface, grid)
pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_left_y, play_width, play_height), 5)
def main():
locked_positions = {}
grid = create_grid(locked_positions)
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.27
score = 0
win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption("Тетрис на Pygame")
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= fall_speed:
fall_time = 0
current_piece.y += 1
if not (valid_space(current_piece, grid)) and current_piece.y > 0:
current_piece.y -= 1
change_piece = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
elif event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
elif event.key == pygame.K_UP:
current_piece.rotation += 1
if not valid_space(current_piece, grid):
current_piece.rotation -= 1
shape_pos = convert_shape_format(current_piece)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
if change_piece:
for pos in shape_pos:
locked_positions[pos] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
score += clear_rows(grid, locked_positions) * 10
draw_window(win, grid, score)
pygame.display.update()
if check_lost(locked_positions):
run = False
draw_window(win, grid, score)
draw_text_middle(win, "ВЫ ПРОИГРАЛИ", 40, (255, 255, 255))
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
if __name__ == '__main__':
main()