因此,我将根据以下内容生成一个随机棋盘。
def getBoard(size)
randomStart = []
for i in range(0. size)
column = [i, random.randrange(0, size)]
randomStart.append(column)
return randomStart
然后,例如,如果我得到以下木板。[[0,3],[1,1],[2,4],[3,0],[4,3]]
然后我尝试将板子打印成类似这样的样子。
- - - X -
- X - - -
- - - - X
X - - - -
- - - X -
我试图做的方式是有一个字符串“ line”并逐行打印,如果列等于随机列位置,则打印X。 由于某种原因,我看不出该怎么做。任何帮助将不胜感激。
答案 0 :(得分:2)
仅逐行打印,检查每个点是否在您的点列表中,都应用X标记:
size = 5
points = [[0, 3],[1, 1],[2, 4],[3, 0],[4, 3]]
for j in range(size):
row = ""
for i in range(size):
if [i,j] in points:
row += "X "
else:
row += "- "
print(row)
输出
- - - X -
- X - - -
- - - - -
X - - - X
- - X - -
答案 1 :(得分:2)
我稍微整理了一下代码。如果我对您的理解正确,解决方案将是:
import random
def get_board(size):
random_start = []
for i in range(size):
column = [i, random.randrange(size)]
random_start.append(column)
return random_start
def print_board(size):
occupied = get_board(size)
for i in range(size):
for j in range(size):
if [i, j] in occupied:
print("X ", end='') # end='' to prevent newlines
else:
print("- ", end='')
print("") # newline after a row
答案 2 :(得分:1)
这是一种numpy
方法,可将您的电路板输出为矩阵:
import numpy as np
np.random.seed(0)
size = 5
board = np.zeros((size, size)).astype(str)
board[board=='0.0'] = '-'
points = [[i, np.random.randint(size)] for i in range(size)]
mapping = {tuple(i): 'X' for i in points}
for i, j in mapping.keys():
board[i,j] = mapping[(i,j)]
返回:
[['-' '-' '-' '-' 'X']
['X' '-' '-' '-' '-']
['-' '-' '-' 'X' '-']
['-' '-' '-' 'X' '-']
['-' '-' '-' 'X' '-']]
答案 3 :(得分:0)
board = getBoard(5)
for line in board:
print (' '.join('X' if i == line[1] else '-' for i in range(len(board))))
这将创建一个-
和X
字符的列表,然后使用join
将其连接成单个字符串,用于每一行。