Advertisement
simeonshopov

Snake

Jun 23rd, 2020
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. MOVES = {
  2.     'up': (-1, 0),
  3.     'right': (0, +1),
  4.     'down': (+1, 0),
  5.     'left': (0, -1),
  6. }
  7.  
  8.  
  9. def is_valid(n):
  10.     return 0 <= n < size
  11.  
  12.  
  13. def check_position(r, c):
  14.     row = r
  15.     col = c
  16.     if not is_valid(row):
  17.         if row < 0:
  18.             row = size -1
  19.         else:
  20.             row = 0
  21.     if not is_valid(col):
  22.         if col < 0:
  23.             col = size -1
  24.         else:
  25.             col = 0
  26.     return row, col
  27.  
  28.  
  29. def find_snake():
  30.     global matrix
  31.  
  32.     for x in range(size):
  33.         for y in range(size):
  34.             if matrix[x][y] == 's':
  35.                 return x, y
  36.  
  37.  
  38. def next_coordinates(r, c, cc):
  39.     next_r = r + MOVES[cc][0]
  40.     next_c = c + MOVES[cc][1]
  41.     return next_r, next_c
  42.  
  43.  
  44. def move(p: tuple, m: list, c: str):
  45.     global enemy_hit, snake_length
  46.  
  47.     m[p[0]][p[1]] = '*'
  48.  
  49.     next_row, next_col = next_coordinates(p[0], p[1], c)
  50.     next_position = check_position(next_row, next_col)
  51.     cell = m[next_position[0]][next_position[1]]
  52.  
  53.     if cell == 'e':
  54.         enemy_hit = True
  55.         return p, m
  56.     elif cell == 'f':
  57.         snake_length += 1
  58.         p = (next_position[0], next_position[1])
  59.         m[p[0]][p[1]] = '*'
  60.  
  61.     p = (next_position[0], next_position[1])
  62.  
  63.     return p, m
  64.  
  65.  
  66. def check_food():
  67.     food = 0
  68.     global matrix, all_food
  69.     for x in range(size):
  70.         for y in range(size):
  71.             if matrix[x][y] == 'f':
  72.                 food +=1
  73.     return food
  74.  
  75.  
  76. def output(f: int):
  77.     global all_food
  78.  
  79.     if f > 0:
  80.         all_food = False
  81.     else:
  82.         all_food = True
  83.  
  84.     if enemy_hit:
  85.         return 'You lose! Killed by an enemy!'
  86.     elif all_food:
  87.         return f'You win! Final snake length is {snake_length}'
  88.     return f'You lose! There is still {f} food to be eaten.'
  89.  
  90.  
  91.  
  92. size = int(input())
  93. commands = input().split(', ')
  94. matrix = [input().split() for _ in range(size)]
  95. snake_length = 1
  96. all_food = False
  97. enemy_hit = False
  98.  
  99. snake = find_snake()
  100.  
  101. for command in commands:
  102.     snake, matrix = move(snake, matrix, command)
  103.     if enemy_hit:
  104.         break
  105.  
  106. food_left = check_food()
  107. print(output(food_left))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement