gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
Can you code Tetris in Python usin ascii art?
- User
Can you code Tetris in Python usin ascii art?
- Assistant
Yes, it is possible to code Tetris in Python using ASCII art. Here is an example implementation:
import random import time # This function draws the game board with the current state of the game def drawBoard(board, score): print("Score:", score) print("+-" * len(board[0]) + "+") for row in board: print("|" + "".join(row) + "|") print("+-" * len(board[0]) + "+") # This function checks if a shape can be placed at a specific location def isLegalMove(board, shape, x, y): for i in range(len(shape)): for j in range(len(shape[0])): if shape[i][j] == "#" and (y+i >= len(board) or x+j < 0 or x+j >= len(board[0]) or board[y+i][x+j] != "-"): return False return True # This function removes any completed rows and updates the score def removeCompletedRows(board, score): rowsToRemove = [] for y in range(len(board)): if "-" not in board[y]: rowsToRemove.append(y) for y in rowsToRemove: board.pop(y) score += 1 board.insert(0, ["-"] * len(board[0])) return score # This is the main game loop def tetrisGame(): shapes = [ [["#", "#"], ["#", "#"]], # Square [["#", "#", "#", "#"]], # Line [[".", ".", "#"], ["#", "#", "#"]], # L [["#", ".", "."], ["#", "#", "#"]], # Reverse L [[".", "#", "#"], ["#", "#", "."]], # Z [["#", "#", "."], [".", "#", "#"]] # Reverse Z ] boardWidth = 12 boardHeight = 20 board = [["-"] * boardWidth for y in range(boardHeight)] score = 0 currentShape = random.choice(shapes) currentShapeX = boardWidth // 2 - len(currentShape[0]) // 2 currentShapeY = 0 while True: # Check for completed rows and update the score score = removeCompletedRows(board, score) # Check if the current shape can be moved down if isLegalMove(board, currentShape, currentShapeX, currentShapeY+1): currentShapeY += 1 # If the current shape can't be moved down, place it on the board else: for i in range(len(currentShape)): for j in range(len(currentShape[0])): if currentShape[i][j] == "#": board[currentShapeY+i][currentShapeX+j] = "#" # Choose a new shape to use and place it at the top of the board currentShape = random.choice(shapes) currentShapeX = boardWidth // 2 - len(currentShape[0]) // 2 currentShapeY = 0 # Check if the new shape can be placed at the top of the board if not isLegalMove(board, currentShape, currentShapeX, currentShapeY): break # Game over # Draw the current state of the board drawBoard(board, score) time.sleep(0.5) # Wait for a bit before redrawing # Start the game tetrisGame()Note: This implementation uses "#" to represent the blocks of the Tetris shapes and "-" to represent empty spaces on the board. Feel free to modify the implementation to use different symbols for the blocks and empty spaces.