ultimate/cli.py

125 lines
3.1 KiB
Python
Raw Normal View History

2022-07-09 22:27:42 -05:00
#!/usr/bin/env python
from board2 import Board
2022-07-11 19:27:49 -05:00
from board2 import BoardTools
2022-07-09 22:27:42 -05:00
from pos import TwoDPos
from pos import TwoDUtils
2022-07-11 19:27:49 -05:00
from node import Node
class StateError(BaseException):
pass
2022-07-09 22:27:42 -05:00
piecemaps = {
0: '.',
1: 'x',
2: 'o',
}
mappings = TwoDUtils.reverse
2022-07-11 19:27:49 -05:00
def tree_of_node(node):
parent = node
print("considering board with moveset " + str(parent.inner.moves))
possible = parent.inner.possible()
if len(possible) != 0:
print("permuting!")
for i in possible:
copy = parent.inner.copy()
copy.append(i)
childnode = Node()
childnode.inner = copy
parent.children.append(childnode)
for i in parent.children:
tree_of_node(i)
else:
print("calculated score")
rawscore = BoardTools.winning(None, parent.inner.metaboard())
if rawscore == Board.cross:
score = -1
elif rawscore == Board.nought:
score = 1
elif rawscore == Board.tie:
score = 0
else:
score = None
raise StateError("aaaa")
print("score" + str(score))
2022-07-09 22:27:42 -05:00
def render(board):
print("123 456 789")
moves = board.possible()
moves = [i.glob() for i in moves]
for i in range(9):
buf = []
for j in range(9):
ri = mappings[i]
string = ''.join([ri, str(j + 1)])
pos = TwoDPos(TwoDPos.g, string)
item = board.get(*pos.local())
if string in moves:
buf.append('?')
else:
buf.append(piecemaps[item])
if j in [2, 5]:
buf.append(" | ")
if j == 8:
buf.append(" " + ri)
print(''.join(buf))
if i in [2, 5]:
print("----+-----+----")
print("to play: " + str(board.turn))
2022-07-11 19:27:49 -05:00
def help_text():
2022-07-09 22:27:42 -05:00
print("m - make a move")
print("p - see coordinates of legal moves")
print("t - see whose turn it is")
print("r - render the board to the screen")
print("q - quit program")
print("h - show help (this list)")
def move(board, move):
move = TwoDPos(TwoDPos.g, move)
print(move)
board.append(move)
def possibilities(board):
print(board.possible())
def turn(board):
print("to play: " + str(board.turn))
def main():
b = Board()
print("type h for help")
while True:
2022-07-11 19:27:49 -05:00
# try:
2022-07-09 22:27:42 -05:00
cmd = input("> ")
spl = cmd.split(' ')
if spl[0] == "m":
move(b, spl[1])
elif spl[0] == "p":
possibilities(b)
elif spl[0] == "t":
turn(b)
elif spl[0] == "r":
render(b)
elif spl[0] == "h":
2022-07-11 19:27:49 -05:00
help_text()
elif spl[0] == "z":
# create node from current board
node = Node()
node.inner = b
tree_of_node(node)
2022-07-09 22:27:42 -05:00
elif spl[0] == "q":
break;
2022-07-11 19:27:49 -05:00
# except:
# print("error occured")
2022-07-09 22:27:42 -05:00
return
if __name__ == "__main__":
main()