maxdepth = -1 def parselines(ix, lines, firstdepth): from string import strip global maxdepth retval = [] firstdepth = 0 nextcursorpos = ix while ix < len(lines): # try: depth = 0 while lines[ix][depth] == ' ': depth = depth + 1 depth = depth / 2 maxdepth = max(depth, maxdepth) addlist = retval for i in range(depth): addlist = addlist[-1] data = strip(lines[ix]) if len(data) != 0: addlist.append([data]) # except: # print "error in opening library at line", ix, "data:", lines[ix] # raise "Error in opening library" ix = ix + 1 return retval #[["e2-e4", ["b7-b6", ["d2-d4"]], ["g7-g6", ["d2-d4"]]], ["d2-d4"]] library = None def readlibrary(): global library; if library == None: file = open("openinglibrary.txt") lines = file.readlines() cursor = 0 library = parselines(cursor, lines, 0) return library openinglib = readlibrary() def allnextmoves(lib, movehistory): from string import split global maxdepth if (len(movehistory) > maxdepth): return [] retval = [] moves = [] if (len(movehistory)): for olib in lib: librepr = split(olib[0], ":")[0] if librepr == repr(movehistory[0]): return allnextmoves(olib[1:], movehistory[1:]) else: for olib in lib: retval.append(olib[0]) return retval return [] def allnextmoveslib(movehistory): return allnextmoves(openinglib, movehistory) def nextmove(movehistory): from string import split lmoves = allnextmoves(openinglib, movehistory) if len(lmoves) == 0: return None from random import random while 1: ix = int(len(lmoves) * (random() ** 3.14)) ix = min(ix, len(lmoves)) if lmoves[ix][-1] != "?": # bad opening lines are marked with ? return split(lmoves[ix], ":") def gameName(moves): from string import split gamename = "" if len(moves): gamename = repr(moves[0]) + " opening" if len(moves) >= 2: gamename = (repr(moves[0]) + " " + repr(moves[1]) + " opening") for i in range(0, len(moves)): movesUpto = moves[:(i)] anm = allnextmoveslib(movesUpto) for move in anm: nmove = split(move, ":") if nmove[0] == repr(moves[i]): if len(nmove) > 1: gamename = nmove[1] return gamename def _test3(): import nchess6 m = nchess6.Move(12,12+16) a = gameName([m]) print "FINAL: ", a def _test2(): import nchess6 m = nchess6.Move(12,12+16) m1 = nchess6.Move(6 * 8 + 4, 4 * 8 + 4) a = gameName([m, m1]) print "FINAL: ", a def _test(): lib = readlibrary() print lib moves = allnextmoves(lib, ["e2-e4"]) print "++++++++++++++++" print moves print "================" a = nextmove([]) print "next move", a print "----------------" b = nextmove(["e2-e4"]) print "e2-e4 jatkuu: ", b return print nextmove(["e2-e4", "b7-b6"]) print nextmove([]) print nextmove([]) print nextmove([]) _test2()