我是Python的新手,我正在开发Connect Four游戏。我能够初始化电路板,自己动作,让计算机移动。但是,我知道必须有一种更好的“放置我的作品”的方式,而不是我拥有的大量IF语句。此外,我不确定如何接近实际检查游戏是否“赢得”或抽出的逻辑。
这是我的代码:
import random
board = [["." for x in range(7)] for x in range(6)]
symbol = ""
def boardLogic(pick, user):
if user == "user":
symbol = "0"
else:
symbol = "X"
if board[0][pick] != ".":
if board[1][pick] != ".":
if board[2][pick] != ".":
if board[3][pick] != ".":
if board[4][pick] != ".":
if board[5][pick] != ".":
if board[6][pick] != ".":
print("That column is full.")
else:
board[6][pick] = symbol
else:
board[5][pick] = symbol
else:
board[4][pick] = symbol
else:
board[3][pick] = symbol
else:
board[2][pick] = symbol
else:
board[1][pick] = symbol
else:
board[0][pick] = symbol
def printBoard():
for row in board:
for val in row:
print '{:4}'.format(val),
print
won = False
while not won:
printBoard()
#pick a column
#ADD FUNCTIONALITY TO DISALLOW A FULL COLUMN FROM BEING ENTERED
while True:
try:
yourPick = int(raw_input('Pick a column 0 - 6: '))
except ValueError: # just catch the exceptions you know!
print 'That\'s not a number!'
else:
if 0 <= yourPick < 6: # this is faster
break
else:
print 'Out of range. Try again'
print(yourPick)
#column logic
boardLogic(yourPick, "user")
#opponent randomly picks a column
theirPick = random.randint(0, 6)
print(theirPick)
#column logic
boardLogic(theirPick, "notUser")
#check win conditions
#won = True