This repository has been archived by the owner on Jan 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grid.py
64 lines (55 loc) · 1.84 KB
/
grid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw
import random
import math
OBSTACLE = 0
OPEN = 1
class Grid:
def __init__(self, width, height, obstacles=0):
if not 0 <= obstacles < 1:
raise ValueError('Chance of obstacles should be 0 <= P < 1')
self.width = width
self.height = height
self.grid = {}
for x in range(self.width):
for y in range(self.height):
if random.random() < obstacles:
self.grid[x, y] = OBSTACLE
else:
self.grid[x, y] = OPEN
def neighbours(self, x, y):
if self.grid[x, y] == OBSTACLE:
return []
ret = []
for h in range(-1, 2):
for v in range(-1, 2):
if h == 0 and v == 0:
continue # skip center
try:
if h != 0 and v != 0 and self.grid[x+h, y] == OBSTACLE \
and self.grid[x, y+v] == OBSTACLE:
continue
if self.grid[x+h, y+v] == OPEN:
ret.append((x+h, y+v))
except KeyError:
pass
return ret
def __str__(self):
ret = '+' + '-' * self.width + '+\n'
for y in range(self.height):
ret += '|'
for x in range(self.width):
if self.grid[x, y] == OPEN:
ret += ' '
elif self.grid[x, y] == OBSTACLE:
ret += 'X'
ret += '|\n'
ret += '+' + '-' * self.width + '+'
return ret
@property
def open_cells(self):
return [k for k in self.grid if self.grid[k] == OPEN]
def dist(s, d):
return max(abs(s[0] - d[0]), abs(s[1] - d[1]))
def cost(s, d):
return math.sqrt(abs(s[0] - d[0]) + abs(s[1] - d[1]))