452 lines
13 KiB
JavaScript
452 lines
13 KiB
JavaScript
/**
|
|
* AI Interactive Fiction
|
|
* Main client-side logic for web interface
|
|
*/
|
|
class AIFiction {
|
|
constructor() {
|
|
// DOM elements
|
|
this.storyContainer = document.getElementById('story');
|
|
this.commandHistoryContainer = document.getElementById('command_history');
|
|
this.playerInput = document.getElementById('player_input');
|
|
this.submitButton = document.getElementById('submit_command');
|
|
this.speechButton = document.getElementById('speech');
|
|
this.rewindButton = document.getElementById('rewind');
|
|
this.saveButton = document.getElementById('save');
|
|
this.loadButton = document.getElementById('reload');
|
|
this.speedSlider = document.getElementById('speed');
|
|
this.speedReset = document.getElementById('speed_reset');
|
|
|
|
// Game state
|
|
this.gameState = {
|
|
started: false,
|
|
currentRoomId: '',
|
|
textSpeed: 50
|
|
};
|
|
|
|
// Socket connection - ensure we're connecting to the right URL
|
|
this.socket = io(window.location.origin, {
|
|
reconnectionAttempts: 5,
|
|
timeout: 10000
|
|
});
|
|
|
|
// Typing effect configuration
|
|
this.typingSpeed = 30; // Default value, will be adjusted by slider
|
|
this.typingTimeout = null;
|
|
|
|
// Bind event handlers
|
|
this.bindEvents();
|
|
|
|
// Initialize socket communication
|
|
this.initializeSocket();
|
|
|
|
// Initialize UI
|
|
this.initializeUI();
|
|
}
|
|
|
|
/**
|
|
* Initialize the UI
|
|
*/
|
|
initializeUI() {
|
|
this.updateTypingSpeed();
|
|
this.updateSpeechButton();
|
|
|
|
// Disable buttons initially
|
|
this.rewindButton.setAttribute('disabled', 'disabled');
|
|
this.loadButton.setAttribute('disabled', 'disabled');
|
|
|
|
// Start the game
|
|
this.startGame();
|
|
}
|
|
|
|
/**
|
|
* Bind event handlers to DOM elements
|
|
*/
|
|
bindEvents() {
|
|
// Submit command on button click
|
|
this.submitButton.addEventListener('click', () => this.submitCommand());
|
|
|
|
// Submit command on Enter key
|
|
this.playerInput.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter') {
|
|
this.submitCommand();
|
|
}
|
|
});
|
|
|
|
// Toggle speech
|
|
this.speechButton.addEventListener('click', () => {
|
|
if (ttsHandler && typeof ttsHandler.isEnabled === 'function') {
|
|
const enabled = ttsHandler.toggle();
|
|
this.updateSpeechButton(enabled);
|
|
|
|
if (enabled) {
|
|
// Speak the last narrative if speech was just enabled
|
|
const lastNarrative = this.storyContainer.lastElementChild;
|
|
if (lastNarrative && lastNarrative.classList.contains('narrative')) {
|
|
ttsHandler.speak(lastNarrative.textContent);
|
|
}
|
|
}
|
|
} else {
|
|
console.log('TTS not ready yet');
|
|
}
|
|
});
|
|
|
|
// Restart game
|
|
this.rewindButton.addEventListener('click', () => {
|
|
if (confirm('Are you sure you want to restart the game? All progress will be lost.')) {
|
|
this.startGame();
|
|
}
|
|
});
|
|
|
|
// Save game
|
|
this.saveButton.addEventListener('click', () => {
|
|
this.socket.emit('saveGame');
|
|
});
|
|
|
|
// Load game
|
|
this.loadButton.addEventListener('click', () => {
|
|
this.socket.emit('loadGame');
|
|
});
|
|
|
|
// Adjust typing speed
|
|
this.speedSlider.addEventListener('input', () => {
|
|
this.updateTypingSpeed();
|
|
});
|
|
|
|
// Reset speed to default
|
|
this.speedReset.addEventListener('click', () => {
|
|
this.speedSlider.value = 50;
|
|
this.updateTypingSpeed();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Initialize socket event handlers
|
|
*/
|
|
initializeSocket() {
|
|
// Connection established
|
|
this.socket.on('connect', () => {
|
|
console.log('Connected to server');
|
|
// Automatically start the game once connected
|
|
if (!this.gameState.started) {
|
|
this.startGame();
|
|
}
|
|
});
|
|
|
|
// Connection error
|
|
this.socket.on('connect_error', (error) => {
|
|
console.error('Connection error:', error);
|
|
this.addSystemMessage('Connection error. Please check your network connection and try again.');
|
|
});
|
|
|
|
// Game introduction received
|
|
this.socket.on('gameIntroduction', (data) => {
|
|
this.clearStory();
|
|
this.addNarrative(data.introduction);
|
|
this.addNarrative(data.initialRoomDescription);
|
|
|
|
this.gameState.started = true;
|
|
this.gameState.currentRoomId = data.currentRoomId;
|
|
|
|
// Enable buttons
|
|
this.rewindButton.removeAttribute('disabled');
|
|
|
|
// Focus on input field
|
|
this.playerInput.focus();
|
|
});
|
|
|
|
// Narrative response received
|
|
this.socket.on('narrativeResponse', (data) => {
|
|
// Clear any pending "thinking" indicators
|
|
if (this.currentCommandTimeout) {
|
|
clearTimeout(this.currentCommandTimeout);
|
|
this.currentCommandTimeout = null;
|
|
|
|
// Remove any existing thinking indicators
|
|
document.querySelectorAll('.thinking').forEach(el => el.remove());
|
|
}
|
|
|
|
this.addNarrative(data.text);
|
|
|
|
if (data.suggestions && data.suggestions.length > 0) {
|
|
this.addSuggestions(data.suggestions);
|
|
}
|
|
|
|
// Update game state
|
|
if (data.gameState) {
|
|
this.gameState.currentRoomId = data.gameState.currentRoomId;
|
|
}
|
|
|
|
// Scroll to bottom and focus input
|
|
this.scrollToBottom();
|
|
this.playerInput.focus();
|
|
|
|
// Re-enable input (failsafe)
|
|
this.playerInput.disabled = false;
|
|
this.submitButton.disabled = false;
|
|
});
|
|
|
|
// Game saved confirmation
|
|
this.socket.on('gameSaved', () => {
|
|
this.addSystemMessage('Game saved successfully.');
|
|
// Enable load button
|
|
this.loadButton.removeAttribute('disabled');
|
|
});
|
|
|
|
// Game loaded confirmation
|
|
this.socket.on('gameLoaded', (data) => {
|
|
this.clearStory();
|
|
this.addSystemMessage('Game loaded successfully.');
|
|
this.addNarrative(data.currentRoomDescription);
|
|
|
|
// Update game state
|
|
this.gameState.currentRoomId = data.currentRoomId;
|
|
});
|
|
|
|
// Error messages
|
|
this.socket.on('error', (data) => {
|
|
this.addSystemMessage(`Error: ${data.message}`);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Start a new game
|
|
*/
|
|
startGame() {
|
|
this.clearStory();
|
|
this.addSystemMessage('Starting a new game...');
|
|
this.socket.emit('startGame');
|
|
}
|
|
|
|
/**
|
|
* Submit a player command
|
|
*/
|
|
submitCommand() {
|
|
const command = this.playerInput.value.trim();
|
|
|
|
if (command === '') return;
|
|
|
|
// Disable input temporarily
|
|
this.playerInput.disabled = true;
|
|
this.submitButton.disabled = true;
|
|
|
|
// Add command to history
|
|
this.addUserCommand(command);
|
|
|
|
// Add a temporary "thinking" message
|
|
const thinkingId = this.addThinking();
|
|
|
|
// Send command to server
|
|
this.socket.emit('playerCommand', { command });
|
|
|
|
// Clear input
|
|
this.playerInput.value = '';
|
|
|
|
// Re-enable input field after a short delay (or after 8 seconds as failsafe)
|
|
const timeout = setTimeout(() => {
|
|
this.playerInput.disabled = false;
|
|
this.submitButton.disabled = false;
|
|
|
|
// Remove thinking indicator
|
|
const thinkingElement = document.getElementById(thinkingId);
|
|
if (thinkingElement) {
|
|
thinkingElement.remove();
|
|
}
|
|
|
|
// Add system message if no response was received (likely timeout)
|
|
if (document.getElementById(thinkingId)) {
|
|
this.addSystemMessage('The server is taking too long to respond. Please try again.');
|
|
}
|
|
}, 8000);
|
|
|
|
// Store the timeout so it can be cleared if we get a response
|
|
this.currentCommandTimeout = timeout;
|
|
}
|
|
|
|
/**
|
|
* Add a user command to the story
|
|
*/
|
|
addUserCommand(command) {
|
|
const element = document.createElement('p');
|
|
element.className = 'user-input';
|
|
element.textContent = `> ${command}`;
|
|
this.storyContainer.appendChild(element);
|
|
this.scrollToBottom();
|
|
}
|
|
|
|
/**
|
|
* Add a narrative response with typing effect
|
|
*/
|
|
addNarrative(text) {
|
|
const element = document.createElement('p');
|
|
element.className = 'narrative hide';
|
|
this.storyContainer.appendChild(element);
|
|
|
|
// Apply SmartyPants transformations for better typography
|
|
const processedText = SmartyPants.smartypantsu ? SmartyPants.smartypantsu(text, 1) : text;
|
|
|
|
// Clear any existing typing timeouts
|
|
if (this.typingTimeout) {
|
|
clearTimeout(this.typingTimeout);
|
|
}
|
|
|
|
// Add the text with a typing effect
|
|
this.typeText(element, processedText, 0);
|
|
|
|
// Read text aloud if speech is enabled
|
|
if (ttsHandler && ttsHandler.isEnabled()) {
|
|
ttsHandler.speak(text);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Add suggestions to the story
|
|
*/
|
|
addSuggestions(suggestions) {
|
|
const element = document.createElement('div');
|
|
element.className = 'suggestions';
|
|
|
|
const heading = document.createElement('p');
|
|
heading.textContent = 'Suggestions:';
|
|
heading.style.fontStyle = 'italic';
|
|
heading.style.marginTop = '1rem';
|
|
element.appendChild(heading);
|
|
|
|
const list = document.createElement('ul');
|
|
suggestions.forEach(suggestion => {
|
|
const item = document.createElement('li');
|
|
item.textContent = suggestion;
|
|
|
|
// Make suggestions clickable
|
|
item.style.cursor = 'pointer';
|
|
item.addEventListener('click', () => {
|
|
this.playerInput.value = suggestion;
|
|
this.submitCommand();
|
|
});
|
|
|
|
list.appendChild(item);
|
|
});
|
|
element.appendChild(list);
|
|
|
|
this.storyContainer.appendChild(element);
|
|
this.scrollToBottom();
|
|
}
|
|
|
|
/**
|
|
* Add a system message
|
|
*/
|
|
addSystemMessage(message) {
|
|
const element = document.createElement('p');
|
|
element.className = 'system-message';
|
|
element.textContent = message;
|
|
element.style.fontStyle = 'italic';
|
|
element.style.color = '#555';
|
|
this.storyContainer.appendChild(element);
|
|
this.scrollToBottom();
|
|
}
|
|
|
|
/**
|
|
* Add a thinking indicator
|
|
*/
|
|
addThinking() {
|
|
const id = 'thinking-' + Date.now();
|
|
const element = document.createElement('div');
|
|
element.id = id;
|
|
element.className = 'thinking';
|
|
element.innerHTML = '<p>Thinking<span class="loading-indicator"><span>.</span><span>.</span><span>.</span></span></p>';
|
|
element.style.fontStyle = 'italic';
|
|
element.style.color = '#777';
|
|
this.storyContainer.appendChild(element);
|
|
this.scrollToBottom();
|
|
return id;
|
|
}
|
|
|
|
/**
|
|
* Clear the story container
|
|
*/
|
|
clearStory() {
|
|
while (this.storyContainer.firstChild) {
|
|
this.storyContainer.removeChild(this.storyContainer.firstChild);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Type text into an element character by character
|
|
*/
|
|
typeText(element, text, index) {
|
|
// Show the element if it was hidden
|
|
if (index === 0) {
|
|
element.classList.remove('hide');
|
|
}
|
|
|
|
// Set the current text
|
|
element.textContent = text.substring(0, index);
|
|
|
|
// If we haven't reached the end of the text
|
|
if (index < text.length) {
|
|
// Calculate delay (randomize slightly for more natural effect)
|
|
const delay = Math.max(10, 100 - this.gameState.textSpeed) / 5;
|
|
const randomDelay = delay * (0.8 + Math.random() * 0.4);
|
|
|
|
// Schedule the next character
|
|
this.typingTimeout = setTimeout(() => {
|
|
this.typeText(element, text, index + 1);
|
|
}, randomDelay);
|
|
} else {
|
|
// Finished typing
|
|
this.scrollToBottom();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update the typing speed based on the slider value
|
|
*/
|
|
updateTypingSpeed() {
|
|
this.gameState.textSpeed = parseInt(this.speedSlider.value, 10);
|
|
}
|
|
|
|
/**
|
|
* Update the speech button styling
|
|
*/
|
|
updateSpeechButton(enabled = false) {
|
|
if (enabled) {
|
|
this.speechButton.style.fontWeight = 'bold';
|
|
this.speechButton.style.color = '#000';
|
|
} else {
|
|
this.speechButton.style.fontWeight = 'normal';
|
|
this.speechButton.style.color = '#333';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Scroll the story container to the bottom
|
|
*/
|
|
scrollToBottom() {
|
|
const container = document.getElementById('page_right');
|
|
if (container) {
|
|
container.scrollTop = container.scrollHeight;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Create the application when the DOM is fully loaded
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
// Set custom CSS variables based on viewport
|
|
const updateViewportVariables = () => {
|
|
const vw = window.innerWidth;
|
|
const vh = window.innerHeight;
|
|
document.documentElement.style.setProperty('--viewport-aspect-ratio', `${vw / vh}`);
|
|
|
|
// Adjust book size based on viewport
|
|
const bookWidth = Math.min(vw * 0.9, vh * 1.4);
|
|
const bookHeight = bookWidth / 1.613;
|
|
document.documentElement.style.setProperty('--book-width', `${bookWidth}px`);
|
|
document.documentElement.style.setProperty('--book-height', `${bookHeight}px`);
|
|
};
|
|
|
|
// Update variables initially and on resize
|
|
updateViewportVariables();
|
|
window.addEventListener('resize', updateViewportVariables);
|
|
|
|
// Initialize the application
|
|
window.app = new AIFiction();
|
|
}); |