from typing import Type, Literal from module import WIDTH, HEIGHT, JUMP_FORCE from module.block import AirBlock, Block # 玩家类 class Player: def __init__(self, world: list[list[Block]]): self.x = 100 self.y = 100 self.velocity = 0 self.on_ground = False self.selected_block = AirBlock self.world = world def move(self, dx, dy): world_position = {'x': int(self.x) // 20, 'y': int(self.y) // 20} # TODO:Need to judgment x and y in order not to raise Index Out Of Range Error top_block = self.world[world_position['x']][world_position['y'] - 1] button_block = self.world[world_position['x']][world_position['y'] + 1] left_block = self.world[world_position['x'] - 1][world_position['y']] right_block = self.world[world_position['x'] + 1][world_position['y']] if dx < 0 and left_block.collision: new_x = left_block.get_screen_x() + 30 elif dx > 0 and right_block.collision: new_x = right_block.get_screen_x() - 10 else: new_x = self.x + dx if dy < 0 and top_block.collision: new_y = top_block.get_screen_y() + 30 elif dy > 0 and button_block.collision: new_y = button_block.get_screen_y() - 10 else: new_y = self.y + dy if 0 <= new_x < WIDTH and 0 <= new_y < HEIGHT: self.x = new_x self.y = new_y def jump(self): if self.on_ground: self.velocity = JUMP_FORCE self.on_ground = False def select_block(self, block: Type[Block]): self.selected_block = block def put_block(self, x: int, y: int, action: Literal['create', 'delete'] = 'create'): if action == 'create': self.world[x][y] = self.selected_block(x, y) elif action == 'delete': self.world[x][y] = AirBlock(x, y) else: pass