Advertisement
Kaloyankerr

02. Snake

Oct 13th, 2020
1,964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. def get_snake_position():
  2.     global matrix
  3.     for r in range(n):
  4.         if 'S' in matrix[r]:
  5.             for c in range(n):
  6.                 if matrix[r][c] == 'S':
  7.                     return [r, c]
  8.                     # get the index with the .index() method
  9.  
  10.  
  11. def get_burrows_indexes(field):
  12.     global n
  13.     res = []
  14.     for x in range(n):
  15.         if 'B' in field[x]:
  16.             res.append([x, field[x].index('B')])
  17.     return res
  18.  
  19.  
  20. def is_valid(row1, col1, row2, col2):
  21.     global n
  22.     return 0 <= (row1 + row2) < n and 0 <= (col1 + col2) < n
  23.  
  24.  
  25. moves = {
  26.     'up': [-1, 0],
  27.     'down': [1, 0],
  28.     'left': [0, -1],
  29.     'right': [0, 1]
  30. }
  31.  
  32. n = int(input())
  33. matrix = [[x for x in input()[:n]] for _ in range(n)]
  34. burrows = get_burrows_indexes(field=matrix)
  35. food_quantity = 0
  36.  
  37. while True:
  38.     current_row, current_col = get_snake_position()
  39.     current_move = input()
  40.     next_row, next_col = moves[current_move]
  41.  
  42.     if not is_valid(current_row, current_col, next_row, next_col):
  43.         matrix[current_row][current_col] = '.'
  44.         print('Game over!')
  45.         break
  46.  
  47.     matrix[current_row][current_col] = '.'
  48.     next_snake_position = matrix[current_row + next_row][current_col + next_col]
  49.  
  50.     if next_snake_position == '*':
  51.         current_row, current_col = current_row + next_row, current_col + next_col
  52.         food_quantity += 1
  53.         if food_quantity == 10:
  54.             print('You won! You fed the snake.')
  55.             matrix[current_row][current_col] = 'S'
  56.             break
  57.  
  58.     elif next_snake_position == 'B':
  59.         for burrow in burrows:
  60.             if [current_row + next_row, current_col + next_col] != burrow:
  61.                 matrix[current_row + next_row][current_col + next_col] = '.'
  62.                 current_row, current_col = burrow
  63.  
  64.     else:
  65.         current_row, current_col = current_row + next_row, current_col + next_col
  66.  
  67.     matrix[current_row][current_col] = 'S'
  68.  
  69. print(f'Food eaten: {food_quantity}')
  70. [print(''.join(x)) for x in matrix]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement