我正在尝试用 Python 编写一个简单的黑白棋游戏。
在我的代码中有两个主要列表:
takered - 包含红色玩家占据的位置
takeblue - 包含蓝色玩家占据的位置
在玩家的每一次移动之后,我都会更新这些列表以包含每个玩家的更新位置
这是我的问题:
当我使用输入运行代码时:
R
02
23
我收到一条错误消息,指出在列表中找不到最后一个索引,因此无法删除它。
到目前为止,我尝试的是使用 for 循环中的缩进,因为其余代码对我来说似乎是正确的。
我的代码:
import numpy as np
import math
def isfull(board):
for i in range(0, 4):
for j in range(0, 4):
if board[i][j] == 'e':
return False
return True
def main():
board = np.empty([4, 4], dtype=str)
for t in range(0, 4):
for n in range(0, 4):
board[t, n] = 'e'
board[1, 1] = 'R'
board[1, 2] = 'B'
board[2, 1] = 'B'
board[2, 2] = 'R'
takenblue = [[1, 2], [2, 1]]
takenred = [[1, 1], [2, 2]]
toswitch1=[]
toswitch2=[]
print(board)
player = str(input('input player R or B: '))
otherplayer = 'e'
while isfull(board) == False:
if player == 'R':
otherplayer = 'B'
else:
otherplayer = 'R'
loc = list(input(player + 'loc '))
for i in range(0, 2):
loc[i] = int(loc[i], base=10)
if player == 'R':
if board[loc[0], loc[1]]=='e':
for j in takenred:
if (loc[0] == j[0] or loc[1] == j[1] or abs(loc[1] - j[1]) == abs(loc[0] - j[0]) or abs(
loc[1] - j[1]) == abs(j[0] - loc[0])):
if (board[math.floor((loc[0] + j[0]) // 2), math.floor((loc[1] + j[1]) // 2)] == otherplayer):
board[math.floor((loc[0] + j[0]) // 2), math.floor((loc[1] + j[1]) // 2)] = player
board[loc[0], loc[1]] = player
toswitch1 = [math.floor((loc[0] + j[0]) // 2), math.floor((loc[1] + j[1]) // 2)]
print(takenred)
print(toswitch1)
takenblue.remove(toswitch1)
takenred.append(toswitch1)
takenred.append(loc)
print('R: ', takenred)
print('B: ', takenblue)
if player == 'B':
if board[loc[0], loc[1]]=='e':
for t in takenblue:
if (loc[0] == t[0] or loc[1] == t[1] or abs(loc[1] - t[1]) == abs(loc[0] - t[0]) or abs(
loc[1] - t[1]) == abs(t[0] - loc[0])):
if(board[math.floor((loc[0] + t[0]) // 2), math.floor((loc[1] + t[1]) // 2)] == otherplayer):
board[math.floor((loc[0] + t[0]) // 2), math.floor((loc[1] + t[1]) // 2)] = player
board[loc[0], loc[1]] = player
toswitch2 = [math.floor((loc[0] + t[0]) // 2), math.floor((loc[1] + t[1]) // 2)]
print(toswitch2)
takenred.remove(toswitch2)
takenblue.append(toswitch2)
takenblue.append(loc)
print('B: ', takenblue)
print('R: ', takenred)
if player == 'B':
player = 'R'
otherplayer = 'B'
else:
player = 'B'
otherplayer = 'R'
print(board)
if __name__ == '__main__':
main()
欢迎任何帮助!
终端:
[['e' 'e' 'e' 'e']
['e' 'R' 'B' 'e']
['e' 'B' 'R' 'e']
['e' 'e' 'e' 'e']]
input player R or B: R
Rloc 02
[1, 2]
R: [[1, 1], [2, 2], [1, 2], [0, 2]]
B: [[2, 1]]
[['e' 'e' 'R' 'e']
['e' 'R' 'R' 'e']
['e' 'B' 'R' 'e']
['e' 'e' 'e' 'e']]
Bloc 23
[2, 2]
Traceback (most recent call last):
File "x:/xxx/xxx/xxx/xxx.py", line 78, in <module>
main()
File "x:/x/xxx/xxx/xxx.py", line 63, in main
takenred.remove(toswitch2)
ValueError: list.remove(x): x not in list
Process finished with exit code 1