Advertisement
GalinaKG

02.Snake

Sep 22nd, 2022 (edited)
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. def find_snake_position(matrix):
  2.     for row in range(len(matrix)):
  3.         for col in range(len(matrix)):
  4.             if matrix[row][col] == 'S':
  5.                 return row, col
  6.  
  7.  
  8. def is_valid(matrix, next_row, next_col):
  9.     if 0 <= next_row < len(matrix) and 0 <= next_col < len(matrix):
  10.         return True
  11.  
  12.    
  13. size = int(input())
  14. matrix = [list(input()) for _ in range(size)]
  15.  
  16. direction = input()
  17.  
  18. counter_food = 0
  19.  
  20. while direction:
  21.     row_snake, col_snake = find_snake_position(matrix)
  22.     possible_directions = {
  23.         'up': [row_snake - 1, col_snake],
  24.         'down': [row_snake + 1, col_snake],
  25.         'left': [row_snake, col_snake - 1],
  26.         'right': [row_snake, col_snake + 1]
  27.     }
  28.  
  29.     next_row, next_col = possible_directions[direction]
  30.     if not is_valid(matrix, next_row, next_col):
  31.         matrix[row_snake][col_snake] = '.'
  32.         print('Game over!')
  33.         break
  34.  
  35.     if matrix[next_row][next_col] == 'B' and is_valid(matrix, next_row, next_col):
  36.         matrix[next_row][next_col] = 'S'
  37.         matrix[row_snake][col_snake] = '.'
  38.         for row in range(size):
  39.             for col in range(size):
  40.                 if matrix[row][col] == 'B':
  41.                     matrix[row][col] = 'S'
  42.                     matrix[next_row][next_col] = '.'
  43.                     break
  44.         direction = input()
  45.         continue
  46.  
  47.     elif matrix[next_row][next_col] == '*' and is_valid(matrix, next_row, next_col):
  48.         counter_food += 1
  49.  
  50.     matrix[next_row][next_col] = 'S'
  51.     matrix[row_snake][col_snake] = '.'
  52.     if counter_food == 10:
  53.         print("You won! You fed the snake.")
  54.         break
  55.  
  56.     direction = input()
  57.  
  58. print(f'Food eaten: {counter_food}')
  59. for row in matrix:
  60.     print(''.join(row))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement