有没有办法打印一个字符串并防止它在随机字符串生成器中重新打印?

时间:2019-02-07 21:42:27

标签: python

我已经制作了一个程序,可以为像游戏这样的地牢爬行者打印随机的字符行,我想知道是否可以让它一次只打印一次@符号。

我尝试使它检查以前打印的字符串列表,并确保如果已经打印过,它将不会再次打印,但这似乎不起作用,对此我有点陌生。有什么建议吗?

import random
import time
randomnumber = random.randint(6,16)
block = []
printed = []
health = 10
blocks = "\x1b[1;37;48m#"
x_axis = 1
y_axis = 1
randumplace = random.randint(0, len(block))
multiplier = random.randrange(6,35)
def build(blocks):
  for i in range (multiplier):
    block.append(blocks)
    i = random.randrange(1,75)
    if i == 4:
      blocks = "\x1b[1;31;48mM"
    elif i == 15:
      blocks = "\x1b[1;36;48m~"
    elif i == 25:
      blocks = "\x1b[1;36;48m~"
    elif i == 22:
      blocks = "\x1b[1;33;48m$"
    elif i == 1:
      blocks = "\x1b[1;37;48m#"
    elif i == 10 and "@" not in printed:
      blocks = "@"
    else:
      blocks = "\x1b[1;37;48m."
fip = build(blocks)
counter  = 1
print("# "+"# # # # # #" + " #" * (multiplier - 6))
while counter != randomnumber:
  printed.append(block)
  del block[:]
  build(blocks)
  print (*block)
  counter += 1
print ("" + "# " * (multiplier +1))

它应该打印出5到15行的字符串,例如“#... M。$.....。 但是它会打印多个@符号,例如 “#..... @ M .. @ ........” 我还想确保其他行也不会打印@符号,这就是“已打印”列表的原因。

3 个答案:

答案 0 :(得分:0)

一种更简单的方法是在内存中创建一个矩阵,例如

maze = [[' '] * random_width for i in range(random_height)]

然后您可以根据需要填充迷宫,只有完成后才打印。

答案 1 :(得分:0)

首先,将您选择的块折叠到一个简单的查找表中:

rand_limit = 75
block = ["\x1b[1;37;48m."] * rand_limit
block[01] = "\x1b[1;37;48m#"
block[04] = "\x1b[1;31;48mM"
block[15] = "\x1b[1;36;48m~"
block[22] = "\x1b[1;33;48m$"
block[25] = "\x1b[1;36;48m~"

现在,您可以将整个迷宫作为一个嵌套列表来理解,用块符号代替随机数:

maze_rows = random.randrange(6, 35)
maze_cols = random.randrange(5, 16)

maze = [ [block[random.randrange(1, rand_limit)]
             for col in range(maze_cols)]
                 for row in range(maze_rows) ]

最后,为您的唯一符号选择一个随机的行和列:

maze[random.randrange(maze_rows][random.randrange(maze_cols]] = '@'

如果您不想覆盖现有的符号,请循环播放直到碰到空白。

答案 2 :(得分:0)

我刚刚将printed.append()函数移到了构建函数中。

尝试一下:

import random
import time
randomnumber = random.randint(6,16)
block = []
printed = []
health = 10
blocks = "\x1b[1;37;48m#"
x_axis = 1
y_axis = 1
randumplace = random.randint(0, len(block))
multiplier = random.randrange(6,35)
def build(blocks):
  for i in range (multiplier):
    block.append(blocks)
    i = random.randrange(1,75)
    if i == 4:
      blocks = "\x1b[1;31;48mM"
    elif i == 15:
      blocks = "\x1b[1;36;48m~"
    elif i == 25:
      blocks = "\x1b[1;36;48m~"
    elif i == 22:
      blocks = "\x1b[1;33;48m$"
    elif i == 1:
      blocks = "\x1b[1;37;48m#"
    elif i == 10 and "@" not in printed:
      blocks = "@"
      printed.append("@")
    else:
      blocks = "\x1b[1;37;48m."
fip = build(blocks)
counter  = 1
print("# "+"# # # # # #" + " #" * (multiplier - 6))
while counter != randomnumber:
  del block[:]
  build(blocks)
  print (*block)
  counter += 1
print ("" + "# " * (multiplier +1))