def snakeGame(gameBoard, commands): def setGB(x, y, c): gameBoard[x][y] = c def valid(x, y): return x in range(len(gameBoard)) and y in range(len(gameBoard[0])) moves = {'<': lambda x, y: (x, y-1), '>': lambda x, y: (x, y+1), '^': lambda x, y: (x-1, y), 'v': lambda x, y: (x+1, y)} rotations = {'<': {'L': 'v', 'R': '^'}, '>': {'L': '^', 'R': 'v'}, '^': {'L': '<', 'R': '>'}, 'v': {'L': '>', 'R': '<'}} snake = {} for (i, row) in enumerate(gameBoard): for (j, c) in enumerate(row): if c == '.': continue if c in {'<', '>', '^', 'v'}: headPos = (i, j) headDir = c snake[(i, j)] = [] if (i-1, j) in snake.keys(): snake[(i, j)].append((i-1, j)) snake[(i-1, j)].append((i, j)) if (i, j-1) in snake.keys(): snake[(i, j)].append((i, j-1)) snake[(i, j-1)].append((i, j)) tailPos = next(filter(lambda x: len(snake[x]) == 1 and x != headPos, snake.keys())) if len(snake) > 1 else headPos for cmd in commands: if cmd == 'F': newHeadPos = moves[headDir](*headPos) if valid(*newHeadPos) and (not newHeadPos in snake.keys()): snake[newHeadPos] = [] setGB(*newHeadPos, headDir) if len(snake) == 1: setGB(*headPos, '.') del snake[headPos] else: setGB(*tailPos, '.') newTailPos = snake[tailPos][0] snake[newTailPos].remove(tailPos) del snake[tailPos] tailPos = newTailPos setGB(*headPos, '*') snake[headPos].append(newHeadPos) snake[newHeadPos].append(headPos) headPos = newHeadPos else: for pos in snake.keys(): setGB(*pos, 'X') break else: headDir = rotations[headDir][cmd] print('%s', gameBoard) return gameBoard gameBoard([['.', '.', '.', '.'], ['.', '*', '>', '.'], ['.', '.', '.', '.']], 'F')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question