Initial commit
This commit is contained in:
@@ -0,0 +1,440 @@
|
||||
/**
|
||||
* 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 (tts.isReady()) {
|
||||
const enabled = tts.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')) {
|
||||
tts.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) => {
|
||||
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.process(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 (tts && tts.enabled) {
|
||||
tts.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"><div></div><div></div><div></div><div></div></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() {
|
||||
this.storyContainer.scrollTop = this.storyContainer.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();
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* SmartyPants - Smart typography for web content
|
||||
* Converts straight quotes to curly quotes, dashes to em-dashes, etc.
|
||||
* Based on the original SmartyPants by John Gruber
|
||||
*/
|
||||
|
||||
const SmartyPants = (function() {
|
||||
// Regular expressions for matching
|
||||
const quotes = {
|
||||
double: {
|
||||
opening: /(\s|^)"(\w)/g,
|
||||
closing: /(\w)"/g,
|
||||
openingNested: /(\s|^)'(\w)/g,
|
||||
closingNested: /(\w)'/g
|
||||
},
|
||||
single: {
|
||||
opening: /(\s|^)'(\w)/g,
|
||||
closing: /(\w)'/g
|
||||
}
|
||||
};
|
||||
|
||||
const dashes = {
|
||||
emDash: /--/g,
|
||||
enDash: / - /g
|
||||
};
|
||||
|
||||
const ellipses = /\.\.\./g;
|
||||
|
||||
/**
|
||||
* Process text with SmartyPants transformations
|
||||
*/
|
||||
function process(text) {
|
||||
if (!text) return text;
|
||||
|
||||
let result = text;
|
||||
|
||||
// Transform double quotes
|
||||
result = result.replace(quotes.double.opening, '$1"$2');
|
||||
result = result.replace(quotes.double.closing, '$1"');
|
||||
|
||||
// Transform single quotes
|
||||
result = result.replace(quotes.single.opening, '$1\u2018$2');
|
||||
result = result.replace(quotes.single.closing, '$1\u2019');
|
||||
|
||||
// Transform apostrophes (same as closing single quotes)
|
||||
result = result.replace(/(\w)'(\w)/g, '$1\u2019$2');
|
||||
|
||||
// Transform dashes
|
||||
result = result.replace(dashes.emDash, '—');
|
||||
result = result.replace(dashes.enDash, ' – ');
|
||||
|
||||
// Transform ellipses
|
||||
result = result.replace(ellipses, '…');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
process: process
|
||||
};
|
||||
})();
|
||||
|
||||
// Make available in browser and Node.js environments
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = SmartyPants;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Text-to-Speech Handler for AI Interactive Fiction
|
||||
* Uses Web Speech API for text-to-speech
|
||||
*/
|
||||
class TTSHandler {
|
||||
constructor() {
|
||||
this.enabled = false;
|
||||
this.speaking = false;
|
||||
this.queue = [];
|
||||
this.synthesis = window.speechSynthesis;
|
||||
this.utterance = null;
|
||||
|
||||
// Check if browser supports speech synthesis
|
||||
if (this.synthesis) {
|
||||
console.log('Speech synthesis is supported in this browser');
|
||||
this.browserSupport = true;
|
||||
} else {
|
||||
console.warn('Speech synthesis is not supported in this browser');
|
||||
this.browserSupport = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle TTS on/off
|
||||
*/
|
||||
toggle() {
|
||||
this.enabled = !this.enabled;
|
||||
if (!this.enabled && this.speaking) {
|
||||
this.stop();
|
||||
}
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Speak the given text
|
||||
*/
|
||||
speak(text) {
|
||||
if (!this.enabled || !this.browserSupport) return;
|
||||
|
||||
// Add to queue
|
||||
this.queue.push(text);
|
||||
|
||||
// If not already speaking, start processing queue
|
||||
if (!this.speaking) {
|
||||
this.processQueue();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the speech queue
|
||||
*/
|
||||
processQueue() {
|
||||
if (this.queue.length === 0 || this.speaking) return;
|
||||
|
||||
this.speaking = true;
|
||||
const text = this.queue.shift();
|
||||
|
||||
try {
|
||||
this.utterance = new SpeechSynthesisUtterance(text);
|
||||
|
||||
// Configure speech options
|
||||
this.utterance.rate = 1.0; // Speech rate (0.1 to 10)
|
||||
this.utterance.pitch = 1.0; // Speech pitch (0 to 2)
|
||||
|
||||
// When speech ends, process the next item
|
||||
this.utterance.onend = () => {
|
||||
this.speaking = false;
|
||||
this.processQueue();
|
||||
};
|
||||
|
||||
// If speech is interrupted or errors
|
||||
this.utterance.onerror = (event) => {
|
||||
console.error('TTS error:', event.error);
|
||||
this.speaking = false;
|
||||
this.processQueue();
|
||||
};
|
||||
|
||||
this.synthesis.speak(this.utterance);
|
||||
} catch (error) {
|
||||
console.error('TTS error:', error);
|
||||
this.speaking = false;
|
||||
this.processQueue();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop current speech
|
||||
*/
|
||||
stop() {
|
||||
if (this.synthesis && this.speaking) {
|
||||
this.synthesis.cancel();
|
||||
}
|
||||
this.queue = [];
|
||||
this.speaking = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if TTS is ready
|
||||
*/
|
||||
isReady() {
|
||||
return this.browserSupport;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a global instance
|
||||
const tts = new TTSHandler();
|
||||
Reference in New Issue
Block a user