2014-02-09 65 views
0
s = [0,2,6,4,7,1,5,3] 


def row_top(): 
    print("|--|--|--|--|--|--|--|--|") 

def cell_left(): 
    print("| ", end = "") 

def solution(s): 
    for i in range(8): 
     row(s[i]) 

def cell_data(isQ): 
    if isQ: 
     print("X", end = "") 
     return() 
    else: 
     print(" ", end = "") 


def row_data(c): 
    for i in range(9): 
     cell_left() 
     cell_data(i == c) 

def row(c): 
    row_top() 
    row_data(c) 
    print("\n") 


solution(s) 

我的输出每两行有一个空格,当不应该出现时,我不确定它在哪里创建多余的行。为8皇后拼图创建一个棋盘

输出是假设是这样的:

|--|--|--|--|--|--|--|--| 
| | | | | | X| | | 
|--|--|--|--|--|--|--|--| 
| | | X| | | | | | 
|--|--|--|--|--|--|--|--| 
| | | | | X| | | | 
|--|--|--|--|--|--|--|--| 
| | | | | | | | X| 
|--|--|--|--|--|--|--|--| 
| X| | | | | | | | 
|--|--|--|--|--|--|--|--| 
| | | | X| | | | | 
|--|--|--|--|--|--|--|--| 
| | X| | | | | | | 
|--|--|--|--|--|--|--|--| 
| | | | | | | X| | 
|--|--|--|--|--|--|--|--| 

我知道这个棋盘不是很广场但这只是目前初稿。

+0

http://stackoverflow.com/questions/21654443/ascii-art-in-python-not-printing-in-one-line?一样吗? –

+0

阅读那一个的评论... – pakiboii

+1

好的,但请不要单独提问每一个小的变化。最好只问一次。 –

回答

0

你还在打印额外的换行符:

def row(c): 
    row_top() 
    row_data(c) 
    print("\n") 

取出明确“” \ n'`性格:

def row(c): 
    row_top() 
    row_data(c) 
    print() 

或者更好的是,按照我以前的答案更紧密地与打印一关闭|酒吧:

def row(c): 
    row_top() 
    row_data(c) 
    print('|') 
1

这里是一个替代实现:

def make_row(rowdata, col, empty, full): 
    items = [col] * (2*len(rowdata) + 1) 
    items[1::2] = (full if d else empty for d in rowdata) 
    return ''.join(items) 

def make_board(queens, col="|", row="---", empty=" ", full=" X "): 
    size = len(queens) 
    bar = make_row(queens, col, row, row) 
    board = [bar] * (2*size + 1) 
    board[1::2] = (make_row([i==q for i in range(size)], col, empty, full) for q in queens) 
    return '\n'.join(board) 

queens = [0,2,6,4,7,1,5,3] 
print(make_board(queens)) 

这导致

|---|---|---|---|---|---|---|---| 
| X | | | | | | | | 
|---|---|---|---|---|---|---|---| 
| | | X | | | | | | 
|---|---|---|---|---|---|---|---| 
| | | | | | | X | | 
|---|---|---|---|---|---|---|---| 
| | | | | X | | | | 
|---|---|---|---|---|---|---|---| 
| | | | | | | | X | 
|---|---|---|---|---|---|---|---| 
| | X | | | | | | | 
|---|---|---|---|---|---|---|---| 
| | | | | | X | | | 
|---|---|---|---|---|---|---|---| 
| | | | X | | | | | 
|---|---|---|---|---|---|---|---| 

现在是很容易通过改变传递到行中的字符串来改变板的宽度,空的,满;我为每个添加了一个额外的字符,导致(有点)方格板。