-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
150 lines (115 loc) ยท 4.52 KB
/
Copy pathbot.js
File metadata and controls
150 lines (115 loc) ยท 4.52 KB
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
const API_BASE_URL = 'http://localhost:8000';
const API_GAME_URL = `${API_BASE_URL}/api/game`;
// Credentials van je bot-gebruiker in de database
const BOT_CREDENTIALS = {
username: 'Tester',
password: 'testen'
};
function waitForAnyKey() {
return new Promise((resolve) => {
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.once('data', (data) => {
process.stdin.setRawMode(false);
process.stdin.pause();
resolve(data.toString());
});
});
}
function chooseCardToPlay(legalMoves, currentTrickCards = []) {
if (!legalMoves || legalMoves.length === 0) {
throw new Error("No legal moves provided by server!");
}
if (currentTrickCards.length === 0) {
return legalMoves.reduce((min, c) => c.rank < min.rank ? c : min);
}
const leadSuit = currentTrickCards[0].card.suit;
const sameSuitOnTable = currentTrickCards
.filter(t => t.card.suit === leadSuit)
.map(t => t.card.rank);
const maxOnTable = Math.max(...sameSuitOnTable);
const safeCards = legalMoves.filter(c => c.suit === leadSuit && c.rank < maxOnTable);
if (safeCards.length > 0) {
return safeCards.reduce((max, c) => c.rank > max.rank ? c : max);
}
return legalMoves.reduce((max, c) => c.rank > max.rank ? c : max);
}
let jwtToken = null;
async function loginAndGetToken() {
console.log(`๐ Logging in as ${BOT_CREDENTIALS.username}...`);
const response = await fetch(`${API_BASE_URL}/api/login_check`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(BOT_CREDENTIALS)
});
const data = await response.json();
if (!response.ok || !data.token) {
throw new Error(`โ JWT Login Mislukt: ${JSON.stringify(data)}`);
}
jwtToken = data.token;
console.log("โ
JWT Token succesvol ontvangen!");
}
async function jwtFetch(url, options = {}) {
if (!jwtToken) {
throw new Error("Geen JWT token aanwezig. Log eerst in!");
}
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${jwtToken}`,
...(options.headers || {})
};
return fetch(url, { ...options, headers }).then(r => r.json());
}
async function playBotGame() {
try {
await loginAndGetToken();
console.log("๐ฎ Starting new bot game...");
let res = await jwtFetch(`${API_GAME_URL}/start`, { method: 'POST' });
if (res.error || !res.game_state) {
console.error("โ Failed to start game:", res);
return;
}
let gameId = res.game_id;
console.log("Game ID:", gameId);
await waitForAnyKey();
while (res.game_state && !res.game_state.is_finished) {
//await waitForAnyKey();
const state = res.game_state;
const myHand = state.hand || [];
if (state.state === 'PASSING_CARDS') {
const sortedHand = [...myHand].sort((a, b) => b.rank - a.rank);
const cardsToPass = sortedHand.slice(0, 3).map(c => ({
suit: c.suit,
rank: Number(c.rank)
}));
res = await jwtFetch(`${API_GAME_URL}/${gameId}/pass`, {
method: 'POST',
body: JSON.stringify({ cards: cardsToPass })
});
if (res.error || !res.game_state) {
console.error("โ Pass cards failed:", res.error || res);
break;
}
// Phase 2: PLAYING_TRICKS
} else if (state.state === 'PLAYING_TRICKS' && state.your_turn) {
const currentTrickCards = state.current_trick?.cards || [];
const legalMoves = state.legal_moves || [];
const cardToPlay = chooseCardToPlay(legalMoves, currentTrickCards);
res = await jwtFetch(`${API_GAME_URL}/${gameId}/play`, {
method: 'POST',
body: JSON.stringify({ suit: cardToPlay.suit, rank: cardToPlay.rank })
});
if (res.error || !res.game_state) {
console.error("โ Play card failed:", res.error || res);
break;
}
}
}
if (res?.game_state?.is_finished) {
console.log("๐ Game finished! Final scores:", res.game_state.total_scores);
}
} catch (e) {
console.error("๐ฅ Error during bot game execution:", e.message);
}
}
playBotGame();