Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- MOVES = {
- 'up': (-1, 0),
- 'right': (0, +1),
- 'down': (+1, 0),
- 'left': (0, -1),
- }
- def is_valid(n):
- return 0 <= n < size
- def check_position(r, c):
- row = r
- col = c
- if not is_valid(row):
- if row < 0:
- row = size -1
- else:
- row = 0
- if not is_valid(col):
- if col < 0:
- col = size -1
- else:
- col = 0
- return row, col
- def find_snake():
- global matrix
- for x in range(size):
- for y in range(size):
- if matrix[x][y] == 's':
- return x, y
- def next_coordinates(r, c, cc):
- next_r = r + MOVES[cc][0]
- next_c = c + MOVES[cc][1]
- return next_r, next_c
- def move(p: tuple, m: list, c: str):
- global enemy_hit, snake_length
- m[p[0]][p[1]] = '*'
- next_row, next_col = next_coordinates(p[0], p[1], c)
- next_position = check_position(next_row, next_col)
- cell = m[next_position[0]][next_position[1]]
- if cell == 'e':
- enemy_hit = True
- return p, m
- elif cell == 'f':
- snake_length += 1
- p = (next_position[0], next_position[1])
- m[p[0]][p[1]] = '*'
- p = (next_position[0], next_position[1])
- return p, m
- def check_food():
- food = 0
- global matrix, all_food
- for x in range(size):
- for y in range(size):
- if matrix[x][y] == 'f':
- food +=1
- return food
- def output(f: int):
- global all_food
- if f > 0:
- all_food = False
- else:
- all_food = True
- if enemy_hit:
- return 'You lose! Killed by an enemy!'
- elif all_food:
- return f'You win! Final snake length is {snake_length}'
- return f'You lose! There is still {f} food to be eaten.'
- size = int(input())
- commands = input().split(', ')
- matrix = [input().split() for _ in range(size)]
- snake_length = 1
- all_food = False
- enemy_hit = False
- snake = find_snake()
- for command in commands:
- snake, matrix = move(snake, matrix, command)
- if enemy_hit:
- break
- food_left = check_food()
- print(output(food_left))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement