-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
143 lines (116 loc) · 4.36 KB
/
script.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
import {gameTitle, scenario, firstCall, imageStyle, doAfterEachAction} from "./adventureData.js";
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('game-title').innerText = gameTitle;
const userInputElement = document.getElementById('user-input');
const userInputFormElement = document.getElementById('user-input-form');
const statusBarContainer = document.getElementById('status-bars');
const illustrativeImageElement = document.getElementById('illustrative-image');
const sceneDescriptionElement = document.getElementById('scene-description');
const loadingContainer = document.getElementById('loading-container');
statusBarContainer.innerHTML = '';
let state = {
log: '',
};
function extractTags(text) {
const tagRegex = /\$([A-Z_]+)\s(.*?)\$/g;
const tags = [];
let match;
const names = {};
while ((match = tagRegex.exec(text)) !== null) {
const name = match[1].replace('_', ' ');
if(name in names) continue;
names[name] = true;
tags.push(`${name}: ${match[2]}`);
}
return tags;
}
function removeTags(text) {
const tagRegex = /\$[A-Z_]+\s.*?\$/g;
return text.replace(tagRegex, '').trim();
}
let lastImageUpdateTime = 0;
function updateDisplay(newState) {
// Update the scene description
sceneDescriptionElement.innerHTML = removeTags(newState.txt);
// Update the status bars
statusBarContainer.innerHTML = extractTags(newState.txt)
.filter(x => !x.startsWith("IMAGE:"))
.map(status => `<div class="d-flex align-items-center"><span class="mx-2">${status}</span></div>`)
.join('');
// images?
const images = extractTags(newState.txt).filter(x => x.startsWith("IMAGE:"));
const currentTime = new Date().getTime();
if (images.length === 1 && currentTime - lastImageUpdateTime >= 120000) {
lastImageUpdateTime = currentTime;
updateImage(images[0].substring(6)).then(() => {
console.log("update image done");
});
}
}
async function callApi(action) {
showLoading();
const response = await fetch('backend.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
scn: scenario.split("\n").join(" ").trim(),
act: action.trim() + "\n(Note: " + doAfterEachAction + ")",
log: state.log,
}),
});
hideLoading();
const newState = await response.json();
if(newState.err) {
console.error(newState.err);
return;
}
console.log(newState.txt);
state.log += `\n\n${newState.txt}`;
updateDisplay(newState);
}
function showLoading() {
loadingContainer.style.display = 'flex';
}
function hideLoading() {
loadingContainer.style.display = 'none';
}
async function updateImage(text) {
text = text + " " + imageStyle;
console.log("update image: ", text);
const apiUrl = 'image.php';
const requestData = {
text: text
};
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
const imageUrl = data.img_url;
console.log("loaded image!", imageUrl);
illustrativeImageElement.src = imageUrl;
} catch (error) {
console.error('Error updating image:', error);
}
}
userInputFormElement.addEventListener('submit', async (event) => {
event.preventDefault();
// Get the user action from the input field
const userAction = userInputElement.value.trim();
// Call the API with the user action
await callApi(userAction);
// Clear the input field
userInputElement.value = '';
});
// Initialize the game
callApi(firstCall);
});