如何清除董事会

时间:2015-10-08 10:05:17

标签: python

我遇到的问题是如何让我的游戏停止“重新打印”棋盘游戏而不是在控制台的每一轮/转弯中反复显示棋盘?我希望它改变第一块板子中的“X”,而不是用“X”重新打印板。

以下是代码:

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

print ship_row
print ship_col

for turn in range(4):
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        break
    else:
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
            print "Oops, that's not even in the ocean."
        elif(board[guess_row][guess_col] == "X"):
            print "You guessed that one already."
        else:
            print "You missed my battleship!"
            board[guess_row][guess_col] = "X"
        print "Turn", turn + 1
        print_board(board)

print "Game Over"

1 个答案:

答案 0 :(得分:4)

如果你想简单一点,你可以用这一行清除屏幕:

print(chr(27) + "[2J")

然后迅速重新粉刷董事会。

对于更高级的控制台管理,您可以使用curses模块。它不是很容易使用,但它会让你做很多花哨的东西。它实际上是C curses库的精简绑定,因此如果您搜索C语言库,可能会发现更多文档。

如果您想要图形,标准库是pygame。它是流行的SDL库的一个不那么薄的绑定,但你会发现很多pygame例子。