zoukankan      html  css  js  c++  java
  • python生成迷宫

    # -*- coding: utf-8 -*-
    """
    Created on Sat Mar  8 23:52:39 2021
    
    @author: mengxin
    """
    
    import random
    import numpy as np
    
    row = 15
    cul = 15
    if row % 2 == 0:
        row = row + 1
    if cul % 2 == 0:
        cul = cul + 1
    def creator(row, cul):
      a = np.ones((row + 2, cul + 2), dtype = int)
      b = np.zeros(a.shape, dtype = bool)
      return a, b
    
    t_map, t_b = creator(row, cul)
    
    while(True):
      a = (random.randint(0, row + 1), random.randint(0, cul + 1))
      if a[0] % 2 == 1 and a[1] % 2 == 1:
        break
    
    allst = []
    allst.append(a)
    while(allst):
      b = allst.pop(random.randint(0, len(allst) - 1))
      t_map[b[0]][b[1]] = 0
      arnd = []
      if b[0] > 1 and b[0] < row:
        if t_map[b[0] - 2][b[1]] == 0:
          arnd.append([b[0] - 2, b[1]])
        else:
          allst.append((b[0] - 2, b[1]))
        if t_map[b[0] + 2][b[1]] == 0:
          arnd.append([b[0] + 2, b[1]])
        else:
          allst.append((b[0] + 2, b[1]))
      elif b[0] == 1:
        if t_map[b[0] + 2][b[1]] == 0:
          arnd.append([b[0] + 2, b[1]])
        else:
          allst.append((b[0] + 2, b[1]))
      elif b[0] == row:
        if t_map[b[0] - 2][b[1]] == 0:
          arnd.append([b[0] - 2, b[1]])
        else:
          allst.append((b[0] - 2, b[1]))
      if b[1] > 1 and b[1] < cul:
        if t_map[b[0]][b[1] - 2] == 0:
          arnd.append([b[0], b[1] - 2])
        else:
          allst.append((b[0], b[1] - 2))
        if t_map[b[0]][b[1] + 2] == 0:
          arnd.append([b[0], b[1] + 2])
        else:
          allst.append((b[0], b[1] + 2))
      elif b[1] == 1:
        if t_map[b[0]][b[1] + 2] == 0:
          arnd.append([b[0], b[1] + 2])
        else:
          allst.append((b[0], b[1] + 2))
      elif b[1] == cul:
        if t_map[b[0]][b[1] - 2] == 0:
          arnd.append([b[0], b[1] - 2])
        else:
          allst.append((b[0], b[1] - 2))
      allst = list(set(allst))
      if arnd:
        c = arnd.pop(random.randint(0, len(arnd) - 1))
        if b[0] == c[0]:
            c[1] = (b[1] + c[1]) // 2
        elif b[1] == c[1]:
            c[0] = (b[0] + c[0]) // 2
        t_map[c[0]][c[1]] = 0
    
    for i in range(len(t_map)):
        s = ''
        for j in range(len(t_map[i])):
            if t_map[i][j] == 0:
                s += '0'
            else:
                s += '1'
        print(s)

    其中0为路径,1为墙体。

  • 相关阅读:
    视图结构 wxml 列表渲染 for
    表存在之设置默认值
    Oracle之根据约束名查找表
    java中String.indexOf()用法
    Idea之快捷键
    List<Map<String,Object>>之按照某个字段排序
    Oracle之mergeInto
    Oracle之根据字段查找表
    Mybatis之一级/二级缓存
    VueJs之前后端数据交互(使用Vue-resource实现)
  • 原文地址:https://www.cnblogs.com/mengxinteriri/p/14509061.html
Copyright © 2011-2022 走看看