Skip to content

Instantly share code, notes, and snippets.

@bobmurder
Created October 31, 2012 06:35
Show Gist options
  • Save bobmurder/3985465 to your computer and use it in GitHub Desktop.
Save bobmurder/3985465 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from collections import defaultdict
from itertools import repeat
from pprint import pprint
from random import choice
def grid(height, width):
return [['0' for n in range(width)] for n in range(height)]
grid = grid(15, 15)
def place_bombs(grid, n_bombs):
height, width, left = len(grid), len(grid[0]), n_bombs
bombs = []
while left > 0:
x, y = choice(range(height)), choice(range(width))
if grid[x][y] == '0':
grid[x][y] = 'X'
bombs.append((x, y))
left -= 1
return grid, bombs
grid, bombs = place_bombs(grid, 20)
pprint(sorted(bombs))
for l in grid:
print ' '.join([c for c in l])
# spaces to check
#
# -1, -1 | 0, -1 | 1, -1
# -1, 0 | point | 1, 0
# -1, 1 | 0, 1 | 1, 1
# boundary conditions:
#---------------------
# if coord = (0, 0), (0, 14), (14, 0), (14, 14)
# only three checks are needed.
# each corner checks the 3 coords opposite itself in the chart above
# if point is upper left, check the spaces to the right, lower-right, and below
# those the the 3 spaces opposite the upper left corner (-1, -1) above.
def corners(height, width):
# hardcode this shit for now
height, width = map(lambda x: x - 1, [height, width])
return {
(0, 0): [(0, 1), (1, 0), (1, 1)], # top left
(width, 0): [(-1, 0), (-1, 1), (0, 1)], # top right
(0, height): [(0, -1), (1, -1), (1, 0)], # bottom left
(width, height): [(-1, 0), (-1, -1), (0, 1)] # bottom right
}
# if coord is in range:
# (1, 0) - (13, 0) or
# (0, 1) - (0, 13) or
# (14, 1), (14, 13) or
# (1, 14), (13, 14)
# only 5 checks are necessary
def edges(height, width):
return ([(n, 0) for n in range(1, width)] + # top
[(n, 14) for n in range(1, width)] + # bottom
[(0, n) for n in range(1, height)] + # left
[(14, n) for n in range(1, height)]) # right
# all other coords require all 8 checks.
# there is no need to make a data structure of the rest.
# to check surrounding spaces, do this:
# 1. check if the space is a bomb
# 2. if it is a bomb, return False
# 3. if it isn't a bomb, return True
def check_space(grid, coord):
# grid is a list of lists, coord is a tuple in the form (x, y)
# checking for a bomb instead of '0' allows us to change when we insert
# values into the grid. as of now, the grid is only populated with
# 'X' or '0' until all spaces are checked.
if grid[coord[0]][coord[1]] == 'X':
return False
return True
corners = corners(15, 15)
edges = edges(15, 15)
pprint(corners)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment