Skip to content

Instantly share code, notes, and snippets.

@mchost252
Created June 6, 2025 16:14
Show Gist options
  • Save mchost252/8759cc0b7d13a0810edc545cd07053c3 to your computer and use it in GitHub Desktop.
Save mchost252/8759cc0b7d13a0810edc545cd07053c3 to your computer and use it in GitHub Desktop.
const { bot, generateList } = require('../lib/')
// Enhanced game storage with persistent data
const activeGames = new Map()
const gameScores = new Map()
const playerStats = new Map()
const gameHistory = new Map()
const achievements = new Map()
// Game achievements system
const ACHIEVEMENTS = {
'first_win': { name: '🏆 First Victory', desc: 'Win your first game', points: 10 },
'speed_demon': { name: '⚡ Speed Demon', desc: 'Answer in under 5 seconds', points: 15 },
'word_master': { name: '📚 Word Master', desc: 'Use 50+ words in word chain', points: 25 },
'trivia_genius': { name: '🧠 Trivia Genius', desc: 'Answer 10 trivia questions correctly', points: 30 },
'social_butterfly': { name: '🦋 Social Butterfly', desc: 'Play with 5+ different people', points: 20 },
'streak_master': { name: '🔥 Streak Master', desc: 'Win 5 games in a row', points: 50 },
'night_owl': { name: '🦉 Night Owl', desc: 'Play games after midnight', points: 15 },
'early_bird': { name: '🐦 Early Bird', desc: 'Play games before 6 AM', points: 15 }
}
// Helper functions
function updatePlayerStats(playerId, gameType, result) {
if (!playerStats.has(playerId)) {
playerStats.set(playerId, {
gamesPlayed: 0,
gamesWon: 0,
totalScore: 0,
achievements: [],
streakCount: 0,
lastPlayed: Date.now(),
favoriteGame: null
})
}
const stats = playerStats.get(playerId)
stats.gamesPlayed++
stats.lastPlayed = Date.now()
if (result === 'win') {
stats.gamesWon++
stats.streakCount++
} else if (result === 'lose') {
stats.streakCount = 0
}
// Update favorite game
const gameCount = stats.gameTypes || {}
gameCount[gameType] = (gameCount[gameType] || 0) + 1
stats.gameTypes = gameCount
stats.favoriteGame = Object.keys(gameCount).reduce((a, b) => gameCount[a] > gameCount[b] ? a : b)
playerStats.set(playerId, stats)
checkAchievements(playerId, gameType, result)
}
function checkAchievements(playerId, gameType, result) {
const stats = playerStats.get(playerId)
const playerAchievements = achievements.get(playerId) || []
// Check for new achievements
if (result === 'win' && stats.gamesWon === 1 && !playerAchievements.includes('first_win')) {
playerAchievements.push('first_win')
stats.totalScore += ACHIEVEMENTS.first_win.points
}
if (stats.streakCount >= 5 && !playerAchievements.includes('streak_master')) {
playerAchievements.push('streak_master')
stats.totalScore += ACHIEVEMENTS.streak_master.points
}
const hour = new Date().getHours()
if (hour >= 0 && hour < 6 && !playerAchievements.includes('early_bird')) {
playerAchievements.push('early_bird')
stats.totalScore += ACHIEVEMENTS.early_bird.points
}
if (hour >= 23 || hour < 2 && !playerAchievements.includes('night_owl')) {
playerAchievements.push('night_owl')
stats.totalScore += ACHIEVEMENTS.night_owl.points
}
achievements.set(playerId, playerAchievements)
playerStats.set(playerId, stats)
}
// Enhanced Word Chain Game
bot(
{
pattern: 'wordchain ?(start|join|end|score|stats|help)?',
desc: 'Enhanced word chain game with achievements and stats',
type: 'game',
},
async (message, match) => {
const gameId = message.jid
const player = message.participant || message.sender
if (match === 'help') {
return await message.send(
`🔗 *WORD CHAIN GAME GUIDE*\n\n` +
`🎯 *How to Play:*\n` +
`• Next word must start with last letter of previous word\n` +
`• No repeating words allowed\n` +
`• English words only (2+ letters)\n` +
`• Be creative and fast!\n\n` +
`🏆 *Scoring:*\n` +
`• +1 point per valid word\n` +
`• +2 bonus for words 6+ letters\n` +
`• +3 bonus for rare words (Q, X, Z)\n\n` +
`💡 *Commands:*\n` +
`• \`.wordchain start\` - Start new game\n` +
`• \`.wordchain join\` - Join active game\n` +
`• \`.wordchain end\` - End current game\n` +
`• \`.wordchain score\` - View leaderboard\n` +
`• \`.wordchain stats\` - Your personal stats\n\n` +
`🏅 *Achievements Available:*\n` +
`• Word Master (50+ words)\n` +
`• Speed Demon (answer in 5s)\n` +
`• First Victory (win first game)`
)
}
if (match === 'stats') {
const stats = playerStats.get(player)
if (!stats) {
return await message.send(`📊 *No stats yet!* Play some games first with \`.wordchain start\``)
}
const winRate = ((stats.gamesWon / stats.gamesPlayed) * 100).toFixed(1)
const playerAchievements = achievements.get(player) || []
return await message.send(
`📊 *Your Word Chain Stats*\n\n` +
`🎮 *Games Played:* ${stats.gamesPlayed}\n` +
`🏆 *Games Won:* ${stats.gamesWon}\n` +
`📈 *Win Rate:* ${winRate}%\n` +
`🔥 *Current Streak:* ${stats.streakCount}\n` +
`⭐ *Total Score:* ${stats.totalScore}\n` +
`🎯 *Favorite Game:* ${stats.favoriteGame || 'None yet'}\n\n` +
`🏅 *Achievements (${playerAchievements.length}/${Object.keys(ACHIEVEMENTS).length}):*\n` +
`${playerAchievements.map(a => ACHIEVEMENTS[a]?.name || a).join('\n') || 'None yet - keep playing!'}`,
{ mentions: [player] }
)
}
if (match === 'start') {
if (activeGames.has(gameId) && activeGames.get(gameId).type === 'wordchain') {
return await message.send(`🔗 *Word chain already active!* Use \`.wordchain join\` to join or \`.wordchain end\` to end it.`)
}
activeGames.set(gameId, {
type: 'wordchain',
lastWord: '',
players: new Set([player]),
words: [],
wordOwners: new Map(),
turn: player,
startTime: Date.now(),
difficulty: 'normal',
bonusWords: []
})
return await message.send(
`🔗 *ENHANCED WORD CHAIN STARTED!*\n\n` +
`🎯 *Rules:*\n` +
`• Next word starts with last letter of previous word\n` +
`• No repeating words\n` +
`• English words only (2+ letters)\n` +
`• Longer words = bonus points!\n\n` +
`👤 *Started by:* @${player.split('@')[0]}\n\n` +
`🏆 *Scoring System:*\n` +
`• Basic word: +1 point\n` +
`• Long word (6+ letters): +2 points\n` +
`• Rare letters (Q,X,Z): +3 points\n\n` +
`💡 *Commands:*\n` +
`• Type any word to play\n` +
`• \`.wordchain join\` - Join game\n` +
`• \`.wordchain end\` - End game\n` +
`• \`.wordchain help\` - Full guide\n\n` +
`🚀 *Start with any word!*`,
{ quoted: message.data, mentions: [player] }
)
}
if (match === 'join') {
const game = activeGames.get(gameId)
if (!game || game.type !== 'wordchain') {
return await message.send('❌ *No word chain game active!*\nStart one with `.wordchain start`')
}
if (game.players.has(player)) {
return await message.send(`✅ *You're already in the game!* Current word: *${game.lastWord || 'None yet'}*`)
}
game.players.add(player)
// Welcome message with current game status
const gameTime = Math.round((Date.now() - game.startTime) / 1000)
return await message.send(
`🎉 *@${player.split('@')[0]} joined the word chain!*\n\n` +
`👥 *Players:* ${game.players.size}\n` +
`🔗 *Last word:* ${game.lastWord || 'None yet - start with any word!'}\n` +
`🎯 *Next letter:* ${game.lastWord ? game.lastWord.slice(-1).toUpperCase() : 'Any letter'}\n` +
`📝 *Words so far:* ${game.words.length}\n` +
`⏱️ *Game time:* ${gameTime}s\n\n` +
`💡 *Tip:* Longer words give bonus points!`,
{ mentions: [player] }
)
}
if (match === 'end') {
const game = activeGames.get(gameId)
if (!game || game.type !== 'wordchain') {
return await message.send('❌ *No active word chain game to end!*')
}
const duration = Math.round((Date.now() - game.startTime) / 1000)
// Calculate final scores and winner
const finalScores = new Map()
game.wordOwners.forEach((owner, word) => {
const currentScore = finalScores.get(owner) || 0
let points = 1
// Bonus points for long words
if (word.length >= 6) points += 2
// Bonus for rare letters
if (/[qxz]/i.test(word)) points += 3
finalScores.set(owner, currentScore + points)
})
// Find winner
let winner = null
let maxScore = 0
finalScores.forEach((score, player) => {
if (score > maxScore) {
maxScore = score
winner = player
}
})
// Update player stats
game.players.forEach(player => {
const result = player === winner ? 'win' : 'lose'
updatePlayerStats(player, 'wordchain', result)
})
activeGames.delete(gameId)
// Create final results message
const scoreList = Array.from(finalScores.entries())
.sort(([,a], [,b]) => b - a)
.map(([player, score], index) => {
const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '🏅'
return `${medal} @${player.split('@')[0]}: ${score} points`
}).join('\n')
return await message.send(
`🏁 *WORD CHAIN GAME ENDED!*\n\n` +
`⏱️ *Duration:* ${Math.floor(duration / 60)}m ${duration % 60}s\n` +
`🔗 *Total words:* ${game.words.length}\n` +
`👥 *Players:* ${game.players.size}\n\n` +
`🏆 *FINAL SCORES:*\n${scoreList}\n\n` +
`${winner ? `🎉 *Winner:* @${winner.split('@')[0]}! 🎉\n\n` : ''}` +
`📝 *Word chain:*\n${game.words.slice(0, 20).join(' → ')}${game.words.length > 20 ? '...' : ''}\n\n` +
`🎮 *Play again with* \`.wordchain start\``,
{ mentions: winner ? [winner] : [] }
)
}
if (match === 'score') {
const scores = gameScores.get(gameId) || {}
if (Object.keys(scores).length === 0) {
return await message.send('📊 *No scores recorded yet!*')
}
const sortedScores = Object.entries(scores)
.sort(([,a], [,b]) => b - a)
.slice(0, 10)
let scoreText = '🏆 *Word Chain Leaderboard:*\n\n'
sortedScores.forEach(([player, score], index) => {
const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '🏅'
scoreText += `${medal} @${player.split('@')[0]}: ${score} points\n`
})
return await message.send(scoreText, {
mentions: sortedScores.map(([player]) => player)
})
}
// Default - show game status or instructions
const game = activeGames.get(gameId)
if (!game || game.type !== 'wordchain') {
return await message.send(
`🔗 *Word Chain Game*\n\n` +
`🎯 *How to play:*\n` +
`• Start: \`.wordchain start\`\n` +
`• Join: \`.wordchain join\`\n` +
`• End: \`.wordchain end\`\n` +
`• Scores: \`.wordchain score\`\n\n` +
`📝 *Rules:*\n` +
`• Next word starts with last letter\n` +
`• No repeating words\n` +
`• English words only`
)
}
return await message.send(
`🔗 *Active Word Chain Game*\n\n` +
`👥 *Players:* ${game.players.size}\n` +
`🔗 *Last word:* ${game.lastWord || 'None yet'}\n` +
`🎯 *Next letter:* ${game.lastWord ? game.lastWord.slice(-1).toUpperCase() : 'Any'}\n` +
`📝 *Words so far:* ${game.words.length}`
)
}
)
// Enhanced word chain gameplay handler
bot(
{
pattern: '.*',
fromMe: false,
dontAddCommandList: true,
},
async (message, match) => {
const gameId = message.jid
const player = message.participant || message.sender
const game = activeGames.get(gameId)
if (!game || game.type !== 'wordchain') return
if (!game.players.has(player)) return
const word = match.trim().toLowerCase()
// Enhanced word validation
if (!/^[a-z]+$/.test(word) || word.length < 2) return
// Check if word was already used
if (game.words.includes(word)) {
return await message.send(
`❌ *"${word.toUpperCase()}" was already used!*\n\n` +
`🔗 *Last word:* ${game.lastWord}\n` +
`🎯 *Need word starting with:* ${game.lastWord.slice(-1).toUpperCase()}\n` +
`📝 *Words so far:* ${game.words.length}\n\n` +
`💡 *Tip:* Try a different word starting with "${game.lastWord.slice(-1).toUpperCase()}"`,
{ quoted: message.data }
)
}
// Check if word starts with correct letter
if (game.lastWord && word[0] !== game.lastWord.slice(-1).toLowerCase()) {
return await message.send(
`❌ *"${word.toUpperCase()}" doesn't start with "${game.lastWord.slice(-1).toUpperCase()}"!*\n\n` +
`🔗 *Last word:* ${game.lastWord}\n` +
`🎯 *Need word starting with:* ${game.lastWord.slice(-1).toUpperCase()}\n` +
`📝 *Total words:* ${game.words.length}\n\n` +
`💡 *Examples:* ${generateWordSuggestions(game.lastWord.slice(-1).toLowerCase())}`,
{ quoted: message.data }
)
}
// Calculate points for this word
let points = 1
let bonusText = ''
// Length bonus
if (word.length >= 6) {
points += 2
bonusText += ' +2 (long word)'
}
// Rare letter bonus
if (/[qxz]/i.test(word)) {
points += 3
bonusText += ' +3 (rare letters)'
}
// Speed bonus (if answered within 10 seconds of last word)
const timeSinceLastWord = Date.now() - (game.lastWordTime || game.startTime)
if (timeSinceLastWord < 10000) {
points += 1
bonusText += ' +1 (speed)'
}
// Valid word! Add to game
game.lastWord = word
game.lastWordTime = Date.now()
game.words.push(word)
game.wordOwners.set(word, player)
game.turn = player
// Update player score
const scores = gameScores.get(gameId) || {}
scores[player] = (scores[player] || 0) + points
gameScores.set(gameId, scores)
// Check for achievements
if (timeSinceLastWord < 5000) {
const playerAchievements = achievements.get(player) || []
if (!playerAchievements.includes('speed_demon')) {
playerAchievements.push('speed_demon')
achievements.set(player, playerAchievements)
bonusText += ' 🏆 SPEED DEMON!'
}
}
// Generate next letter suggestions
const nextLetter = word.slice(-1).toUpperCase()
const suggestions = generateWordSuggestions(word.slice(-1).toLowerCase())
await message.send(
`✅ *"${word.toUpperCase()}" accepted!*\n\n` +
`👤 *Player:* @${player.split('@')[0]}\n` +
`💰 *Points earned:* ${points}${bonusText}\n` +
`📊 *Your total:* ${scores[player]} points\n` +
`🎯 *Next letter:* ${nextLetter}\n` +
`📝 *Word count:* ${game.words.length}\n\n` +
`💡 *Suggestions:* ${suggestions}`,
{ mentions: [player] }
)
// Auto-end game after 50 words or 10 minutes
if (game.words.length >= 50 || (Date.now() - game.startTime) > 600000) {
setTimeout(async () => {
if (activeGames.has(gameId)) {
await message.send(`⏰ *Game auto-ending!* Use \`.wordchain end\` to see final results.`)
}
}, 5000)
}
}
)
// Helper function to generate word suggestions
function generateWordSuggestions(letter) {
const suggestions = {
'a': ['apple', 'amazing', 'adventure'],
'b': ['beautiful', 'butterfly', 'brilliant'],
'c': ['creative', 'challenge', 'celebration'],
'd': ['delicious', 'diamond', 'discovery'],
'e': ['excellent', 'elephant', 'exciting'],
'f': ['fantastic', 'friendship', 'freedom'],
'g': ['gorgeous', 'galaxy', 'grateful'],
'h': ['happiness', 'harmony', 'horizon'],
'i': ['incredible', 'imagination', 'inspiring'],
'j': ['joyful', 'journey', 'justice'],
'k': ['kindness', 'knowledge', 'kingdom'],
'l': ['lovely', 'laughter', 'lightning'],
'm': ['magical', 'mystery', 'magnificent'],
'n': ['natural', 'notebook', 'nutrition'],
'o': ['outstanding', 'opportunity', 'optimistic'],
'p': ['perfect', 'paradise', 'powerful'],
'q': ['quality', 'question', 'quantum'],
'r': ['rainbow', 'remarkable', 'revolution'],
's': ['spectacular', 'sunshine', 'symphony'],
't': ['tremendous', 'treasure', 'triumph'],
'u': ['unique', 'universe', 'unlimited'],
'v': ['victory', 'valuable', 'vibrant'],
'w': ['wonderful', 'wisdom', 'waterfall'],
'x': ['xenial', 'xerox', 'xylophone'],
'y': ['youthful', 'yesterday', 'yearning'],
'z': ['zealous', 'zenith', 'zeppelin']
}
const wordList = suggestions[letter] || ['...']
return wordList.slice(0, 3).join(', ')
}
// Number Guessing Game
bot(
{
pattern: 'guess ?(start|hint|give up|stats)?',
desc: 'Interactive number guessing game with hints',
type: 'game',
},
async (message, match) => {
const gameId = message.jid
const player = message.participant || message.sender
if (match === 'start') {
const difficulty = Math.random() < 0.3 ? 'hard' : Math.random() < 0.6 ? 'medium' : 'easy'
const ranges = {
easy: { min: 1, max: 50, attempts: 8 },
medium: { min: 1, max: 100, attempts: 7 },
hard: { min: 1, max: 200, attempts: 6 }
}
const range = ranges[difficulty]
const secretNumber = Math.floor(Math.random() * (range.max - range.min + 1)) + range.min
activeGames.set(gameId, {
type: 'guess',
secretNumber,
difficulty,
range,
attempts: range.attempts,
maxAttempts: range.attempts,
guesses: [],
startTime: Date.now(),
hints: 0,
player
})
return await message.send(
`🎯 *NUMBER GUESSING GAME STARTED!*\n\n` +
`🎲 *Difficulty:* ${difficulty.toUpperCase()}\n` +
`📊 *Range:* ${range.min} - ${range.max}\n` +
`🎯 *Attempts:* ${range.attempts}\n` +
`👤 *Player:* @${player.split('@')[0]}\n\n` +
`🤔 *I'm thinking of a number between ${range.min} and ${range.max}*\n\n` +
`💡 *Commands:*\n` +
`• Type a number to guess\n` +
`• \`.guess hint\` - Get a hint (-1 attempt)\n` +
`• \`.guess give up\` - Reveal answer\n\n` +
`🚀 *Make your first guess!*`,
{ mentions: [player] }
)
}
if (match === 'hint') {
const game = activeGames.get(gameId)
if (!game || game.type !== 'guess') {
return await message.send('❌ *No guessing game active!* Start one with `.guess start`')
}
if (game.attempts <= 1) {
return await message.send('❌ *Not enough attempts left for a hint!*')
}
game.attempts--
game.hints++
let hint = ''
const secret = game.secretNumber
if (game.hints === 1) {
hint = secret % 2 === 0 ? 'The number is EVEN' : 'The number is ODD'
} else if (game.hints === 2) {
const digits = secret.toString().length
hint = `The number has ${digits} digit${digits > 1 ? 's' : ''}`
} else if (game.hints === 3) {
const sum = secret.toString().split('').reduce((a, b) => parseInt(a) + parseInt(b), 0)
hint = `The sum of its digits is ${sum}`
} else {
const range = Math.floor((game.range.max - game.range.min) / 4)
const quarter = Math.floor((secret - game.range.min) / range)
const quarters = ['first quarter', 'second quarter', 'third quarter', 'fourth quarter']
hint = `The number is in the ${quarters[quarter] || 'last quarter'} of the range`
}
return await message.send(
`💡 *HINT ${game.hints}:* ${hint}\n\n` +
`🎯 *Attempts left:* ${game.attempts}\n` +
`📊 *Range:* ${game.range.min} - ${game.range.max}\n\n` +
`🤔 *What's your guess?*`
)
}
if (match === 'give up') {
const game = activeGames.get(gameId)
if (!game || game.type !== 'guess') {
return await message.send('❌ *No guessing game active!*')
}
updatePlayerStats(player, 'guess', 'lose')
activeGames.delete(gameId)
return await message.send(
`😔 *You gave up!*\n\n` +
`🎯 *The number was:* ${game.secretNumber}\n` +
`📊 *Your guesses:* ${game.guesses.join(', ') || 'None'}\n` +
`⏱️ *Time played:* ${Math.round((Date.now() - game.startTime) / 1000)}s\n\n` +
`🎮 *Try again with* \`.guess start\``,
{ mentions: [player] }
)
}
return await message.send(
`🎯 *NUMBER GUESSING GAME*\n\n` +
`🎮 *How to play:*\n` +
`• \`.guess start\` - Start new game\n` +
`• Type numbers to guess\n` +
`• \`.guess hint\` - Get helpful hints\n` +
`• \`.guess give up\` - Reveal answer\n\n` +
`🏆 *Difficulty levels:*\n` +
`• Easy: 1-50 (8 attempts)\n` +
`• Medium: 1-100 (7 attempts)\n` +
`• Hard: 1-200 (6 attempts)\n\n` +
`🎯 *Start guessing now!*`
)
}
)
// Handle number guesses
bot(
{
pattern: '^[0-9]+$',
fromMe: false,
dontAddCommandList: true,
},
async (message, match) => {
const gameId = message.jid
const player = message.participant || message.sender
const game = activeGames.get(gameId)
if (!game || game.type !== 'guess' || game.player !== player) return
const guess = parseInt(match)
// Validate guess range
if (guess < game.range.min || guess > game.range.max) {
return await message.send(
`❌ *Invalid guess!* Number must be between ${game.range.min} and ${game.range.max}`
)
}
// Check if already guessed
if (game.guesses.includes(guess)) {
return await message.send(`❌ *You already guessed ${guess}!* Try a different number.`)
}
game.guesses.push(guess)
game.attempts--
if (guess === game.secretNumber) {
// Winner!
const timeTaken = Math.round((Date.now() - game.startTime) / 1000)
const score = Math.max(100 - (game.maxAttempts - game.attempts) * 10 - game.hints * 5, 10)
updatePlayerStats(player, 'guess', 'win')
activeGames.delete(gameId)
return await message.send(
`🎉 *CORRECT! YOU WON!* 🎉\n\n` +
`🎯 *The number was:* ${game.secretNumber}\n` +
`🏆 *Score:* ${score} points\n` +
`📊 *Attempts used:* ${game.maxAttempts - game.attempts}/${game.maxAttempts}\n` +
`💡 *Hints used:* ${game.hints}\n` +
`⏱️ *Time:* ${timeTaken}s\n` +
`🎲 *Difficulty:* ${game.difficulty}\n\n` +
`🎮 *Play again with* \`.guess start\``,
{ mentions: [player] }
)
} else if (game.attempts <= 0) {
// Game over
updatePlayerStats(player, 'guess', 'lose')
activeGames.delete(gameId)
return await message.send(
`💥 *GAME OVER!*\n\n` +
`🎯 *The number was:* ${game.secretNumber}\n` +
`📊 *Your guesses:* ${game.guesses.join(', ')}\n` +
`⏱️ *Time played:* ${Math.round((Date.now() - game.startTime) / 1000)}s\n\n` +
`🎮 *Try again with* \`.guess start\``,
{ mentions: [player] }
)
} else {
// Give feedback
const diff = Math.abs(guess - game.secretNumber)
let feedback = ''
if (diff <= 2) feedback = '🔥 VERY HOT!'
else if (diff <= 5) feedback = '♨️ Hot!'
else if (diff <= 10) feedback = '🌡️ Warm'
else if (diff <= 20) feedback = '❄️ Cold'
else feedback = '🧊 Very Cold!'
const direction = guess > game.secretNumber ? '📉 Too HIGH!' : '📈 Too LOW!'
return await message.send(
`${direction} ${feedback}\n\n` +
`🎯 *Your guess:* ${guess}\n` +
`🎯 *Attempts left:* ${game.attempts}\n` +
`📊 *Previous guesses:* ${game.guesses.slice(0, -1).join(', ') || 'None'}\n\n` +
`💡 *Need help?* Use \`.guess hint\`\n` +
`🤔 *Keep guessing!*`
)
}
}
)
// Enhanced Trivia Game
bot(
{
pattern: 'trivia ?(start|answer|score|categories|stats)?',
desc: 'Enhanced trivia quiz game with categories and achievements',
type: 'game',
},
async (message, match) => {
const gameId = message.jid
const player = message.participant || message.sender
// Trivia questions database
const triviaQuestions = [
{
question: "What is the capital of France?",
options: ["London", "Berlin", "Paris", "Madrid"],
correct: 2,
category: "Geography"
},
{
question: "Which planet is known as the Red Planet?",
options: ["Venus", "Mars", "Jupiter", "Saturn"],
correct: 1,
category: "Science"
},
{
question: "Who painted the Mona Lisa?",
options: ["Van Gogh", "Picasso", "Da Vinci", "Monet"],
correct: 2,
category: "Art"
},
{
question: "What is the largest mammal in the world?",
options: ["Elephant", "Blue Whale", "Giraffe", "Hippo"],
correct: 1,
category: "Nature"
},
{
question: "In which year did World War II end?",
options: ["1944", "1945", "1946", "1947"],
correct: 1,
category: "History"
},
{
question: "What is the chemical symbol for gold?",
options: ["Go", "Gd", "Au", "Ag"],
correct: 2,
category: "Science"
},
{
question: "Which country invented pizza?",
options: ["France", "Italy", "Greece", "Spain"],
correct: 1,
category: "Food"
},
{
question: "What is the fastest land animal?",
options: ["Lion", "Cheetah", "Leopard", "Tiger"],
correct: 1,
category: "Nature"
}
]
if (match === 'start') {
const randomQuestion = triviaQuestions[Math.floor(Math.random() * triviaQuestions.length)]
activeGames.set(gameId, {
type: 'trivia',
question: randomQuestion,
players: new Set(),
answers: new Map(),
startTime: Date.now(),
timeLimit: 30000 // 30 seconds
})
const optionsText = randomQuestion.options
.map((option, index) => `${index + 1}. ${option}`)
.join('\n')
setTimeout(async () => {
const game = activeGames.get(gameId)
if (game && game.type === 'trivia') {
await message.send(
`⏰ *Time's up!*\n\n` +
`✅ *Correct answer:* ${randomQuestion.options[randomQuestion.correct]}\n` +
`📚 *Category:* ${randomQuestion.category}\n\n` +
`🎯 *Start another round with* \`.trivia start\``
)
activeGames.delete(gameId)
}
}, 30000)
return await message.send(
`🧠 *TRIVIA TIME!*\n\n` +
`📚 *Category:* ${randomQuestion.category}\n` +
`❓ *Question:*\n${randomQuestion.question}\n\n` +
`📝 *Options:*\n${optionsText}\n\n` +
`⏰ *You have 30 seconds!*\n` +
`💡 *Reply with the number (1-4)*`
)
}
// Handle answer
if (/^[1-4]$/.test(message.text)) {
const game = activeGames.get(gameId)
if (!game || game.type !== 'trivia') return
const answer = parseInt(message.text) - 1
const isCorrect = answer === game.question.correct
if (game.answers.has(player)) {
return await message.send('❌ *You already answered this question!*')
}
game.answers.set(player, { answer, isCorrect, time: Date.now() - game.startTime })
game.players.add(player)
// Update scores
if (isCorrect) {
const scores = gameScores.get(gameId) || {}
const timeBonus = Math.max(1, Math.floor((30000 - (Date.now() - game.startTime)) / 1000))
scores[player] = (scores[player] || 0) + (10 + timeBonus)
gameScores.set(gameId, scores)
await message.send(
`🎉 *CORRECT!* @${player.split('@')[0]}\n\n` +
`⚡ *Speed bonus:* +${timeBonus} points\n` +
`📊 *Total score:* ${scores[player]} points`,
{ mentions: [player] }
)
// End game if someone got it right
activeGames.delete(gameId)
} else {
await message.send(
`❌ *Wrong answer* @${player.split('@')[0]}\n\n` +
`🤔 *Keep trying! Time remaining...*`,
{ mentions: [player] }
)
}
}
if (match === 'score') {
const scores = gameScores.get(gameId) || {}
if (Object.keys(scores).length === 0) {
return await message.send('📊 *No trivia scores yet!*')
}
const sortedScores = Object.entries(scores)
.sort(([,a], [,b]) => b - a)
.slice(0, 10)
let scoreText = '🧠 *Trivia Leaderboard:*\n\n'
sortedScores.forEach(([player, score], index) => {
const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '🏅'
scoreText += `${medal} @${player.split('@')[0]}: ${score} points\n`
})
return await message.send(scoreText, {
mentions: sortedScores.map(([player]) => player)
})
}
return await message.send(
`🧠 *Trivia Game*\n\n` +
`🎯 *Commands:*\n` +
`• \`.trivia start\` - Start new question\n` +
`• \`.trivia score\` - View leaderboard\n\n` +
`📚 *Categories:* Geography, Science, Art, Nature, History, Food\n\n` +
`🏆 *How to play:*\n` +
`• Answer questions by typing 1-4\n` +
`• Faster answers get bonus points\n` +
`• Compete with friends!`
)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment