我使用以下代码制作了一个网格:
board = []
x = choice_size
y = x
for row in range(0,x):
board.append(["()"]*y)
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
我需要为用户提供输入输入的选项(例如"Left 10 Up 2"
),然后将它们移动到电路板上的相应位置。
我已经尝试搞乱添加他们的数字到变量然后得到列表board
中的x和y位置,但我似乎无法让它工作。
尝试通过添加或减去数字来改变x / y值,具体取决于玩家想要移动的方向。
这是如何移动玩家的示例
但它在重绘电路板之前使用Linux特殊符号来清除终端/控制台。
import time
# --- constants --- (UPPER_CASE names)
SIZE_X = 10
SIZE_Y = 5
SYMBOL_EMPTY = '( )'
SYMBOL_PLAYER = '(@)'
#SYMBOL_DANGER = '(!)'
# --- functions --- (lower_case names)
def print_board(board):
print('\33c') # clear terminal on Linux
for row in board:
print("".join(row))
def move_player(new_x, new_y):
global player_x
global player_y
# remove in old place
board[player_y][player_x] = SYMBOL_EMPTY
# put in new place
player_x = new_x
player_y = new_y
board[player_y][player_x] = SYMBOL_PLAYER
# --- main --- (lower_case names)
# creat board
board = [ ]
for row in range(SIZE_Y):
board.append([SYMBOL_EMPTY] * SIZE_X)
# display empty board
print_board(board)
time.sleep(0.5)
# set player position and symbol
player_x = player_y = 0
board[player_y][player_x] = SYMBOL_PLAYER
# display board with player
print_board(board)
time.sleep(0.5)
# move player
# move left
for new_x in range(SIZE_X):
move_player(new_x, player_y)
# redraw
print_board(board)
time.sleep(0.5)
# move down
for new_y in range(SIZE_Y):
move_player(player_x, new_y)
# redraw
print_board(board)
time.sleep(0.5)
真正的程序可能更复杂。
在控制台中可能存在清除屏幕重绘板和获取键/鼠事件以使其真实交互的问题。也许看看urwid或ncurses
模块。