-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2048.py
executable file
·79 lines (62 loc) · 1.86 KB
/
2048.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
''' Help the user achieve a high score in a real game of 2048 by using a move searcher. '''
from __future__ import print_function
import ctypes
import time
import os
for suffix in ['so', 'dll', 'dylib']:
dllfn = 'bin/2048.' + suffix
ailib = ctypes.CDLL(dllfn)
ailib.init_tables()
ailib.find_best_move.argtypes = [ctypes.c_uint64]
ailib.score_toplevel_move.argtypes = [ctypes.c_uint64, ctypes.c_int]
ailib.score_toplevel_move.restype = ctypes.c_float
def to_c_board(m):
board = 0
i = 0
for row in m:
for c in row:
board |= int(c) << (4*i)
i += 1
return board
from multiprocessing.pool import ThreadPool
pool = ThreadPool(4)
def score_toplevel_move(args):
return ailib.score_toplevel_move(*args)
def find_best_move(m):
board = to_c_board(m)
scores = pool.map(score_toplevel_move, [(board, move) for move in range(4)])
bestmove, bestscore = max(enumerate(scores), key=lambda x:x[1])
if bestscore == 0:
return -1
return bestmove
def movename(move):
return ['up', 'down', 'left', 'right'][move]
def play_game(gamectrl):
moveno = 0
start = time.time()
while 1:
state = gamectrl.get_status()
if state == 'ended':
break
elif state == 'won':
time.sleep(0.75)
gamectrl.continue_game()
moveno += 1
board = gamectrl.get_board()
move = find_best_move(board)
if move < 0:
break
gamectrl.execute_move(move)
def main():
from chromectrl import ChromeDebuggerControl
port = 32768
ctrl = ChromeDebuggerControl(port)
from gamectrl import Hybrid2048Control
gamectrl = Hybrid2048Control(ctrl)
if gamectrl.get_status() == 'ended':
gamectrl.restart_game()
play_game(gamectrl)
if __name__ == '__main__':
exit(main())