|
| 1 | +""" |
| 2 | +@Author: Aseem Jain |
| 3 | +@Linkedin: https://www.linkedin.com/in/premaseem/ |
| 4 | +@Github: https://github.com/premaseem/pythonLab/tree/master/challenge |
| 5 | +
|
| 6 | +We are designing a 2D game and we have a game map that we represent by an integer matrix. |
| 7 | +For now, each cell can be a wall (denoted by -1) or a blank space (0). |
| 8 | +
|
| 9 | +# The player can move 1 space at a time up, down, left, or right. |
| 10 | +The player can't go through walls or land on a wall, or go through the edges of the board. |
| 11 | +
|
| 12 | +# Write a function that, given a board and a player starting position (represented as a row-column pair), |
| 13 | +returns all of the possible next positions for the player. |
| 14 | +
|
| 15 | +# n: width of the input board |
| 16 | +# m: height of the input board |
| 17 | +
|
| 18 | +# Sample inputs (board, starting_position) and outputs (in any order): |
| 19 | +
|
| 20 | +# findLegalMoves(board, (1, 1)) => |
| 21 | +# (0, 1), (1, 0) |
| 22 | +
|
| 23 | +# findLegalMoves(board, (5, 3)) => |
| 24 | +# (5, 2), (5, 4), (4, 3), (6, 3) |
| 25 | +
|
| 26 | +# findLegalMoves(board, (5, 1)) => |
| 27 | +# (6, 1), (4, 1), (5, 0), (5, 2) |
| 28 | +
|
| 29 | +# findLegalMoves(board, (6, 0)) => |
| 30 | +# (5, 0), (6, 1) |
| 31 | +
|
| 32 | +# findLegalMoves(board, (6, 4)) => |
| 33 | +# (5, 4), (6, 3) |
| 34 | +
|
| 35 | +# findLegalMoves(board, (0, 0)) => |
| 36 | +# (0, 1), (1, 0) |
| 37 | +
|
| 38 | +# findLegalMoves(board, (2, 2)) => |
| 39 | +# [empty] |
| 40 | +
|
| 41 | +""" |
| 42 | + |
| 43 | +board = [ |
| 44 | + [0, 0, 0, -1, -1], |
| 45 | + [0, 0, -1, 0, 0], |
| 46 | + [0, -1, 0, -1, 0], |
| 47 | + [0, 0, -1, 0, 0], |
| 48 | + [0, 0, 0, 0, 0], |
| 49 | + [0, 0, 0, 0, 0], |
| 50 | + [0, 0, 0, 0, 0], |
| 51 | +] |
| 52 | + |
| 53 | + |
| 54 | +def findLegalMoves(board, t): |
| 55 | + x, y = t |
| 56 | + p1 = x + 1, y |
| 57 | + p2 = x - 1, y |
| 58 | + p3 = x, y + 1 |
| 59 | + p4 = x, y - 1 |
| 60 | + |
| 61 | + pp = [p1, p2, p3, p4] |
| 62 | + |
| 63 | + for x, y in pp: |
| 64 | + if x >= len(board) or y >= len(board[0]) or x < 0 or y < 0 or -1 == board[x][y]: |
| 65 | + pp.remove((x, y)) |
| 66 | + |
| 67 | + return pp |
| 68 | + |
| 69 | + |
| 70 | +print(findLegalMoves(board, (6, 0))) |
| 71 | + |
| 72 | +test_data = [ |
| 73 | + ((1, 1), [(0, 1), (1, 0)]), |
| 74 | + ((5, 3), [(5, 2), (5, 4), (4, 3), (6, 3)]), |
| 75 | + ((5, 1), [(6, 1), (4, 1), (5, 0), (5, 2)]), |
| 76 | + ((6, 0), [(5, 0), (6, 1)]), |
| 77 | + ((6, 4), [(5, 4), (6, 3)]), |
| 78 | + ((0, 0), [(0, 1), (1, 0)]), |
| 79 | + ((2, 2), []) |
| 80 | +] |
| 81 | + |
| 82 | +for given, expected in test_data: |
| 83 | + print(f" Testing with given {given} and expected = {expected}") |
| 84 | + actual = findLegalMoves(board, given) |
| 85 | + print(f"actual value: {actual}") |
| 86 | + assert actual.sort() == expected.sort() |
0 commit comments