Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ai-typing.py #1637

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 128 additions & 59 deletions Algorithms and Deep Learning Models/ai-typing-game/ai-typing.py
Original file line number Diff line number Diff line change
@@ -1,68 +1,137 @@
import random
import time
import sys
import os
from typing import List, Dict

# Word lists for different difficulty levels
easy_words = ['cat', 'dog', 'sun', 'book', 'tree', 'car', 'bird']
medium_words = ['elephant', 'giraffe', 'balloon', 'umbrella', 'vacation']
hard_words = ['substitution', 'enlightenment', 'interrogation', 'psychological', 'astronomy']
class TypingGame:
def __init__(self):
self.words: Dict[str, List[str]] = {
'Easy': [
'cat', 'dog', 'run', 'jump', 'book', 'desk', 'lamp', 'fish',
'bird', 'tree', 'house', 'door', 'chair', 'table'
],
'Medium': [
'elephant', 'giraffe', 'computer', 'keyboard', 'mountain',
'butterfly', 'telephone', 'umbrella', 'calendar', 'dictionary'
],
'Hard': [
'extraordinary', 'sophisticated', 'revolutionary', 'parliamentary',
'congratulations', 'archaeological', 'meteorological',
'philosophical', 'unprecedented', 'entrepreneurial'
]
}
self.score = 0
self.round = 1
self.total_rounds = 10
self.accuracy_stats = []
self.time_stats = []

# Function to select a random word based on difficulty
def generate_word(level):
if level == 'Easy':
return random.choice(easy_words)
elif level == 'Medium':
return random.choice(medium_words)
elif level == 'Hard':
return random.choice(hard_words)
def clear_screen(self):
os.system('cls' if os.name == 'nt' else 'clear')

# Function to adjust difficulty based on score
def adjust_difficulty(score):
if score >= 50 and score < 100:
return 'Medium'
elif score >= 100:
return 'Hard'
else:
return 'Easy'
def get_difficulty(self) -> str:
if self.score < 50:
return "Easy"
elif self.score < 100:
return "Medium"
else:
return "Hard"

# Function to run the typing game
def start_game():
score = 0
level = 'Easy'

print("Welcome to the AI-Powered Typing Game!\n")
print("Instructions:")
print("Type the given word correctly to score points.")
print("Difficulty will increase as your score increases.\n")

# Main game loop
for round_num in range(10): # Number of rounds (10 in this example)
print(f"\nRound {round_num + 1}: Difficulty Level - {level}")
word_to_type = generate_word(level)
print(f"Type this word: {word_to_type}")

start_time = time.time() # Start the timer
user_input = input("Your input: ")
def get_word(self, difficulty: str) -> str:
return random.choice(self.words[difficulty])

def calculate_wpm(self, time_taken: float, word_length: int) -> float:
# Calculate words per minute (WPM)
characters_per_word = 5 # Standard measure
words = word_length / characters_per_word
minutes = time_taken / 60
return words / minutes if minutes > 0 else 0

def display_stats(self):
if not self.accuracy_stats:
return

# Check if the user typed the correct word
if user_input.lower() == word_to_type.lower():
time_taken = time.time() - start_time
score += 10 # Increase score for correct input
print(f"Correct! You took {time_taken:.2f} seconds.")
print(f"Your score: {score}")
avg_accuracy = sum(self.accuracy_stats) / len(self.accuracy_stats)
avg_time = sum(self.time_stats) / len(self.time_stats)
avg_wpm = sum(wpm for _, wpm in self.time_stats) / len(self.time_stats)

print("\n=== Game Statistics ===")
print(f"Average Accuracy: {avg_accuracy:.2f}%")
print(f"Average Time per Word: {avg_time:.2f} seconds")
print(f"Average WPM: {avg_wpm:.2f}")

def get_feedback(self) -> str:
if self.score >= 100:
return "🏆 Typing master! You're absolutely amazing!"
elif self.score >= 50:
return "👍 Good job! You're making great progress!"
else:
print("Incorrect! Try harder next time.")

# Adjust the difficulty based on score
level = adjust_difficulty(score)

print("\nGame Over!")
print(f"Your final score: {score}")
if score >= 100:
print("You're a typing master!")
elif score >= 50:
print("Good job! Keep practicing!")
else:
print("Keep trying! You'll get better.")
return "💪 Keep practicing! You'll get better with time!"

def display_progress_bar(self):
progress = (self.round - 1) / self.total_rounds
bar_length = 30
filled = int(bar_length * progress)
bar = '█' * filled + '░' * (bar_length - filled)
print(f"\nProgress: [{bar}] {progress*100:.1f}%")

def run_game(self):
self.clear_screen()
print("╔══════════════════════════════════════╗")
print("║ AI-Powered Typing Game v2.0 ║")
print("╚══════════════════════════════════════╝")
print("\nInstructions: Type the given word correctly to score points.")
print("The difficulty increases as your score improves.")
input("\nPress Enter to start...")

while self.round <= self.total_rounds:
self.clear_screen()
difficulty = self.get_difficulty()
word = self.get_word(difficulty)

self.display_progress_bar()
print(f"\nRound {self.round}/{self.total_rounds}")
print(f"Difficulty Level: {difficulty}")
print(f"Current Score: {self.score}")
print(f"\nType this word: {word}")

start_time = time.time()
try:
user_input = input("Your input: ").strip()
except KeyboardInterrupt:
print("\nGame terminated by user.")
sys.exit()

elapsed_time = time.time() - start_time
wpm = self.calculate_wpm(elapsed_time, len(word))

# Calculate accuracy
accuracy = sum(a == b for a, b in zip(word.lower(), user_input.lower()))
accuracy = (accuracy / len(word)) * 100 if word else 0

if user_input.lower() == word.lower():
self.score += 10
print(f"\n✨ Correct! ✨")
print(f"Time: {elapsed_time:.2f} seconds")
print(f"WPM: {wpm:.2f}")
print(f"Accuracy: {accuracy:.2f}%")
else:
print(f"\n❌ Incorrect! The word was: {word}")
print(f"Accuracy: {accuracy:.2f}%")

self.accuracy_stats.append(accuracy)
self.time_stats.append((elapsed_time, wpm))

self.round += 1
input("\nPress Enter to continue...")

self.clear_screen()
print("\n🎮 Game Over! 🎮")
print(f"Final Score: {self.score}")
print(self.get_feedback())
self.display_stats()

# Run the game
start_game()
if __name__ == "__main__":
game = TypingGame()
game.run_game()
4 changes: 2 additions & 2 deletions NLP/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# NLP Naturla Language Processing
# NLP Natural Language Processing

Natural Language Processing (NLP) is a field of machine learning that focuses on the interaction between computers and humans through natural language. It involves teaching machines to understand, interpret, and generate human language in a way that is both meaningful and useful. NLP combines computational linguistics with statistical, machine learning, and deep learning models to process and analyze large amounts of natural language data.

Expand Down Expand Up @@ -64,4 +64,4 @@ graph TD;
- **CoreNLP**: [CoreNLP](https://stanfordnlp.github.io/CoreNLP/) by Stanford NLP Group is a suite of NLP tools that provide various linguistic analysis tools.
- **Flair**: [Flair](https://github.com/flairNLP/flair) is a simple framework for state-of-the-art NLP, developed by Zalando Research.

These resources and libraries can help you further enhance your NLP projects and stay updated with the latest advancements in the field.
These resources and libraries can help you further enhance your NLP projects and stay updated with the latest advancements in the field.
Loading