-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbenchmark.py
91 lines (74 loc) · 2.14 KB
/
benchmark.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
"""
benchmark algorithms and output results.
this file uses multiprocessing and bypass the graphical output so the speed is 4x
modified from Github (https://gist.github.com/fungus/9821090)
@author: peterwongny
1. use txt file instead of database
2. migrate to python 3
3. now can use different algorithms
"""
#please remember to change the algorithm when use
import sys
import random
from time import time
from multiprocessing import Process, Queue
from term2048.game import Game
from term2048 import randomMove
from term2048 import greedyMove
from term2048 import nStepLookAhead
from term2048 import expectimaxMove
def run_game(q1, q2):
while True:
g = Game()
while g.board.canMove():
# m = randomMove.next_move()
# m = greedyMove.next_move(g.board)
m = nStepLookAhead.next_move(g.board,5)
# m = expectimaxMove.next_move(g.board)
g.incScore(g.board.move(m))
if g.board.won():
print("\n")
print(g)
q1.put(g.score)
q2.put(g.board.won())
def progress():
now = time()
rate = count / (now - start)
output = "\r%i high %f game/s %i total" % (high_score,rate,count)
sys.stdout.write(output)
sys.stdout.flush()
if __name__ == '__main__':
# Initialization
start = time()
count = 0
high_score = 0
procs = []
q1 = Queue()
q2 = Queue()
file_name = input("file name: ")
file_name += ".txt"
out_file = open(file_name,"w")
# Start game processes
for i in range(4):
p = Process(target=run_game,args=(q1, q2))
procs.append(p)
p.start()
# Main loop to record scores
try:
while True:
score = q1.get()
won = q2.get()
k = str(score)
if score > high_score:
high_score = score
out_file.write(str(count)+"\t")
out_file.write(str(score)+"\t")
out_file.write(str(won)+"\t")
out_file.write("\n")
out_file.flush()
count += 1
progress()
# Cleanup
finally:
for p in procs:
p.terminate()