Dataset Viewer
Auto-converted to Parquet Duplicate
task_id
int64
1
130
prompt
stringlengths
76
1.13k
entry_point
stringlengths
4
27
canonical_solution
stringlengths
8
2.49k
test
stringclasses
1 value
1
def initialize_game(): """ Sets up the game environment, including the game board, snake, food, and score. The dependent functions are: create_board(width:int, height:int) -> list: Creates an empty game board with specified dimensions. initialize_snake(start_x:int, start_y:int, length:int) -> l...
initialize_game
width, height = 20, 20 board = create_board(width, height) snake = initialize_snake(width // 2, height // 2, 3) food = generate_food(board, snake) return { 'board': board, 'snake': snake, 'food': food, 'direction': 'RIGHT', 'score': 0, 'game_over'...
def check(candidate): pass
2
def create_board(width: int, height: int) -> list: """ Creates an empty game board with specified dimensions. Args: width (int): Width of the game board height (int): Height of the game board Returns: list: 2D grid representing the game board """
create_board
return [[0 for _ in range(width)] for _ in range(height)]
def check(candidate): pass
3
def initialize_snake(start_x: int, start_y: int, length: int) -> list: """ Creates the initial snake with a specified length at a starting position. Args: start_x (int): Starting x-coordinate of the snake's head start_y (int): Starting y-coordinate of the snake's head length (in...
initialize_snake
snake = [] for i in range(length): snake.append((start_x - i, start_y)) return snake
def check(candidate): pass
4
def generate_food(board: list, snake: list) -> tuple: """ Places food at a random position on the board that is not occupied by the snake. Args: board (list): 2D grid representing the game board snake (list): List of (x, y) coordinates representing the snake's body Returns: ...
generate_food
width = len(board[0]) height = len(board) while True: x = random.randint(0, width - 1) y = random.randint(0, height - 1) if (x, y) not in snake: return (x, y)
def check(candidate): pass
5
def handle_input(current_direction: str, key_pressed: str) -> str: """ Processes keyboard input to change the snake's direction. Args: current_direction (str): Current direction of the snake (up, down, left, right) key_pressed (str): Key pressed by the player Returns: s...
handle_input
if key_pressed == 'UP' and current_direction != 'DOWN': return 'UP' elif key_pressed == 'DOWN' and current_direction != 'UP': return 'DOWN' elif key_pressed == 'LEFT' and current_direction != 'RIGHT': return 'LEFT' elif key_pressed == 'RIGHT' and current_direction != 'LEFT': ...
def check(candidate): pass
6
def update_game_state(game_state: dict) -> dict: """ Updates the game state based on the current direction, handling movement, collisions, and growth. The dependent functions are: move_snake(snake: list, direction: str, grow: bool) -> list: Moves the snake in the current direction by updating it...
update_game_state
snake = game_state['snake'] direction = game_state['direction'] board = game_state['board'] food = game_state['food'] score = game_state['score'] grow, new_food, new_score = handle_food_collision(snake, food, board, score) new_snake = move_snake(snake, direction, grow) board_width = le...
def check(candidate): pass
7
def move_snake(snake: list, direction: str, grow: bool) -> list: """ Moves the snake in the current direction by updating its position. """
move_snake
head_x, head_y = snake[0] if direction == 'UP': new_head = (head_x, head_y - 1) elif direction == 'DOWN': new_head = (head_x, head_y + 1) elif direction == 'LEFT': new_head = (head_x - 1, head_y) elif direction == 'RIGHT': new_head = (head_x + 1, head_y) new_sna...
def check(candidate): pass
8
def check_collision(snake: list, board_width: int, board_height: int) -> bool: """ Checks if the snake has collided with the wall or itself. """
check_collision
head_x, head_y = snake[0] # Check wall collision if head_x < 0 or head_x >= board_width or head_y < 0 or head_y >= board_height: return True # Check self collision (skip the head) if snake[0] in snake[1:]: return True return False
def check(candidate): pass
9
def handle_food_collision(snake: list, food: tuple, board: list, score: int) -> tuple: """ Checks if the snake has eaten food and handles the consequences. Parameters: snake (list): List of coordinates representing the snake's body food (tuple): (x, y) coordinates of the food board (...
handle_food_collision
if snake[0] == food: score += 1 new_food = generate_food(board, snake) return True, new_food, score return False, food, score
def check(candidate): pass
10
def render_game(game_state: dict, screen: pygame.Surface) -> None: """ Draws the current game state on the screen. Parameters: game_state (dict): Current game state screen (pygame.Surface): Pygame surface to draw on Returns: None: Updates the display The dependent functions a...
render_game
board = game_state['board'] snake = game_state['snake'] food = game_state['food'] score = game_state['score'] cell_size = screen.get_width() // len(board[0]) draw_board(screen, board) draw_snake(screen, snake, cell_size) draw_food(screen, food, cell_size) draw_score(screen, score) ...
def check(candidate): pass
11
def draw_board(screen: pygame.Surface, board: list) -> None: """ Draws the game board on the screen. Parameters: screen (pygame.Surface): Pygame surface to draw on board (list): The game board Returns: None: Draws the board on the screen """
draw_board
width = len(board[0]) height = len(board) cell_size = screen.get_width() // width screen.fill((0, 0, 0)) for y in range(height): for x in range(width): rect = pygame.Rect(x * cell_size, y * cell_size, cell_size, cell_size) pygame.draw.rect(screen, (50, 50, 50), rect,...
def check(candidate): pass
12
def draw_snake(screen: pygame.Surface, snake: list, cell_size: int) -> None: """ Draws the snake on the screen. Parameters: screen (pygame.Surface): Pygame surface to draw on snake (list): List of coordinates representing the snake's body cell_size (int): Size of each cell in pixels ...
draw_snake
for i, (x, y) in enumerate(snake): rect = pygame.Rect(x * cell_size, y * cell_size, cell_size, cell_size) if i == 0: # Head pygame.draw.rect(screen, (0, 255, 0), rect) else: # Body pygame.draw.rect(screen, (0, 200, 0), rect) pygame.draw.rect(screen, (0, 100,...
def check(candidate): pass
13
def draw_food(screen: pygame.Surface, food: tuple, cell_size: int) -> None: """ Draws the food on the screen. Parameters: screen (pygame.Surface): Pygame surface to draw on food (tuple): (x, y) coordinates of the food cell_size (int): Size of each cell in pixels Returns: ...
draw_food
x, y = food rect = pygame.Rect(x * cell_size, y * cell_size, cell_size, cell_size) pygame.draw.rect(screen, (255, 0, 0), rect)
def check(candidate): pass
14
def draw_score(screen: pygame.Surface, score: int) -> None: """ Displays the current score on the screen. Parameters: screen (pygame.Surface): Pygame surface to draw on score (int): Current score Returns: None: Displays the score on the screen """
draw_score
font = pygame.font.SysFont('Arial', 25) score_text = font.render(f'Score: {score}', True, (255, 255, 255)) screen.blit(score_text, (10, 10))
def check(candidate): pass
15
def show_game_over(screen: pygame.Surface, score: int) -> bool: """ Displays the game over screen with final score and restart option. Parameters: screen (pygame.Surface): Pygame surface to draw on score (int): Final score Returns: bool: True if player wants to restart, False oth...
show_game_over
screen.fill((0, 0, 0)) font_large = pygame.font.SysFont('Arial', 50) font_small = pygame.font.SysFont('Arial', 30) game_over_text = font_large.render('GAME OVER', True, (255, 0, 0)) score_text = font_small.render(f'Final Score: {score}', True, (255, 255, 255)) restart_text = font_small.render(...
def check(candidate): pass
16
def main_game_loop() -> None: """ Main game loop that handles game flow, input, updates, and rendering. Returns: None: Runs the game until exit The dependent functions are: initialize_game() -> dict: Sets up the game environment, including the game board, snake, food, and score. ...
main_game_loop
pygame.init() screen_width, screen_height = 600, 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Snake Game') clock = pygame.time.Clock() game_state = initialize_game() while True: if game_state['game_over']: restart = sho...
def check(candidate): pass
17
def initialize_game() -> dict: """ Sets up the game environment, initializes pygame, creates the game window, and loads necessary resources. Returns: dict: Game state containing screen, clock, and other initialization variables The dependent functions are: load_resources() -> dict: L...
initialize_game
pygame.init() # Define screen dimensions screen_width = 800 screen_height = 600 # Create game window screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Brick Breaker") # Initialize clock clock = pygame.time.Clock() # Load resources ...
def check(candidate): pass
18
def load_resources() -> dict: """ Loads game resources like images, sounds, and fonts. Returns: dict: Dictionary containing loaded game resources """
load_resources
resources = {} # Load fonts pygame.font.init() resources["font_small"] = pygame.font.SysFont("Arial", 20) resources["font_medium"] = pygame.font.SysFont("Arial", 30) resources["font_large"] = pygame.font.SysFont("Arial", 50) # Define colors resources["colors"] = { "white": (255...
def check(candidate): pass
19
def initialize_game() -> dict: """ Sets up the game environment, creates the initial game board, and generates the first two tiles. Returns: dict: Initial game state containing the board, score, and game status The dependent functions are: create_empty_board() -> list[list[int]]: Cre...
initialize_game
board = create_empty_board() board = add_new_tile(board) board = add_new_tile(board) return { 'board': board, 'score': 0, 'game_over': False, 'won': False, 'continue_after_win': False }
def check(candidate): pass
20
def create_empty_board() -> list[list[int]]: """ Creates an empty 4x4 grid filled with zeros. Returns: list[list[int]]: A 4x4 grid represented as a 2D list filled with zeros """
create_empty_board
return [[0 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
def check(candidate): pass
21
def add_new_tile(board: list[list[int]]) -> list[list[int]]: """ Adds a new tile (value 2 or 4) at a random empty position on the board. Parameters: board (list[list[int]]): Current game board Returns: list[list[int]]: Updated game board with a new tile The dependent functions are: ...
add_new_tile
empty_positions = get_empty_positions(board) if empty_positions: i, j = random.choice(empty_positions) board[i][j] = 2 if random.random() < 0.9 else 4 return board
def check(candidate): pass
22
def get_empty_positions(board: list[list[int]]) -> list[tuple[int, int]]: """ Finds all empty positions (cells with value 0) on the board. Parameters: board (list[list[int]]): Current game board Returns: list[tuple[int, int]]: List of (row, column) coordinates of empty cells """
get_empty_positions
empty_positions = [] for i in range(GRID_SIZE): for j in range(GRID_SIZE): if board[i][j] == 0: empty_positions.append((i, j)) return empty_positions
def check(candidate): pass
23
def move(board: list[list[int]], direction: str, score: int) -> tuple[list[list[int]], int, bool]: """ Processes a move in the specified direction, sliding and merging tiles accordingly. Parameters: board (list[list[int]]): Current game board direction (str): Direction to move tiles ('up', '...
move
original_board = [row[:] for row in board] # Apply transformations based on direction if direction == 'up': board = transpose(board) board, score, changed = move_left(board, score) board = transpose(board) elif direction == 'down': board = transpose(board) board ...
def check(candidate): pass
24
def transpose(board: list[list[int]]) -> list[list[int]]: """ Transposes the board matrix (swaps rows and columns). Parameters: board (list[list[int]]): Current game board Returns: list[list[int]]: Transposed game board """
transpose
return [[board[j][i] for j in range(GRID_SIZE)] for i in range(GRID_SIZE)]
def check(candidate): pass
25
def reverse(board: list[list[int]]) -> list[list[int]]: """ Reverses each row in the board. Parameters: board (list[list[int]]): Current game board Returns: list[list[int]]: Board with each row reversed """
reverse
return [row[::-1] for row in board]
def check(candidate): pass
26
def move_left(board: list[list[int]], score: int) -> tuple[list[list[int]], int, bool]: """ Implements the core logic for moving tiles to the left, merging identical tiles, and updating the score. Parameters: board (list[list[int]]): Current game board score (int): Current score Returns:...
move_left
changed = False new_board = [row[:] for row in board] new_score = score for i in range(GRID_SIZE): # Compress the row (move all non-zero elements to the left) row = [tile for tile in new_board[i] if tile != 0] # Merge adjacent same-value tiles j = 0 while j < len...
def check(candidate): pass
27
def check_game_over(board: list[list[int]]) -> bool: """ Checks if the game is over by determining if there are any valid moves left. Parameters: board (list[list[int]]): Current game board Returns: bool: True if the game is over, False otherwise The dependent functions are: can_...
check_game_over
return not can_move(board)
def check(candidate): pass
28
def can_move(board: list[list[int]]) -> bool: """ Checks if any move (up, down, left, right) is possible on the current board. Parameters: board (list[list[int]]): Current game board Returns: bool: True if at least one move is possible, False otherwise """
can_move
if any(0 in row for row in board): return True # Check if there are any adjacent cells with the same value for i in range(GRID_SIZE): for j in range(GRID_SIZE): current = board[i][j] # Check right if j < GRID_SIZE - 1 and board[i][j + 1] == current: ...
def check(candidate): pass
29
def check_win(board: list[list[int]]) -> bool: """ Checks if the player has won by having a tile with value 2048. Parameters: board (list[list[int]]): Current game board Returns: bool: True if a 2048 tile exists, False otherwise """
check_win
return any(2048 in row for row in board)
def check(candidate): pass
30
def render_board(board: list[list[int]], score: int, game_over: bool, won: bool) -> None: """ Renders the game board on the screen with appropriate styling for different tile values. Parameters: board (list[list[int]]): Current game board score (int): Current score game_over (bool): ...
render_board
screen.fill(BACKGROUND_COLOR) # Draw score font = pygame.font.SysFont('Arial', 24) score_text = font.render(f"Score: {score}", True, TEXT_COLOR) screen.blit(score_text, (20, 20)) # Draw grid background pygame.draw.rect(screen, EMPTY_TILE_COLOR, (0, 100, SCREEN_WIDTH, SCREEN_WIDTH), 0, 10) ...
def check(candidate): pass
31
def get_tile_color(value: int) -> str: """ Determines the background color for a tile based on its value. Parameters: value (int): Tile value Returns: str: CSS color code for the tile background """
get_tile_color
return TILE_COLORS.get(value, TILE_COLORS[8192])
def check(candidate): pass
32
def get_tile_text_color(value: int) -> str: """ Determines the text color for a tile based on its value. Parameters: value (int): Tile value Returns: str: CSS color code for the tile text """
get_tile_text_color
return TILE_TEXT_COLORS.get(value, TILE_TEXT_COLORS[8192])
def check(candidate): pass
33
def handle_keypress(key: str, game_state: dict) -> dict: """ Handles keyboard input to control the game. Parameters: key (str): Key pressed by the user game_state (dict): Current game state containing board, score, and status Returns: dict: Updated game state after processing the...
handle_keypress
if game_state['game_over']: return game_state old_board = [row[:] for row in game_state['board']] direction = None if key == K_UP: direction = 'up' elif key == K_DOWN: direction = 'down' elif key == K_LEFT: direction = 'left' elif key == K_RIGHT: dir...
def check(candidate): pass
34
def restart_game() -> dict: """ Resets the game to its initial state. Returns: dict: Fresh game state with new board, zero score, and active status The dependent functions are: initialize_game() -> dict: Sets up the game environment, creates the initial game board, and generates the ...
restart_game
return initialize_game()
def check(candidate): pass
35
def animate_tile_movement(old_board: list[list[int]], new_board: list[list[int]], direction: str) -> None: """ Creates smooth animations for tile movements and merges. Parameters: old_board (list[list[int]]): Board state before the move new_board (list[list[int]]): Board state after the move...
animate_tile_movement
frames = 5 for _ in range(frames): pygame.time.delay(30) render_board(new_board, game_state['score'], game_state['game_over'], game_state['won'])
def check(candidate): pass
36
def main() -> None: """ Main game loop that initializes the game, handles user input, and updates the display. Returns: None: Runs the game until user exits The dependent functions are: initialize_game() -> dict: Sets up the game environment, creates the initial game board, and gener...
main
global screen, game_state # Set up the display screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('2048 Game') # Initialize game state game_state = initialize_game() # Main game loop clock = pygame.time.Clock() running = True while runn...
def check(candidate): pass
37
def initialize_game() -> None: """ Sets up the game window, loads assets, and initializes game variables. The dependent functions are: load_assets() -> None: Loads all game images and sounds from files. create_bird() -> None: Creates the bird character with initial position and physi...
initialize_game
global bird, ground, pipes, last_pipe load_assets() bird = create_bird() ground = create_ground() pipes = initialize_pipes() last_pipe = pygame.time.get_ticks()
def check(candidate): pass
38
def load_assets() -> None: """ Loads all game images and sounds from files. """
load_assets
pass
def check(candidate): pass
39
def create_bird() -> None: """ Creates the bird character with initial position and physics properties. """
create_bird
return { 'x': SCREEN_WIDTH // 4, 'y': SCREEN_HEIGHT // 2, 'width': 30, 'height': 30, 'velocity': 0, 'alive': True, 'rect': pygame.Rect(SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2, 30, 30) }
def check(candidate): pass
40
def create_ground() -> None: """ Creates the scrolling ground element at the bottom of the screen. """
create_ground
return { 'x': 0, 'y': SCREEN_HEIGHT - GROUND_HEIGHT, 'width': SCREEN_WIDTH, 'height': GROUND_HEIGHT, 'rect': pygame.Rect(0, SCREEN_HEIGHT - GROUND_HEIGHT, SCREEN_WIDTH, GROUND_HEIGHT) }
def check(candidate): pass
41
def initialize_pipes() -> None: """ Sets up the initial pipe generation system. """
initialize_pipes
return []
def check(candidate): pass
42
def handle_events() -> None: """ Processes user input events including mouse clicks for flapping. The dependent functions are: flap_bird() -> None: Makes the bird jump upward when the player clicks. """
handle_events
global game_active for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # Left mouse button if game_active: flap_bird() ...
def check(candidate): pass
43
def flap_bird() -> None: """ Makes the bird jump upward when the player clicks. """
flap_bird
if game_active: bird['velocity'] = BIRD_JUMP
def check(candidate): pass
44
def update_game_state() -> None: """ Updates the positions and states of all game elements each frame. The dependent functions are: update_bird() -> None: Updates the bird's position based on gravity and velocity. update_pipes() -> None: Moves existing pipes leftward and generates ne...
update_game_state
if game_active: update_bird() update_pipes() update_ground() check_collisions() update_score()
def check(candidate): pass
45
def update_bird() -> None: """ Updates the bird's position based on gravity and velocity. """
update_bird
bird['velocity'] += GRAVITY bird['y'] += bird['velocity'] bird['rect'].y = bird['y']
def check(candidate): pass
46
def generate_pipe() -> None: """ Creates a new pair of pipes with a random gap height. """
generate_pipe
gap_y = random.randint(100, SCREEN_HEIGHT - GROUND_HEIGHT - 100 - PIPE_GAP) top_pipe = { 'x': SCREEN_WIDTH, 'y': 0, 'width': 50, 'height': gap_y, 'passed': False, 'rect': pygame.Rect(SCREEN_WIDTH, 0, 50, gap_y) } bottom_pipe = { 'x': SCREEN_WIDTH...
def check(candidate): pass
47
def update_pipes() -> None: """ Moves existing pipes leftward and generates new pipes as needed. The dependent functions are: generate_pipe() -> None: Creates a new pair of pipes with a random gap height. """
update_pipes
global last_pipe, pipes current_time = pygame.time.get_ticks() # Generate new pipes at regular intervals if current_time - last_pipe > PIPE_FREQUENCY: pipes.extend(generate_pipe()) last_pipe = current_time # Update existing pipes for pipe in pipes[:]: pipe['x'] -= PIPE...
def check(candidate): pass
48
def update_ground() -> None: """ Scrolls the ground element to create continuous movement. """
update_ground
ground['x'] = (ground['x'] - PIPE_SPEED) % ground['width']
def check(candidate): pass
49
def check_collisions() -> None: """ Detects if the bird has collided with pipes or the ground. The dependent functions are: check_pipe_collision() -> None: Determines if the bird has collided with any pipe. check_ground_collision() -> None: Determines if the bird has hit the ground. ...
check_collisions
global game_active if check_pipe_collision() or check_ground_collision(): game_active = False bird['alive'] = False
def check(candidate): pass
50
def check_pipe_collision() -> None: """ Determines if the bird has collided with any pipe. """
check_pipe_collision
for pipe in pipes: if bird['rect'].colliderect(pipe['rect']): return True return False
def check(candidate): pass
51
def check_ground_collision() -> None: """ Determines if the bird has hit the ground. """
check_ground_collision
return bird['rect'].colliderect(ground['rect']) or bird['y'] <= 0
def check(candidate): pass
52
def update_score() -> None: """ Increments the score when the bird successfully passes through pipes. """
update_score
global score for pipe in pipes: if pipe.get('passed', True) == False and pipe['x'] + pipe['width'] < bird['x']: pipe['passed'] = True score += 0.5 # Count as 0.5 because we have two pipes per gap
def check(candidate): pass
53
def render_game() -> None: """ Draws all game elements to the screen. The dependent functions are: draw_background() -> None: Renders the game background. draw_pipes() -> None: Renders all visible pipes on the screen. draw_ground() -> None: Renders the scrolling ground. ...
render_game
draw_background() draw_pipes() draw_ground() draw_bird() draw_score() if not game_active: show_game_over_screen()
def check(candidate): pass
54
def draw_background() -> None: """ Renders the game background. """
draw_background
screen.fill(SKY_BLUE)
def check(candidate): pass
55
def draw_pipes() -> None: """ Renders all visible pipes on the screen. """
draw_pipes
for pipe in pipes: pygame.draw.rect(screen, GREEN, pipe['rect'])
def check(candidate): pass
56
def draw_ground() -> None: """ Renders the scrolling ground. """
draw_ground
pygame.draw.rect(screen, (139, 69, 19), (ground['x'], ground['y'], ground['width'], ground['height'])) pygame.draw.rect(screen, (139, 69, 19), (ground['x'] - ground['width'], ground['y'], ground['width'], ground['height']))
def check(candidate): pass
57
def draw_bird() -> None: """ Renders the bird with appropriate animation frame based on its state. """
draw_bird
pygame.draw.ellipse(screen, YELLOW, bird['rect']) # Add eye eye_x = bird['x'] + bird['width'] * 3/4 eye_y = bird['y'] + bird['height'] * 1/3 pygame.draw.circle(screen, BLACK, (int(eye_x), int(eye_y)), 3)
def check(candidate): pass
58
def draw_score() -> None: """ Displays the current score on the screen. """
draw_score
score_text = font.render(f"Score: {int(score)}", True, WHITE) screen.blit(score_text, (10, 10))
def check(candidate): pass
59
def game_over() -> None: """ Handles the game over state when the bird collides with an obstacle. The dependent functions are: show_game_over_screen() -> None: Displays the game over message and restart option. """
game_over
show_game_over_screen()
def check(candidate): pass
60
def show_game_over_screen() -> None: """ Displays the game over message and restart option. """
show_game_over_screen
game_over_text = font.render("Game Over", True, WHITE) restart_text = font.render("Click to Restart", True, WHITE) screen.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 3)) screen.blit(restart_text, (SCREEN_WIDTH // 2 - restart_text.get_width() // 2, SCREEN_...
def check(candidate): pass
61
def restart_game() -> None: """ Resets all game elements to start a new game. The dependent functions are: create_bird() -> None: Creates the bird character with initial position and physics properties. initialize_pipes() -> None: Sets up the initial pipe generation system. reset...
restart_game
global bird, pipes bird = create_bird() pipes = initialize_pipes() reset_score()
def check(candidate): pass
62
def reset_score() -> None: """ Sets the score back to zero for a new game. """
reset_score
global score score = 0
def check(candidate): pass
63
def main_game_loop() -> None: """ The main loop that runs the game, handling timing and calling all update and render functions. The dependent functions are: handle_events() -> None: Processes user input events including mouse clicks for flapping. update_game_state() -> None: Updates...
main_game_loop
while True: handle_events() update_game_state() render_game() pygame.display.update() clock.tick(FPS)
def check(candidate): pass
64
def initialize_game() -> dict: """ Sets up the game environment, including the game board, tanks, obstacles, and initial game state. Returns: dict: Game state containing board, tanks, projectiles, and game settings The dependent functions are: create_game_board(width: int, height: int) -> li...
initialize_game
game_state = { 'board': create_game_board(GRID_WIDTH, GRID_HEIGHT), 'tanks': [], 'projectiles': [], 'obstacles': [], 'explosions': [], 'game_over': False, 'max_score': 3 } # Place tanks game_state['tanks'] = place_tanks(game_state) # Generate...
def check(candidate): pass
65
def create_game_board(width: int, height: int) -> list: """ Creates a grid-based game board with specified dimensions. Parameters: width (int): Width of the game board in grid cells height (int): Height of the game board in grid cells Returns: list: 2D grid representing the game ...
create_game_board
return [[0 for _ in range(width)] for _ in range(height)]
def check(candidate): pass
66
def place_tanks(game_state: dict) -> list: """ Places two tanks at initial positions on the game board. Parameters: game_state (dict): Current game state Returns: list: List containing two tank objects with initial positions, orientations, and health """
place_tanks
tanks = [ { 'id': 0, 'position': (1, GRID_HEIGHT // 2), 'orientation': RIGHT, 'health': 100, 'cooldown': 0, 'color': BLUE, 'score': 0 }, { 'id': 1, 'position': (GRID_WIDTH - 2, GRID_HE...
def check(candidate): pass
67
def generate_obstacles(game_state: dict, obstacle_count: int) -> list: """ Creates obstacles on the game board in strategic positions. Parameters: game_state (dict): Current game state obstacle_count (int): Number of obstacles to generate Returns: list: List of obstacle positions...
generate_obstacles
obstacles = [] board = game_state['board'] tanks = game_state['tanks'] # Create a list of all possible positions all_positions = [(x, y) for x in range(GRID_WIDTH) for y in range(GRID_HEIGHT)] # Remove tank positions and adjacent cells from possible positions for tank in tanks: tan...
def check(candidate): pass
68
def handle_input(game_state: dict, events: list) -> dict: """ Processes keyboard input from both players to control tanks. Parameters: game_state (dict): Current game state events (list): List of input events to process Returns: dict: Updated game state with player actions Th...
handle_input
for event in events: if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: # Player 1 controls (WASD + Space) if event.key == pygame.K_w: game_state = move_tank(game_state, 0, 1) elif event...
def check(candidate): pass
69
def move_tank(game_state: dict, tank_id: int, direction: int) -> dict: """ Moves a tank forward or backward based on player input. Parameters: game_state (dict): Current game state tank_id (int): ID of the tank to move direction (int): Direction of movement (1 for forward, -1 for bac...
move_tank
tank = game_state['tanks'][tank_id] x, y = tank['position'] orientation = tank['orientation'] # Calculate new position based on orientation and direction if orientation == UP: new_pos = (x, y - direction) elif orientation == RIGHT: new_pos = (x + direction, y) elif orientati...
def check(candidate): pass
70
def rotate_tank(game_state: dict, tank_id: int, direction: int) -> dict: """ Rotates a tank left or right based on player input. Parameters: game_state (dict): Current game state tank_id (int): ID of the tank to rotate direction (int): Direction of rotation (1 for right, -1 for left)...
rotate_tank
tank = game_state['tanks'][tank_id] # Update orientation (0-3) and wrap around tank['orientation'] = (tank['orientation'] + direction) % 4 return game_state
def check(candidate): pass
71
def fire_projectile(game_state: dict, tank_id: int) -> dict: """ Creates a projectile from a tank's position in its facing direction. Parameters: game_state (dict): Current game state tank_id (int): ID of the tank firing the projectile Returns: dict: Updated game state with new p...
fire_projectile
if not can_fire(game_state, tank_id): return game_state tank = game_state['tanks'][tank_id] x, y = tank['position'] orientation = tank['orientation'] # Set initial projectile position slightly ahead of the tank if orientation == UP: pos = (x, y - 1) elif orientation == RIGH...
def check(candidate): pass
72
def can_fire(game_state: dict, tank_id: int) -> bool: """ Checks if a tank can fire based on its cooldown timer. Parameters: game_state (dict): Current game state tank_id (int): ID of the tank to check Returns: bool: True if the tank can fire, False otherwise """
can_fire
return game_state['tanks'][tank_id]['cooldown'] <= 0
def check(candidate): pass
73
def check_collision(game_state: dict, position: tuple) -> bool: """ Checks if a tank's movement would result in a collision with obstacles or other tanks. Parameters: game_state (dict): Current game state position (tuple): Position to check (x, y) Returns: bool: True if collision...
check_collision
x, y = position # Check if position is out of bounds if x < 0 or x >= GRID_WIDTH or y < 0 or y >= GRID_HEIGHT: return True # Check collision with obstacles for obstacle in game_state['obstacles']: if obstacle['position'] == position: return True # Check collision w...
def check(candidate): pass
74
def update_game_state(game_state: dict, delta_time: float) -> dict: """ Updates the game state for each frame, including tank positions, projectiles, and collisions. Parameters: game_state (dict): Current game state delta_time (float): Time elapsed since last update in seconds Returns: ...
update_game_state
if game_state['game_over']: return game_state # Update projectiles game_state = update_projectiles(game_state, delta_time) # Check for collisions game_state = check_projectile_collisions(game_state) # Update cooldowns game_state = update_cooldowns(game_state, delta_time) retu...
def check(candidate): pass
75
def update_projectiles(game_state: dict, delta_time: float) -> dict: """ Updates the positions of all active projectiles on the game board. Parameters: game_state (dict): Current game state delta_time (float): Time elapsed since last update in seconds Returns: dict: Updated game ...
update_projectiles
updated_projectiles = [] for projectile in game_state['projectiles']: x, y = projectile['position'] orientation = projectile['orientation'] speed = projectile['speed'] * delta_time # Calculate new position based on orientation if orientation == UP: new_pos =...
def check(candidate): pass
76
def check_projectile_collisions(game_state: dict) -> dict: """ Detects collisions between projectiles and tanks or obstacles. Parameters: game_state (dict): Current game state Returns: dict: Updated game state with collision results The dependent functions are: apply_damage(game_...
check_projectile_collisions
updated_projectiles = [] for projectile in game_state['projectiles']: grid_pos = (int(projectile['position'][0]), int(projectile['position'][1])) collision = False # Check collision with tanks for tank in game_state['tanks']: if tank['position'] == grid_pos and tank...
def check(candidate): pass
77
def apply_damage(game_state: dict, tank_id: int, damage: int) -> dict: """ Applies damage to a tank when hit by a projectile. Parameters: game_state (dict): Current game state tank_id (int): ID of the tank taking damage damage (int): Amount of damage to apply Returns: dic...
apply_damage
tank = game_state['tanks'][tank_id] tank['health'] -= damage if tank['health'] <= 0: tank['health'] = 0 game_state = check_tank_destroyed(game_state, tank_id) return game_state
def check(candidate): pass
78
def check_tank_destroyed(game_state: dict, tank_id: int) -> dict: """ Checks if a tank's health has reached zero and handles tank destruction. Parameters: game_state (dict): Current game state tank_id (int): ID of the tank to check Returns: dict: Updated game state with destructi...
check_tank_destroyed
tank = game_state['tanks'][tank_id] if tank['health'] <= 0: # Award points to the other player other_player = 1 if tank_id == 0 else 0 game_state = update_score(game_state, other_player, 1) # Create explosion at tank position game_state = create_explosion(game_state, ta...
def check(candidate): pass
79
def create_explosion(game_state: dict, position: tuple, size: float) -> dict: """ Creates an explosion effect at a specified position. Parameters: game_state (dict): Current game state position (tuple): Position for the explosion (x, y) size (float): Size of the explosion Returns...
create_explosion
explosion = { 'position': position, 'size': size, 'time': 0.5, # Duration in seconds 'current_time': 0 } game_state['explosions'].append(explosion) return game_state
def check(candidate): pass
80
def update_cooldowns(game_state: dict, delta_time: float) -> dict: """ Updates cooldown timers for tank firing and other time-based mechanics. Parameters: game_state (dict): Current game state delta_time (float): Time elapsed since last update in seconds Returns: dict: Updated ga...
update_cooldowns
for tank in game_state['tanks']: if tank['cooldown'] > 0: tank['cooldown'] -= delta_time # Update explosion timers updated_explosions = [] for explosion in game_state['explosions']: explosion['current_time'] += delta_time if explosion['current_time'] < explosion['tim...
def check(candidate): pass
81
def update_score(game_state: dict, player_id: int, points: int) -> dict: """ Updates a player's score when they destroy an enemy tank. Parameters: game_state (dict): Current game state player_id (int): ID of the player who scored points (int): Number of points to add Returns: ...
update_score
game_state['tanks'][player_id]['score'] += points return game_state
def check(candidate): pass
82
def check_game_over(game_state: dict) -> bool: """ Checks if the game has ended based on tank health or other conditions. Parameters: game_state (dict): Current game state Returns: bool: True if game is over, False otherwise """
check_game_over
for tank in game_state['tanks']: if tank['health'] <= 0: return True # Check if max score reached for tank in game_state['tanks']: if tank['score'] >= game_state['max_score']: return True return False
def check(candidate): pass
83
def render_game(game_state: dict, screen: Surface) -> None: """ Renders the current game state to the screen. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Updates the display The dependent functions are: re...
render_game
render_board(game_state, screen) render_tanks(game_state, screen) render_projectiles(game_state, screen) render_explosions(game_state, screen) render_ui(game_state, screen) if game_state['game_over']: show_game_over(game_state, screen) pygame.display.flip()
def check(candidate): pass
84
def render_board(game_state: dict, screen: Surface) -> None: """ Renders the game board grid and obstacles. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Renders the board to the screen """
render_board
screen.fill(BLACK) # Draw grid for x in range(GRID_WIDTH): for y in range(GRID_HEIGHT): rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE) pygame.draw.rect(screen, GRAY, rect, 1) # Draw obstacles for obstacle in game_state['obstacles']: x...
def check(candidate): pass
85
def render_tanks(game_state: dict, screen: Surface) -> None: """ Renders the tanks on the game board. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Renders tanks to the screen """
render_tanks
for tank in game_state['tanks']: if tank['health'] <= 0: continue x, y = tank['position'] rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE) # Draw tank body pygame.draw.rect(screen, tank['color'], rect) # Draw tank cannon based on o...
def check(candidate): pass
86
def render_projectiles(game_state: dict, screen: Surface) -> None: """ Renders active projectiles on the game board. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Renders projectiles to the screen """
render_projectiles
for projectile in game_state['projectiles']: x, y = projectile['position'] center_x = int(x * GRID_SIZE + GRID_SIZE // 2) center_y = int(y * GRID_SIZE + GRID_SIZE // 2) pygame.draw.circle(screen, YELLOW, (center_x, center_y), GRID_SIZE // 4)
def check(candidate): pass
87
def render_explosions(game_state: dict, screen: Surface) -> None: """ Renders explosion animations on the game board. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Renders explosions to the screen """
render_explosions
for explosion in game_state['explosions']: x, y = explosion['position'] center_x = int(x * GRID_SIZE + GRID_SIZE // 2) center_y = int(y * GRID_SIZE + GRID_SIZE // 2) # Calculate explosion radius based on time progress = explosion['current_time'] / explosion['time'] r...
def check(candidate): pass
88
def render_ui(game_state: dict, screen: Surface) -> None: """ Renders user interface elements like health bars, scores, and game messages. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Renders UI elements to the scr...
render_ui
font = pygame.font.SysFont('Arial', 24) # Draw player 1 info tank1 = game_state['tanks'][0] score1_text = font.render(f"P1: {tank1['score']}", True, WHITE) screen.blit(score1_text, (20, 10)) # Draw player 1 health bar health_width = 100 * (tank1['health'] / 100) pygame.draw.rect(screen...
def check(candidate): pass
89
def show_game_over(game_state: dict, screen: Surface) -> None: """ Displays the game over screen with final scores and restart option. Parameters: game_state (dict): Current game state screen (Surface): Pygame surface to render on Returns: None: Displays game over screen """
show_game_over
if not game_state['game_over']: return # Draw semi-transparent overlay overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA) overlay.fill((0, 0, 0, 180)) screen.blit(overlay, (0, 0)) font_large = pygame.font.SysFont('Arial', 48) font_medium = pygame.font.SysFont(...
def check(candidate): pass
90
def restart_game() -> dict: """ Resets the game to its initial state for a new round. Returns: dict: Fresh game state for a new game The dependent functions are: initialize_game() -> dict: Sets up the game environment, including the game board, tanks, obstacles, and initial game stat...
restart_game
return initialize_game()
def check(candidate): pass
91
def main_game_loop() -> None: """ Main game loop that handles game state updates and rendering. Returns: None: Runs the game until exit The dependent functions are: initialize_game() -> dict: Sets up the game environment, including the game board, tanks, obstacles, and initial game s...
main_game_loop
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Tank Battle Game") # Initialize clock clock = pygame.time.Clock() # Initialize game state game_state = initialize_game() # Main game loop while True: # Calculate delta time delt...
def check(candidate): pass
92
def main() -> None: """ The main function that sets up the Streamlit application and orchestrates the workflow. The dependent functions are: upload_file() -> None: Handles the file upload functionality and validates that the uploaded file is in Excel or CSV format. display_data_overview() ->...
main
st.title("Excel Data Processor") st.write("Upload an Excel file to view and manipulate the data") # File upload uploaded_file = upload_file() if uploaded_file is not None: try: # Read the file df = read_file(uploaded_file) # Display data overview ...
def check(candidate): pass
93
def upload_file() -> None: """ Handles the file upload functionality and validates that the uploaded file is in Excel or CSV format. The dependent functions are: read_file() -> None: Reads the uploaded file into a pandas DataFrame based on the file extension. """
upload_file
uploaded_file = st.file_uploader("Choose an Excel or CSV file", type=["xlsx", "xls", "csv"]) return uploaded_file
def check(candidate): pass
94
def read_file() -> None: """ Reads the uploaded file into a pandas DataFrame based on the file extension. """
read_file
file_extension = uploaded_file.name.split(".")[-1] if file_extension in ["xlsx", "xls"]: df = pd.read_excel(uploaded_file) elif file_extension == "csv": df = pd.read_csv(uploaded_file) else: raise ValueError("Unsupported file format. Please upload an Excel or CSV file.") re...
def check(candidate): pass
95
def display_data_overview() -> None: """ Displays basic information about the DataFrame including shape, data types, and missing values. """
display_data_overview
st.subheader("Data Overview") st.write(f"Rows: {df.shape[0]}, Columns: {df.shape[1]}") st.subheader("Data Types") st.write(df.dtypes) st.subheader("Missing Values") missing_data = df.isnull().sum() st.write(missing_data[missing_data > 0] if missing_data.any() else "No missing values")
def check(candidate): pass
96
def handle_data_operations() -> None: """ Manages all data manipulation operations including column selection, filtering, and sorting. The dependent functions are: select_columns() -> None: Allows users to select specific columns from the DataFrame to display. filter_data() -> None: ...
handle_data_operations
st.subheader("Data Operations") # Select columns selected_df = select_columns(df) # Filter data filtered_df = filter_data(selected_df) # Sort data sorted_df = sort_data(filtered_df) return sorted_df
def check(candidate): pass
97
def select_columns() -> None: """ Allows users to select specific columns from the DataFrame to display. """
select_columns
st.subheader("Column Selection") all_columns = df.columns.tolist() selected_columns = st.multiselect("Select columns to display", all_columns, default=all_columns) if not selected_columns: st.warning("Please select at least one column.") return df return df[selected_columns]
def check(candidate): pass
98
def filter_data() -> None: """ Filters the DataFrame based on user-specified conditions for selected columns. """
filter_data
st.subheader("Data Filtering") if df.empty: return df filter_column = st.selectbox("Select a column to filter", df.columns.tolist(), key="filter_column") if filter_column: column_type = df[filter_column].dtype if pd.api.types.is_numeric_dtype(column_type): min_val...
def check(candidate): pass
99
def sort_data() -> None: """ Sorts the DataFrame based on user-selected columns and sort order. """
sort_data
st.subheader("Data Sorting") if df.empty: return df sort_column = st.selectbox("Select a column to sort by", df.columns.tolist(), key="sort_column") if sort_column: sort_order = st.radio("Sort order", ["Ascending", "Descending"]) ascending = sort_order == "Ascending" s...
def check(candidate): pass
100
def toggle_full_data() -> None: """ Toggles between displaying a sample of the data and the full dataset. """
toggle_full_data
st.subheader("Data Display") if df.empty: st.warning("No data to display.") return show_all = st.checkbox("Show all data") if show_all: st.write(df) else: rows_to_show = st.slider("Number of rows to display", 5, 100, 10) st.write(df.head(rows_to_show))
def check(candidate): pass
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
2