Mystery Game #19
← Back to Games List
// Pattern Matching Game
const validInputs = [
'ABOUT', 'ABOVE', 'ABUSE', 'ACTOR', 'ACUTE', 'ADMIT', 'ADOPT', 'ADULT',
'AFTER', 'AGAIN', 'AGENT', 'AGREE', 'AHEAD', 'ALARM', 'ALBUM', 'ALERT',
'ALIKE', 'ALIVE', 'ALLOW', 'ALONE', 'ALONG', 'ALTER', 'AMONG', 'ANGER',
'ANGLE', 'ANGRY', 'APART', 'APPLE', 'APPLY', 'ARENA', 'ARGUE', 'ARISE',
'ARRAY', 'ASIDE', 'ASSET', 'AUDIO', 'AUDIT', 'AVOID', 'AWARD', 'AWARE'
];
const maxAttempts = 6;
const patternLength = 5;
let targetPattern;
let currentAttempt = 0;
let isActive = true;
let attempts = [];
function initializeGame() {
targetPattern = validInputs[Math.floor(Math.random() * validInputs.length)];
currentAttempt = 0;
attempts = [];
isActive = true;
updateDisplay();
}
function evaluatePattern(input) {
if (!isActive || input.length !== patternLength) return;
if (!validInputs.includes(input)) {
showMessage('Invalid input');
return;
}
const result = new Array(patternLength).fill('incorrect');
const targetChars = targetPattern.split('');
const inputChars = input.split('');
// Check for exact matches
for (let i = 0; i < patternLength; i++) {
if (inputChars[i] === targetChars[i]) {
result[i] = 'correct';
targetChars[i] = null;
inputChars[i] = null;
}
}
// Check for partial matches
for (let i = 0; i < patternLength; i++) {
if (inputChars[i] === null) continue;
const matchIndex = targetChars.indexOf(inputChars[i]);
if (matchIndex !== -1) {
result[i] = 'partial';
targetChars[matchIndex] = null;
}
}
attempts.push({
pattern: input,
result: result
});
currentAttempt++;
if (result.every(r => r === 'correct')) {
isActive = false;
showMessage('Success!');
} else if (currentAttempt >= maxAttempts) {
isActive = false;
showMessage('Game Over! Pattern was: ' + targetPattern);
}
updateDisplay();
}
function updateDisplay() {
const grid = document.getElementById('gameGrid');
grid.innerHTML = '';
// Add previous attempts
attempts.forEach(attempt => {
const row = document.createElement('div');
row.className = 'attempt-row';
for (let i = 0; i < patternLength; i++) {
const cell = document.createElement('div');
cell.className = 'cell ' + attempt.result[i];
cell.textContent = attempt.pattern[i];
row.appendChild(cell);
}
grid.appendChild(row);
});
// Add empty rows for remaining attempts
for (let i = attempts.length; i < maxAttempts; i++) {
const row = document.createElement('div');
row.className = 'attempt-row';
for (let j = 0; j < patternLength; j++) {
const cell = document.createElement('div');
cell.className = 'cell empty';
row.appendChild(cell);
}
grid.appendChild(row);
}
}
function showMessage(msg) {
const messageEl = document.getElementById('message');
messageEl.textContent = msg;
setTimeout(() => messageEl.textContent = '', 2000);
}
document.addEventListener('keydown', (e) => {
if (!isActive) {
if (e.key === 'Enter') {
initializeGame();
}
return;
}
const input = document.getElementById('input');
if (e.key === 'Enter') {
evaluatePattern(input.value.toUpperCase());
input.value = '';
} else if (e.key === 'Backspace') {
input.value = input.value.slice(0, -1);
} else if (e.key.length === 1 && e.key.match(/[a-z]/i)) {
if (input.value.length < patternLength) {
input.value += e.key.toUpperCase();
}
}
});
# Pattern Matching Game Implementation
import pygame
import random
from dataclasses import dataclass
from typing import List, Tuple, Literal
from enum import Enum
class MatchResult(Enum):
INCORRECT = 'incorrect'
PARTIAL = 'partial'
CORRECT = 'correct'
@dataclass
class Attempt:
pattern: str
result: List[MatchResult]
class PatternGame:
def __init__(self):
pygame.init()
# Game settings
self.width = 800
self.height = 600
self.cell_size = 60
self.padding = 10
self.max_attempts = 6
self.pattern_length = 5
# Colors
self.colors = {
'background': (51, 51, 51),
'empty': (80, 80, 80),
'incorrect': (120, 120, 120),
'partial': (181, 159, 59), # Yellow
'correct': (83, 141, 78), # Green
'text': (255, 255, 255)
}
# Valid inputs
self.valid_inputs = [
'ABOUT', 'ABOVE', 'ABUSE', 'ACTOR', 'ACUTE', 'ADMIT', 'ADOPT', 'ADULT',
'AFTER', 'AGAIN', 'AGENT', 'AGREE', 'AHEAD', 'ALARM', 'ALBUM', 'ALERT',
'ALIKE', 'ALIVE', 'ALLOW', 'ALONE', 'ALONG', 'ALTER', 'AMONG', 'ANGER',
'ANGLE', 'ANGRY', 'APART', 'APPLE', 'APPLY', 'ARENA', 'ARGUE', 'ARISE',
'ARRAY', 'ASIDE', 'ASSET', 'AUDIO', 'AUDIT', 'AVOID', 'AWARD', 'AWARE'
]
# Initialize display
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption('Pattern Matching')
self.clock = pygame.time.Clock()
# Game state
self.initialize_game()
def initialize_game(self):
"""Initialize or reset game state"""
self.target_pattern = random.choice(self.valid_inputs)
self.current_attempt = 0
self.attempts: List[Attempt] = []
self.is_active = True
self.current_input = ""
self.message = ""
self.message_timer = 0
def evaluate_pattern(self, input_pattern: str) -> None:
"""Evaluate input pattern against target"""
if not self.is_active or len(input_pattern) != self.pattern_length:
return
if input_pattern not in self.valid_inputs:
self.show_message('Invalid input')
return
result = [MatchResult.INCORRECT] * self.pattern_length
target_chars = list(self.target_pattern)
input_chars = list(input_pattern)
# Check for exact matches
for i in range(self.pattern_length):
if input_chars[i] == target_chars[i]:
result[i] = MatchResult.CORRECT
target_chars[i] = None
input_chars[i] = None
# Check for partial matches
for i in range(self.pattern_length):
if input_chars[i] is None:
continue
try:
match_index = target_chars.index(input_chars[i])
result[i] = MatchResult.PARTIAL
target_chars[match_index] = None
except ValueError:
pass
self.attempts.append(Attempt(input_pattern, result))
self.current_attempt += 1
if all(r == MatchResult.CORRECT for r in result):
self.is_active = False
self.show_message('Success!')
elif self.current_attempt >= self.max_attempts:
self.is_active = False
self.show_message(f'Game Over! Pattern was: {self.target_pattern}')
def handle_input(self) -> bool:
"""Handle keyboard input"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.KEYDOWN:
if not self.is_active:
if event.key == pygame.K_RETURN:
self.initialize_game()
return True
if event.key == pygame.K_RETURN:
self.evaluate_pattern(self.current_input)
self.current_input = ""
elif event.key == pygame.K_BACKSPACE:
self.current_input = self.current_input[:-1]
elif event.unicode.isalpha():
if len(self.current_input) < self.pattern_length:
self.current_input += event.unicode.upper()
return True
def show_message(self, msg: str):
"""Show temporary message"""
self.message = msg
self.message_timer = 120 # 2 seconds at 60 FPS
def draw(self):
"""Draw the game state"""
# Clear screen
self.screen.fill(self.colors['background'])
# Calculate grid position
start_x = (self.width - self.pattern_length *
(self.cell_size + self.padding)) // 2
start_y = 100
# Draw attempts grid
for row in range(self.max_attempts):
for col in range(self.pattern_length):
x = start_x + col * (self.cell_size + self.padding)
y = start_y + row * (self.cell_size + self.padding)
if row < len(self.attempts):
# Draw filled cell
color = self.colors[self.attempts[row].result[col].value]
pygame.draw.rect(self.screen, color,
(x, y, self.cell_size, self.cell_size))
# Draw letter
font = pygame.font.Font(None, 48)
text = font.render(self.attempts[row].pattern[col],
True, self.colors['text'])
text_rect = text.get_rect(center=(x + self.cell_size//2,
y + self.cell_size//2))
self.screen.blit(text, text_rect)
else:
# Draw empty cell
pygame.draw.rect(self.screen, self.colors['empty'],
(x, y, self.cell_size, self.cell_size))
# Draw current input
if self.is_active:
font = pygame.font.Font(None, 36)
text = font.render(self.current_input, True, self.colors['text'])
text_rect = text.get_rect(center=(self.width//2, 500))
self.screen.blit(text, text_rect)
# Draw message
if self.message_timer > 0:
font = pygame.font.Font(None, 48)
text = font.render(self.message, True, self.colors['text'])
text_rect = text.get_rect(center=(self.width//2, 50))
self.screen.blit(text, text_rect)
self.message_timer -= 1
pygame.display.flip()
def run(self):
"""Main game loop"""
running = True
while running:
running = self.handle_input()
self.draw()
self.clock.tick(60)
pygame.quit()
if __name__ == '__main__':
game = PatternGame()
game.run()
Play Game