simeonshopov

Book Worm 2

Apr 30th, 2020
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. #!usr/local/bin/python3.8
  2. # -*- coding: utf-8 -*import
  3.  
  4.  
  5. def find_player(m: list):
  6.     """
  7.    Find the initial position of the player.
  8.    :param m:
  9.    :return: x: int, y: int
  10.    """
  11.     for x in range(matrix_size):
  12.         for y in range(len(m[x])):
  13.             if m[x][y] == 'P':
  14.                 return x, y
  15.  
  16.  
  17. def is_valid(i: int):
  18.     return 0 <= i < matrix_size
  19.  
  20.  
  21. def up(x: int, y: int):
  22.     return x - 1, y
  23.  
  24.  
  25. def down(x: int, y: int):
  26.     return x + 1, y
  27.  
  28.  
  29. def left(x: int, y: int):
  30.     return x, y - 1
  31.  
  32.  
  33. def right(x: int, y: int):
  34.     return x, y + 1
  35.  
  36.  
  37. def manage(x: str):
  38.     global matrix, player_row, player_col, text, MOVES
  39.     new_row, new_col = MOVES[x](player_row, player_col)
  40.     if not is_valid(new_row) or not is_valid(new_col):
  41.         if text:
  42.             text = text[:-1]
  43.     else:
  44.         cell = matrix[new_row][new_col]
  45.         if cell != '-':
  46.             text += matrix[new_row][new_col]
  47.             matrix[new_row][new_col] = 'P'
  48.             matrix[player_row][player_col] = '-'
  49.             player_row, player_col = new_row, new_col
  50.         else:
  51.             matrix[new_row][new_col] = 'P'
  52.             matrix[player_row][player_col] = '-'
  53.             player_row, player_col = new_row, new_col
  54.  
  55.  
  56. MOVES = {
  57.     'up': up,
  58.     'down': down,
  59.     'left': left,
  60.     'right': right,
  61. }
  62.  
  63. text = input()
  64. matrix_size = int(input())
  65. matrix = [list(input()) for _ in range(matrix_size)]
  66. player_row, player_col = find_player(matrix)
  67.  
  68. while True:
  69.     move = input()
  70.     if move == 'end':
  71.         break
  72.     manage(move)
  73.  
  74. if text:
  75.     print(text)
  76. [print(''.join(x)) for x in matrix]
Advertisement
Add Comment
Please, Sign In to add comment