сделай тетрис на python Создание простой версии Тетриса на Python можно реализовать с…
- User
сделай тетрис на python Создание простой версии Тетриса на Python можно реализовать с использованием библиотеки
pygame. Вот пример реализации Тетриса:import pygame import random # Размеры экрана SCREEN_WIDTH = 300 SCREEN_HEIGHT = 600 BLOCK_SIZE = 30 # Цвета COLORS = [ (0, 0, 0), # Черный (255, 0, 0), # Красный (0, 255, 0), # Зеленый (0, 0, 255), # Синий (255, 255, 0), # Желтый (0, 255, 255), # Циан (255, 0, 255), # Магента ] # Формы Тетромино SHAPES = [ [[1, 1, 1, 1]], [[1, 1, 1], [0, 1, 0]], [[1, 1], [1, 1]], [[0, 1, 1], [1, 1, 0]], [[1, 1, 0], [0, 1, 1]], [[1, 0, 0], [1, 1, 1]], [[0, 0, 1], [1, 1, 1]], ] class Tetris: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Tetris") self.clock = pygame.time.Clock() self.board = [[0] * (SCREEN_WIDTH // BLOCK_SIZE) for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)] self.current_piece = self.new_piece() self.next_piece = self.new_piece() self.game_over = False self.score = 0 def new_piece(self): shape = random.choice(SHAPES) color = COLORS[random.randint(1, len(COLORS)-1)] return {'shape': shape, 'color': color, 'x': SCREEN_WIDTH // BLOCK_SIZE // 2, 'y': 0} def draw_board(self): for y in range(len(self.board)): for x in range(len(self.board[y])): color = COLORS[self.board[y][x]] pygame.draw.rect(self.screen, color, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) pygame.draw.rect(self.screen, (200, 200, 200), (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1) def draw_piece(self, piece): shape = piece['shape'] color = piece['color'] for y, row in enumerate(shape): for x, block in enumerate(row): if block: pygame.draw.rect(self.screen, color, ((piece['x'] + x) * BLOCK_SIZE, (piece['y'] + y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) def rotate_piece(self): self.current_piece['shape'] = [list(row) for row in zip(*self.current_piece['shape'][::-1])] def clear_lines(self): for y in range(len(self.board)-1, -1, -1): if all(self.board[y]): del self.board[y] self.board.insert(0, [0] * (SCREEN_WIDTH // BLOCK_SIZE)) self.score += 100 def move_piece(self, dx, dy): self.current_piece['x'] += dx self.current_piece['y'] += dy if self.collision(): self.current_piece['x'] -= dx self.current_piece['y'] -= dy if dy > 0: self.merge_piece() self.current_piece = self.next_piece self.next_piece = self.new_piece() if self.collision(): self.game_over = True self.clear_lines() def collision(self): shape = self.current_piece['shape'] for y, row in enumerate(shape): for x, block in enumerate(row): if block: board_x = self.current_piece['x'] + x board_y = self.current_piece['y'] + y if board_x < 0 or board_x >= len(self.board[0]) or board_y < 0 or board_y >= len(self.board): return True if board_y >= 0 and self.board[board_y][board_x]: return True return False def merge_piece(self): shape = self.current_piece['shape'] for y, row in enumerate(shape): for x, block in enumerate(row): if block: self.board[self.current_piece['y'] + y][self.current_piece['x'] + x] = COLORS.index(self.current_piece['color']) def run(self): while not self.game_over: self.screen.fill((0, 0, 0)) self.draw_board() self.draw_piece(self.current_piece) for event in pygame.event.get(): if event.type == pygame.QUIT: self.game_over = True keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.move_piece(-1, 0) if keys[pygame.K_RIGHT]: self.move_piece(1, 0) if keys[pygame.K_DOWN]: self.move_piece(0, 1) if keys[pygame.K_UP]: self.rotate_piece() self.move_piece(0, 1) self.clock.tick(10) pygame.display.flip() pygame.quit() if __name__ == "__main__": game = Tetris() game.run() - Assistant
Конечно! Давайте создадим простой калькулятор на Python. Мы можем сделать это с помощью текстового интерфейса. Вот пример базового калькулятора, который может выполнять основные арифметические операции:
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: return "На ноль делить нельзя!" return x / y def calculator(): print("Выберите операцию:") print("1. Сложение") print("2. Вычитание") print("3. Умножение") print("4. Деление") while True: choice = input("Введите номер операции (1/2/3/4) или 'q' для выхода: ") if choice == 'q': print("Выход из программы.") break if choice in ('1', '2', '3', '4'): try: num1 = float(input("Введите первое число: ")) num2 = float(input("Введите второе число: ")) except ValueError: print("Пожалуйста, введите действительное число.") continue if choice == '1': print(f"{num1} + {num2} = {add(num1, num2)}") elif choice == '2': print(f"{num1} - {num2} = {subtract(num1, num2)}") elif choice == '3': print(f"{num1} * {num2} = {multiply(num1, num2)}") elif choice == '4': print(f"{num1} / {num2} = {divide(num1, num2)}") else: print("Неверный ввод, попробуйте снова.") if __name__ == "__main__": calculator()