import random class AreaGenerator(): def __init__(self, row=8, col=9): self.points = list() self.row = row self.col = col def get_no_conflict_cells(self, x, y): xl = [point[0] for point in self.points if point[1] == y] yl = [point[0] for point in self.points if point[0] == x] x_start = 1 x_end = self.col - 1 for i in xl: if i > x_start and x > i: x_start = i if i < x_end and x < i: x_end = i y_start = 1 y_end = self.row - 1 for i in yl: if i > y_start and i < y: y_start = i if i < y_end and i > y: y_end = i rows = [[xx, y] for xx in range(x_start, x_end) if xx != x] cols = [[x, yy] for yy in range(y_start, y_end) if yy != y] cols.extend(rows) return cols def get_next_point(self, x, y): p = self.get_no_conflict_cells(x, y) if p != None: return random.choice(p) def generate(self, points=3, retry=10): a = [] c = points while c > 0 and retry > 0: x = random.randint(1, self.col - 1) y = random.randint(1, self.row - 1) a.append([x, y]) for i in range(1, points): p = self.get_next_point(x, y) if None == p: c = points a = [] retry = -1 break else: (x, y) = p a.append(p) c = -1 return a def generate_coins(self, coins=5): way_points = self.generate(points=coins) result = [] x1, y1, x2, y2 = 0, 0, 0, 0 x1, y1 = way_points.pop(0) result.append([x1, y1]) for point in way_points: x2, y2 = point if x1 == x2: if y1 < y2: result.append([x2, y2 + 1]) else: result.append([x2, y2 - 1]) elif y1 == y2: if x1 < x2: result.append([x2 + 1, y2]) else: result.append([x2 - 1, y2]) x1, y1 = x2, y2 return result a = AreaGenerator() p = a.generate_coins(4) ga = [[0 for x in range(8)] for y in range(9)] for i in p: ga[i[0]][i[1]] = 1 for b in ga: print(b)
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