Created
December 21, 2016 23:44
-
-
Save TheZoq2/16bc099ce6070f1a9abb8bcb16da2c94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from copy import deepcopy | |
| import pdb | |
| EMPTY_CHAR = "." | |
| PLAYER_CHAR = "x" | |
| def change_piece_at(pos, board, new): | |
| board[pos[0]][pos[1]] = new | |
| def update_player_pos(game_state, new): | |
| new_state = deepcopy(game_state) | |
| change_piece_at(game_state.player_pos, new_state.grid, EMPTY_CHAR) | |
| change_piece_at(new, new_state.grid, PLAYER_CHAR) | |
| new_state.player_pos = new | |
| return new_state | |
| def add_to_player_pos(game_state, add): | |
| new_state = deepcopy(game_state) | |
| (old_x, old_y) = new_state.player_pos | |
| return update_player_pos(new_state, (old_x + add[0], old_y + add[1])) | |
| def draw_grid(grid): | |
| def draw_inner(row): | |
| if row: | |
| print(row[0], end="") | |
| draw_inner(row[1:]) | |
| else: | |
| print("") | |
| if grid: | |
| draw_inner(grid[0]) | |
| draw_grid(grid[1:]) | |
| def on_left(game_state): | |
| return add_to_player_pos(game_state, (0, -1)) | |
| def on_right(game_state): | |
| return add_to_player_pos(game_state, (0, 1)) | |
| def on_up(game_state): | |
| return add_to_player_pos(game_state, (-1, 0)) | |
| def on_down(game_state): | |
| return add_to_player_pos(game_state, (1, 0)) | |
| def on_quit(game_state): | |
| new_state = deepcopy(game_state) | |
| new_state.is_running = False | |
| return new_state | |
| input_map = { | |
| "left": on_left, | |
| "west": on_left, | |
| "right": on_right, | |
| "east": on_right, | |
| "up": on_up, | |
| "north": on_up, | |
| "down": on_down, | |
| "south": on_down, | |
| "quit": on_quit | |
| } | |
| def handle_input(game_state): | |
| command = input(">>") | |
| if command not in input_map: | |
| print("Unrecognised command: {}".format(command)) | |
| return game_state | |
| else: | |
| return input_map[command](game_state) | |
| class GameState: | |
| def __init__(self, size): | |
| self.size = size | |
| self.grid = [[EMPTY_CHAR for i in range(size[1])] for i in range(size[0])] | |
| self.player_pos = (0,0) | |
| self.is_running = True | |
| def main(): | |
| game_state = GameState((10, 10)) | |
| while(game_state.is_running == True): | |
| game_state = handle_input(game_state) | |
| draw_grid(game_state.grid) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment