-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictac.py
1295 lines (1146 loc) · 36.8 KB
/
tictac.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
* * * * * * * * * * * *
* Paul Schwendenman *
* 09/20/11 *
* If you have to ask: *
* You aren't allowed *
* * * * * * * * * * * *
'''
# * * * * * * *
# * Imported *
# * * * * * * *
from UserList import UserList
from handleError import handleError
from ProgressBar import ProgressProcess
from Timer import Timer
# * * * * * * * * * * *
# * Global Variables *
# * * * * * * * * * * *
DEBUG = 0 # Choose: 0 or 1
NUMBERLASTGAMES = 15 # Choose: 1, 2, 3...
AIADJUST = [{'win': 1, 'lose': -1, 'draw': 0, 'last': 2},
{'win': 1, 'lose': -1, 'draw': 0, 'last': 2}]
USEDSPACE = -5 # This is used to adjust values for used spaces in grids
RECURSIONCOUNT = 50 # Number of times to try and not pick a used move
# * * * * * * * *
# * Grid Class *
# * * * * * * * *
class Grid(UserList):
'''
The Basic 3 by 3 grid
'''
def __init__(self, initlist=None):
# From the userlist
self.data = []
if initlist is not None:
if type(initlist) == type(self.data):
self.data[:] = initlist
elif isinstance(initlist, UserList):
self.data[:] = initlist.data[:]
elif isinstance(initlist, int):
self.data = [int(item) for item in ('0' * 9 + str(initlist)) \
[-9:]]
elif isinstance(initlist, str):
if ':' in initlist:
self.fromString(initlist)
else:
self.data = [int(item) for item in list(initlist)]
else:
self.data = list(initlist)
else:
self.data = [0] * 9
if ':' in self:
raise TypeError
def __str__(self):
'''
Prints the list as a continuous word.
'''
a = ''.join([str(a) for a in self.data])
return a
def toString(self):
'''
Prints the list joined with ":"
'''
def pick(a, b):
if a > b:
return b
else:
return a
return ':'.join([(" " + str(a))[pick(-4, -len(str(a))):] \
for a in self.data])
def __sub__(self, other):
'''
Used to find the differences between two grids item by item
'''
assert len(self.data) == len(self.data)
return Grid([self.data[index] - other[index] for \
index in range(0, len(self.data))])
def fromString(self, a):
'''
Inverse of toString()
'''
self.data = [int(b) for b in a.split(':')]
def returnXO(self):
'''
Returns a list with the 0, 1, and 2s replaced.
'''
b = {0: " ", 1: "X", 2: "O"}
return [b[a] for a in self.data]
def getEmptySpaces(self):
'''
Return the index of all positions with value '0'
'''
return [a for a, b in enumerate(self.data) if b == 0]
def getUsedSpaces(self):
'''
Returns a list of (spaces) list indices that are not valued empty.
'''
return [a for a, b in enumerate(self.data) if b != 0]
def __hash__(self):
'''
Okay to hash despite being mutable, hash reveals state not variable
'''
#return int(self.__str__())
return Translate.Hash(self)
# * * * * * * * * *
# * Player Class *
# * * * * * * * * *
class Player():
'''
The base player class for a game.
'''
def __init__(self, index):
self.index = index
def getMove(self, *args):
'''
This function should take a variable number
of inputs and return a single number.
Typically takes two inputs:
- the current grid
- an error raised flag
Output:
- should be in [0...8] (3x3 grid)
'''
pass
def handleGameOver(self, *args):
'''
The method should handle all end game
activities for the player.
Typical Input:
- winner
- startingplayer
- gamegrids
- index, aidata <-- local
'''
pass
class Human(Player):
'''
Player designed for human input.
'''
def getMove(self, grid, error):
'''
Get the move.
'''
try:
printXO(grid)
if error != None:
print "Invalid Move: ", error + 1
input = raw_input("Move? ")[0]
if input == "h" or input == "H":
self.printHelp()
input = raw_input("Move? ")[0]
else:
return int(input) - 1
except (ValueError, IndexError, KeyError, EOFError, KeyboardInterrupt):
raise UserError("User Quit")
def handleGameOver(self, winner, gamegrids):
'''
Finalize the game.
'''
printXO(gamegrids[-1][0])
assert winner in [-1, 1, 2]
if winner == -1:
print "You tied!"
elif (winner == self.index):
print "You won! computer lost"
else:
print "You lost, computer won"
@staticmethod
def printHelp():
'''
Helpful grid for seeing desired output
Move to player.
'''
print
print " 1 | 2 | 3 "
print "---+---+---"
print " 4 | 5 | 6 "
print "---+---+---"
print " 7 | 8 | 9 "
class HumanNumber(Human):
'''
Use the numberpad.
'''
def getMove(self, *args):
'''
Returns the user move from number pad.
'''
a = {7: 0, 8: 1, 9: 2, 4: 3, 5: 4, 6: 5, 1: 6, 2: 7, 3: \
8}[Human.getMove(self, *args) + 1] - 1
print "Move:", a
return a
@staticmethod
def printHelp():
'''
Helpful grid for seeing desired output
Move to player.
'''
print
print " 7 | 8 | 9 "
print "---+---+---"
print " 4 | 5 | 6 "
print "---+---+---"
print " 1 | 2 | 3 "
class Comp(Player):
'''
Base that all computer players have.
'''
def __init__(self, index, **settings):
self.index = index
if 'filename' in settings:
self.filename = settings['filename']
else:
self.filename = 'data'
if 'record' in settings and settings['record'] == 1:
self.record = 1
self.load()
else:
self.record = 0
self.aidata = {}
def setAIdata(self, aidata):
'''
Set the memory of the ai
'''
self.aidata = aidata
def getMove(self, *args):
'''
Get the move should be over-ridden
'''
pass
def handleGameOver(self, *args):
'''
Handle any per game finalization.
'''
pass
def loadPickle(self, filename=None):
'''
Loads the unpickled data into from file
into the aidata
'''
from cPickle import load
try:
a = open(filename)
self.aidata = load(a)
a.close()
except IOError:
print "File doesn't exist?"
self.aidata = {}
else:
print "aidata has %i items" % (len(self.aidata))
def load(self):
'''
Open previously saved data.
Overload this function to toggle how data is saved
'''
self.loadPickle(self.filename)
def dumpPickle(self):
'''
Dumps the currently saved aidata into a file with pickle.
'''
from cPickle import dump
b = open(self.filename, "w")
dump(self.aidata, b)
print "aidata has %i items" % (len(self.aidata))
b.close()
def dump(self):
'''
Save the current data
Overload this function to toggle how data is saved.
'''
self.record = 0
self.dumpPickle()
def __del__(self):
'''
Save data before deleting
'''
if self.record:
self.dump()
class CompPick(Comp):
'''
Pick one... no thought.
'''
def getMove(self, grid, c):
return pickOne(grid.getEmptySpaces())
class CompTwo(Comp):
'''
Plays 'perfect' should finish wins and
should block moves.
'''
def getMove(self, grid, c):
'''
Return the move.
'''
one = ([item[1] for item in filter(lambda a: a[0] == 1, \
mapGrid(pickPlay, grid))])
two = ([item[1] for item in filter(lambda a: a[0] == 2, \
mapGrid(pickPlay, grid))])
grid = grid.getEmptySpaces()
if self.index == 2:
if two:
grid = two
elif one:
grid = one
elif self.index == 1:
if two:
grid = two
elif one:
grid = one
return pickOne(grid)
def handleGameOver(self, *args):
'''
Doesn't Need to learn anything
'''
pass
class CompLearning(Comp):
def getMove(self, grid, error):
'''
Make Move
'''
# Make getMove handle errors
DEBUGFUNC = 0
if grid.count(0) == len(grid):
return pickOne([pickOne([0, 2, 6, 8]), pickOne([1, 3, 5, 7]), 4])
b = Translate.GridMax(grid)
if DEBUG or DEBUGFUNC:
printXO(grid)
printXO(b[0])
if error != None:
f = [0, 1, 2, 3, 4, 5, 6, 7, 8, ]
e = Translate.GridReverse(f, b[1])[error]
if DEBUG or DEBUGFUNC:
print "Invalid Computer Move:"
print "\t error:", error, "\t e:", e, "\t b[1]:", b[1]
print "\t self.aidata[b[0]]:", self.aidata[b[0]].toString(),
self.aidata[b[0]][e] += USEDSPACE
if DEBUG or DEBUGFUNC:
print "\nAfter:"
print "\t self.aidata[b[0]]:", self.aidata[b[0]].toString()
d = Translate.GetMove(grid, self.aidata)
if error == d and d != None and error != None:
raise ValueError("error = d")
if d == None:
# Should be Intializing 'new' states
#if DEBUG or DEBUGFUNC:
# print "AI\n\t self.aidata:", self.aidata,
self.aidata[b[0]] = Grid()
if DEBUG or DEBUGFUNC:
print "\n\t empty: ", self.aidata[b[0]]
d = Grid()
#d = pickOne(grid.getEmptySpaces())
return pickOne(d)
#return getEmptySpaces(a)[0]
def handleGameOver(self, a, b):
'''
Process move.
'''
adjustAI(a, b[: -1][2 - self.index:: 2], self.index, self.aidata)
def load(self):
'''
Open saved data.
'''
self.aidata = {}
try:
file = open(self.filename)
lines = file.readlines()
for line in lines:
line = line[:-1].split("\t")
grid = Grid()
value = Grid()
grid.fromString(line[0])
value.fromString(line[1])
self.aidata[grid] = value
file.close()
except IOError:
print "File doesn't exist?"
self.aidata = {}
except:
handleError
try:
file.close()
self.loadPickle()
except:
pass
print "aidata has %i items" % (len(self.aidata))
def dump(self):
'''
Save opened data.
'''
self.record = 0
file = open(self.filename, "w")
grids = sorted(self.aidata.keys())
for grid in grids:
file.write(grid.toString() + "\t" + \
self.aidata[grid].toString() + "\n")
print "aidata has %i items" % (len(self.aidata))
file.close()
class CompTree(Comp):
def getMove(self, grid, error):
'''
Make Move.
'''
DEBUGFUNC = 1
if error != None:
print "Error:", error, grid
assert error == None
gridmax, trans = Translate.GridMax(grid)
#gridmax = grid
print gridmax, self.hash(gridmax), grid, self.hash(grid)
print self.hash(gridmax) in self.aidata, len(self.aidata)
if self.hash(gridmax) in self.aidata:
if DEBUGFUNC:
print "Tree"
print "=" * 4
move = self.followTree(gridmax)
if DEBUGFUNC:
print "Moves:", move
move = move[0]
else:
if DEBUGFUNC:
print "Pick"
move = gridmax.getEmptySpaces()[0]
#move = pickOne(gridmax.getEmptySpaces())
if DEBUGFUNC:
print "Move:", move
#if move not in grid.getEmptySpaces():
if DEBUGFUNC:
print "Translation Checking:"
print "=" * 21
#print "\tDisabled"
move2 = Translate.GridReverse(range(0, 9), trans)[move]
print "trans index:", trans
print gridmax, Grid(range(0, 9)), gridmax.getEmptySpaces(), move
print grid, Translate.GridReverse(range(0, 9), trans), \
grid.getEmptySpaces(), move2
print "Move checking:"
print "=" * 14
print gridmax
if DEBUGFUNC and 1:
griiids = sorted(self.aidata.keys())[:10]
for griiid in griiids:
print griiid == gridmax
print "\t", griiid, type(griiid)#, self.aidata[griiid][:4]
print "-" * 45
return Translate.GridReverse(range(0, 9), trans).index(move)
#return move
@staticmethod
def hash(grid):
'''
Hash should return a valid key for aidata.
The "perfect tree" is using grids but
the AIdata one uses hash()?
'''
#return grid
return hash(grid)
@staticmethod
def followResult(item, len=0):
if isinstance(item, tuple):
return CompTree.followResult(item[1], len+1)
else:
return (len, item)
@staticmethod
def followResultLength(item):
if isinstance(item, tuple):
return 1 + CompTree.followResultLength(item[1])
else:
return 0
def followTree(self, grid, **settings):
'''
Process Move.
'''
DEBUGFUNC = 1
# print Translate.GridMax(grid)[0], grid, self.aidata, "\n"
if self.hash(grid) in self.aidata and isinstance(self.aidata[self.hash(grid)], int):
if len(grid.getEmptySpaces()) == 1:
return (grid.getEmptySpaces()[0], self.aidata[self.hash(grid)])
else:
return (None, self.aidata[self.hash(grid)])
elif len(self.aidata[self.hash(grid)]) > 0:
recordedmoves = set([item[0] for item in self.aidata[self.hash(grid)]])
results = []
for each in self.aidata[self.hash(grid)]:
maxgrid, trans = Translate.GridMax(grid)
if self.index not in (each - maxgrid):
print each, grid, maxgrid, each - maxgrid
results.append((Translate.GridReverse(each - maxgrid, trans).index(self.index), \
self.followTree(each),))
if DEBUGFUNC:
print "Empty:", set(grid.getEmptySpaces()), "Recorded:", recordedmoves, "Results:", results,
for each in set(grid.getEmptySpaces()) - recordedmoves:
results.append((each, 0))
moves = [s for s in filter(lambda a: self.followResult(a[1]) == self.index, results)]
if not moves: # No Wins
if DEBUGFUNC:
print "No wins,",
moves = [s for s in filter(lambda a: self.followResult(a[1]) == -1, results)]
if not moves: # No ties
if DEBUGFUNC:
print "No ties,",
moves = [s for s in filter(lambda a: self.followResult(a[1]) == 0, results)]
if not moves: # No non-losses / unknown
if DEBUGFUNC:
print "No non-losses,",
moves = [s for s in filter(lambda a: self.followResult(a[1]) not in \
[-1, 0, self.index], results)]
assert moves == results
if DEBUGFUNC:
print
return pickOne(moves)
else:
raise Exception
if DEBUGFUNC and 0:
if 'tabs' not in settings:
settings['tabs'] = 0
print '\t' * settings['tabs'], "Catch Error"
print '\t' * settings['tabs'], self.aidata[self.hash(grid)][0], grid, \
(self.aidata[self.hash(grid)][0] - grid), (self.index)
print '\t' * settings['tabs'], [str(key) + ": " + \
str(self.aidata[key]) for key in self.aidata.keys()]
print self.followTree(self.aidata[self.hash(grid)][0], \
tabs=(settings['tabs'] + 1))
return ((self.aidata[self.hash(grid)][0] - grid).index(self.index), \
self.followTree(self.aidata[self.hash(grid)][0]),)
def handleGameOver(self, winner, grids):
'''
Process data.
'''
DEBUGFUNC = 0
grids = grids[self.index - 1:: 2]
if DEBUGFUNC:
print "\nHandle Game Over"
print "-" * 16
printGameGrids(grids)
print [(grids[i][0] - grids[i - 1][0]).index(self.index) \
if self.index in (grids[i][0] - grids[i - 1][0]) \
else (grids[i][0] - grids[i - 1][0]) \
for i in range(1, len(grids))]
printGameGrids([(grids[i][0] - grids[i - 1][0],) \
for i in range(1, len(grids))])
maxgrids = [Translate.GridMax(grid[0]) for grid in grids]
if DEBUGFUNC:
printGameGrids(maxgrids)
print [(maxgrids[i][0] - maxgrids[i - 1][0]).index(self.index) \
if self.index in (maxgrids[i][0] - maxgrids[i - 1][0]) \
else (maxgrids[i][0] - maxgrids[i - 1][0]) \
for i in range(1, len(maxgrids))]
print [(maxgrids[i][0] - maxgrids[i - 1][0]) \
for i in range(1, len(maxgrids))]
try:
for i in range(1, len(maxgrids)):
printGameGrids(Translate.GuessDifference(maxgrids[i - 1][0], maxgrids[i][0]),)
except:
handleError()
printGrids([maxgrids[i][0] - maxgrids[i - 1][0] \
for i in range(1, len(maxgrids))])
grids.reverse()
maxgrids.reverse()
while len(grids) > 1:
#grid = Translate.GridMax(grids.pop()[0])[0]
grid = (grids.pop()[0])
maxgrid = maxgrids.pop()
if self.hash(grid) in self.aidata:
#self.aidata[grid].append(Translate.GridMax(grids[-1][0])[0])
self.aidata[self.hash(grid)].append(Translate.Grid(grids[-1][0], maxgrid[1]))
#self.aidata[grid].append((grids[-1][0]))
else:
#self.aidata[grid] = [Translate.GridMax(grids[-1][0])[0]]
self.aidata[self.hash(grid)] = [Translate.Grid(grids[-1][0], maxgrid[1])]
#self.aidata[grid] = [(grids[-1][0])]
assert len(grids) == 1
#grid = Translate.GridMax(grids.pop()[0])[0]
if DEBUGFUNC:
print 'Last', grids
grid = grids.pop()[0]
if DEBUGFUNC:
print grids, grid
if self.hash(grid) not in self.aidata:
self.aidata[self.hash(grid)] = winner
else:
print self.aidata[self.hash(grid)], winner, self.aidata[self.hash(grid)] == winner
if self.aidata[self.hash(grid)] != winner:
print grid, locals()
assert self.aidata[self.hash(grid)] == winner
# * * * * * * * *
# * UserError *
# * * * * * * * *
class UserError(Exception):
'''
When the User quits pass a unique exception to
eliminate confusion between other valid exceptions.
'''
pass
# * * * * * * * * * * * * * *
# * Grid Display Functions *
# * * * * * * * * * * * * * *
def printXO(b):
'''
Prints the tictactoe grid with XOs
'''
printGrid(b.returnXO())
def printNine(a):
'''
Print the list of 9 in 3x3 form.
'''
print "%2i %2i %2i\n%2i %2i %2i\n%2i %2i %2i\n" % (a[0], a[1], a[2], \
a[3], a[4], a[5], a[6], a[7], a[8])
def printGrid(a):
'''
Basic formatting for lists
'''
if type(a[0]) == type(1):
print
print " %i | %i | %i " % (a[0], a[1], a[2])
print "---+---+---"
print " %i | %i | %i " % (a[3], a[4], a[5])
print "---+---+---"
print " %i | %i | %i " % (a[6], a[7], a[8])
else:
print
print " %c | %c | %c " % (a[0], a[1], a[2])
print "---+---+---"
print " %c | %c | %c " % (a[3], a[4], a[5])
print "---+---+---"
print " %c | %c | %c " % (a[6], a[7], a[8])
def printAIData(a):
'''
Prints a useful representation of the AIdata variable.
'''
print len(a)
for b, c in a.iteritems():
d = b.returnXO()
printEighteen(d, c)
def printEighteen(a, b):
'''
Prints a pair of 3x3 grids next to each other.
'''
print "%c %c %c %2i %2i %2i" % (a[0], a[1], a[2], b[0], b[1], b[2])
print "%c %c %c %2i %2i %2i" % (a[3], a[4], a[5], b[3], b[4], b[5])
print "%c %c %c %2i %2i %2i" % (a[6], a[7], a[8], b[6], b[7], b[8])
print
def printGameGrids(a, one='', two='', three=''):
'''
Prints a resonable representation of the value of
GameGrids and thus the history of the game so far.
When passed a list of tuples with a list as the first item
each with lengths greater than nine prints the first nine
of each list in 3x3 form horizontally.
'''
b = [d[0].returnXO() for d in a]
for c in b:
print c[0], c[1], c[2], "|",
print one
for c in b:
print c[3], c[4], c[5], "|",
print two
for c in b:
print c[6], c[7], c[8], "|",
print three
print
def printGameGridsValues(gamegrids, aidata):
'''
Print the value for each grid in gamegrids based on aidata.
'''
h = []
for i in gamegrids:
f = Translate.FindMax(i[0])
g = Translate.Grid(i[0], f)
#print i , g, f
h.append(Translate.GridReverse(aidata[g], f)
if (g in aidata) else Grid([''] * 9))
printGrids(h)
def printGrids(a):
'''
When passed a list of lists with lengths greater than
nine print the first nine of each list in 3x3 form
horizontally.
'''
for c in a:
print "%2s%2s%2s%c" % (c[0], c[1], c[2], "|"),
print
for c in a:
print "%2s%2s%2s%c" % (c[3], c[4], c[5], "|"),
print
for c in a:
print "%2s%2s%2s%c" % (c[6], c[7], c[8], "|"),
print
print
# * * * * * * * * * * * * * * * *
# * Mostly Depricated Functions * <-- Remove them?
# * * * * * * * * * * * * * * * *
def convertGridToNumber(a):
'''
Hashs a list based on its contents
'''
# int(str(a)) # <-- better?
c = 0
for b in a:
c = c * 10
c = c + b
return c
def convertNumberToGrid(a):
'''
Turns a hash into a list.
'''
b = [] # Make this use Grid()?
for c in str(a):
b.append(int(c))
return b
def convertGridToXO(a):
'''
Returns a list based on values of the input Grid
'''
b = []
c = {0: " ", 1: "X", 2: "O"}
for e in a:
b.append(c[e])
return b
def getEmptySpaces(a):
'''
Returns a list of the spaces that are valued empty.
'''
empty = 0
b = []
for c, d in enumerate(a):
if d == empty:
b.append(c)
return b
def getUsedSpaces(a):
'''
Returns a list of (spaces) list indices that are not valued empty.
'''
empty = 0
b = []
for c, d in enumerate(a):
if d != empty:
b.append(c)
return b
# * * * * * * * * * * * *
# * Translation Helpers *
# * * * * * * * * * * * *
def join(a):
'''
When passed a list joins the list with ":"
'''
return ":".join(a)
def split(a):
'''
The reverse of split. Don't know if these
are called anymore.
Use to initialize a string into a grid?
'''
DEBUGFUNC = 0
assert isinstance(a, str)
return [int(b) for b in a.split(":")]
# * * * * * * * * * * * * *
# * Translation Functions *
# * * * * * * * * * * * * *
class Translate():
@staticmethod
def GetMove(a, b):
'''
Given a (current grid) and b (aidata)
Requires c in b to get move
'''
c, d = Translate.GridMax(a)
if c in b:
f = Translate.GridReverse(b[c], d)
g = [i for i, j in enumerate(f) if j == max(f)]
#g = f.index(max(f))
else:
g = None
return g
@staticmethod
def Grid(a, e):
'''
Returns only the selected transition, designated by e.
'''
assert Translate.Array(a)[e] == Grid([a[f] \
for f in Translate.Data()[e]])
return Grid([a[f] for f in Translate.Data()[e]])
@staticmethod
def GridReverse(a, e):
'''
Returns the Reverse Grid
'''
return Translate.Grid(a, Translate.ReverseIndex(e))
@staticmethod
def ReverseIndex(a):
'''
Returns the complementary translation
Because clockwise turns need reversed with counter-clockwise turns.
'''
b = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 7, 6: 6, 7: 5}
return b[a]
@staticmethod
def Array(a):
'''
Finds all of the possible transitions.
'''
return [Grid([a[f] for f in e]) for e in Translate.Data()]
@staticmethod
def Hash(a):
'''
Return an integer rep. of the grid A.
'''
return int(str(Translate.Grid(a, Translate.FindMax(a))))
@staticmethod
def FindMax(a):
'''
Returns the highest valued transition.
'''
assert a != type("")
return max([(Grid([int(a[f]) for f in e]), d) \
for d, e in enumerate(Translate.Data())])[1]
#Remove the above int()
@staticmethod
def FindIndex(a, b):
'''
Find the translation index from grid A to grid B.
'''
return Translate.Array(a).index(b)
@staticmethod
def GridMax(a):
'''
Returns the maximum valued grid, and the transition index
'''
e = Translate.FindMax(a)
return (Translate.Grid(a, e), e)
@staticmethod
def GuessDifference(one, two):
'''
Returns possible 'correct' forms of two from the
perspective of one.
'''
array = [a - one for a in Translate.Array(two)]
valid = filter(lambda a: (array[a].count(0) == 7) and \
(array[a].count(1) == 1) and (array[a].count(2) == 1), \
range(0, len(array)))
if len(valid) == 0:
print "Not valid?"
print printGrids(array)
printGameGrids([(one,), (two,), (Grid(),)] + [(item,) for item in Translate.Array(two)])
return [(Translate.Array(two)[a], a) for a in valid]
@staticmethod
def Data():
'''
Returns the transitions used for all
'''
return [[0, 1, 2, 3, 4, 5, 6, 7, 8], [2, 1, 0, 5, 4, 3, 8, 7, 6],
[6, 7, 8, 3, 4, 5, 0, 1, 2], [8, 5, 2, 7, 4, 1, 6, 3, 0],
[0, 3, 6, 1, 4, 7, 2, 5, 8], [6, 3, 0, 7, 4, 1, 8, 5, 2],
[8, 7, 6, 5, 4, 3, 2, 1, 0], [2, 5, 8, 1, 4, 7, 0, 3, 6]]
# * * * * * * * * * * * * * * * * *
# * Sorting and Filter Functions *
# * * * * * * * * * * * * * * * * *
def mapGrid(f, grid):
'''
Map grid looks at the important lines on a grid and
compares them using a passed function 'f'
'''
lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), \
(0, 3, 6), (1, 4, 7), (2, 5, 8), \
(0, 4, 8), (2, 4, 6)]
return [f(line, grid) for line in lines]
def pickGameOver(sample, grid):
'''
Picks the in a given sample. Ex: row.
'''
values = [grid[sample[0]], grid[sample[1]], grid[sample[2]]]
if values[0] == values[1] == values[2] and values[0] != 0:
return (values[0])
return (None)
def pickPlay(sample, grid):
'''
Picks the open space in a given sample. Ex: row.
'''
values = [grid[sample[0]], grid[sample[1]], grid[sample[2]]]
if values.count(0) == 1:
index = values.index(0)
del values[index]
if values[0] == values[1]:
return (values[0], sample[index])
return (None, None)
def gameOver(grid):
'''