-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrun-pptr-web.js
202 lines (145 loc) · 5.41 KB
/
run-pptr-web.js
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
import { puppeteer, runChrome } from './index.js';
//import puppeteer from './puppeteer-web.js';
//import procChrome from './proc-chrome.js';
import { makeGif, deletePics } from './run-ffmpeg.js';
import {
cpScore,
calculateBoardOutcomes,
calculateLegalMoves,
} from 'https://denopkg.com/nikfrank/react-sheshbesh/src/util.js';
const wait = t=> (new Promise(f=> setTimeout(f, t)));
const [proc, ws] = await runChrome();
await wait(900);
const url = 'http://sheshbesh.nikfrank.com/';
const port = 9222;
const response = await fetch('http://localhost:'+port+'/json')
const tabs = await response.json();
// this entails trailing / (as browser fills that in)
const socketUrl = tabs
.find((tab={ url: null }) => tab.url === url)
.webSocketDebuggerUrl;
const browser = await puppeteer.connect({
browserWSEndpoint: socketUrl,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle2' });
const pageDriver = {
picCount: 0,
savePic: selector=> !selector ? page.screenshot({
path: `pic${pageDriver.picCount++}.png`,
fullPage: true,
encoding: 'base64',
}) : (async ()=>{
const rect = await page.evaluate(selector => {
const element = document.querySelector(selector);
if (!element) return null;
const {x, y, width, height} = element.getBoundingClientRect();
return {left: x, top: y, width, height, id: element.id};
}, selector);
if (!rect)
throw Error(`Could not find element that matches selector: ${selector}.`);
return await page.screenshot({
path: `pic${pageDriver.picCount++}.png`,
clip: {
x: rect.left,
y: rect.top,
width: rect.width,
height: rect.height,
},
encoding: 'base64',
});
})(),
click: selector=> page.evaluate(selector=> {
document.querySelector(selector)?.click();
}, selector),
clickSVG: selector=> page.evaluate((selector)=>{
const event = document.createEvent("SVGEvents");
event.initEvent("click",true,true);
document.querySelector(selector).dispatchEvent(event);
}, selector),
dblclickSVG: selector=> page.evaluate((selector)=> {
const event = document.createEvent("SVGEvents");
event.initEvent("dblclick",true,true);
document.querySelector(selector).dispatchEvent(event);
}, selector),
}
const getGameState = ()=> page.evaluate(()=> ({
dice: [...document.querySelectorAll('.dice-container svg')]
.map((_, i)=>
document.querySelectorAll('.dice-container svg:nth-child('+(i+1)+') circle').length
),
blackJail: document.querySelectorAll('.Board > circle.black-chip').length,
whiteJail: document.querySelectorAll('.Board > circle.white-chip').length,
chips: [
...document.querySelectorAll('.Board > g:not(:nth-of-type(1)):not(:nth-of-type(2))')
].map(chip => (
(chip.querySelectorAll('.black-chip').length) -
(chip.querySelectorAll('.white-chip').length)
)),
blackHome: document.querySelectorAll('.Board .black-home').length,
whiteHome: document.querySelectorAll('.Board .white-home').length,
turn: 'black', // no easy way to determine this from DOM
}));
const getBestMoves = (board)=> {
const options = calculateBoardOutcomes(board);
if( !options.length ) return console.log('no move', board.dice);
const scoredOptions = options.map(option=> ({
score: cpScore(option.board), moves: option.moves,
}));
const bestMoves = scoredOptions.sort((a, b)=> (b.score - a.score) )[0].moves;
return bestMoves;
};
// click based on moves.
let prev, gameState;
const clickMove = (async (move)=>{
for( let i=0, moveFrom, moveTo; i < move.length; i++) {
gameState = await getGameState();
prev = gameState.dice.toString() + gameState.chips.toString();
if( typeof move[i].moveFrom === 'number' )
await pageDriver.clickSVG('.Board > g:nth-of-type('+(move[i].moveFrom+3)+') rect');
if( typeof move[i].moveTo === 'number' )
await pageDriver.clickSVG('.Board > g:nth-of-type('+(move[i].moveTo+3)+') rect');
if( (''+move[i].moveTo).includes('Home') )
await pageDriver.dblclickSVG('.Board > g:nth-of-type('+(move[i].moveFrom+3)+') rect');
gameState = await getGameState();
if( (gameState.dice.toString() + gameState.chips.toString()) !== prev )
await pageDriver.savePic('svg');
}
});
await page.evaluate(()=>{
const TO = window.setTimeout;
window.setTimeout = (fn, t)=> TO(fn, t/4);
});
const roll = ()=> pageDriver.click('.dice-container button');
await roll();
await pageDriver.savePic('svg');
gameState = await getGameState();
let move = getBestMoves(gameState);
await clickMove(move);
let maxHome = 0;
for( let j=0; j < 200; j++){
gameState = await getGameState();
if( (gameState.dice.toString() + gameState.chips.toString()) !== prev )
await pageDriver.savePic('svg');
const nextMax = Math.max(gameState.blackHome, gameState.whiteHome);
if( nextMax > maxHome ) maxHome = nextMax;
if( nextMax < maxHome || nextMax === 15 ) break;
await roll();
await wait(20);
if( (gameState.dice.toString() + gameState.chips.toString()) !== prev ){
await pageDriver.savePic('svg');
gameState = await getGameState();
move = getBestMoves(gameState);
if(move){
await clickMove(move);
await pageDriver.savePic('svg');
}
}
prev = gameState.dice.toString() + gameState.chips.toString();
await wait(100);
}
await makeGif();
await deletePics();
proc.close();
Deno.exit(0);