diff --git a/Easy/26_Hangman.py b/Easy/26_Hangman.py new file mode 100644 index 0000000..c7f364d --- /dev/null +++ b/Easy/26_Hangman.py @@ -0,0 +1,113 @@ +import random + +def choose_word(): + words = ["python", "hangman", "computer", "programming", "algorithm", "variable", "function", "loop", "condition", "string"] + return random.choice(words).upper() + +def display_hangman(tries): + stages = [ + """ + -------- + | | + | O + | \\|/ + | | + | / \\ + - + """, + """ + -------- + | | + | O + | \\|/ + | | + | / + - + """, + """ + -------- + | | + | O + | \\|/ + | | + | + - + """, + """ + -------- + | | + | O + | \\| + | | + | + - + """, + """ + -------- + | | + | O + | | + | | + | + - + """, + """ + -------- + | | + | O + | + | + | + - + """, + """ + -------- + | | + | + | + | + | + - + """ + ] + return stages[tries] + +def play_hangman(): + word = choose_word() + word_letters = set(word) + guessed_letters = set() + tries = 6 + + print("Welcome to Hangman!") + print(display_hangman(tries)) + print("_ " * len(word)) + + while tries > 0 and word_letters: + while True: + guess = input("Guess a letter: ").strip().upper() + if len(guess) == 1 and guess.isalpha(): + break + print("Invalid input. Please enter a single alphabetic character.") + + if guess in guessed_letters: + print("You already guessed that letter.") + elif guess in word_letters: + word_letters.remove(guess) + guessed_letters.add(guess) + print("Good guess!") + else: + tries -= 1 + guessed_letters.add(guess) + print("Wrong guess!") + + print(display_hangman(tries)) + word_display = [letter if letter in guessed_letters else "_" for letter in word] + print(" ".join(word_display)) + + if not word_letters: + print(f"Congratulations! You guessed the word: {word}") + else: + print(f"Sorry, you ran out of tries. The word was: {word}") + +if __name__ == "__main__": + play_hangman() \ No newline at end of file diff --git a/Expert/26_Reinforcement_Learning_Game_Agent/agent.py b/Expert/26_Reinforcement_Learning_Game_Agent/agent.py new file mode 100644 index 0000000..d822399 --- /dev/null +++ b/Expert/26_Reinforcement_Learning_Game_Agent/agent.py @@ -0,0 +1,112 @@ +import numpy as np +import pickle +import os + +class QLearningAgent: + def __init__(self, alpha=0.1, gamma=0.9, epsilon=0.1): + self.alpha = alpha # Learning rate + self.gamma = gamma # Discount factor + self.epsilon = epsilon # Exploration rate + self.q_table = {} + self.load_q_table() + + def get_state_key(self, state): + return tuple(state) + + def get_q_value(self, state, action): + state_key = self.get_state_key(state) + if state_key not in self.q_table: + self.q_table[state_key] = np.zeros(9) + return self.q_table[state_key][action] + + def set_q_value(self, state, action, value): + state_key = self.get_state_key(state) + if state_key not in self.q_table: + self.q_table[state_key] = np.zeros(9) + self.q_table[state_key][action] = value + + def choose_action(self, state, available_actions): + if np.random.random() < self.epsilon: + return np.random.choice(available_actions) + else: + q_values = [self.get_q_value(state, action) for action in available_actions] + max_q = max(q_values) + best_actions = [action for action, q in zip(available_actions, q_values) if q == max_q] + return np.random.choice(best_actions) + + def learn(self, state, action, reward, next_state, next_available_actions, done): + current_q = self.get_q_value(state, action) + + if done: + target = reward + else: + next_q_values = [self.get_q_value(next_state, next_action) for next_action in next_available_actions] + max_next_q = max(next_q_values) if next_q_values else 0 + target = reward + self.gamma * max_next_q + + new_q = current_q + self.alpha * (target - current_q) + self.set_q_value(state, action, new_q) + + def save_q_table(self): + with open('q_table.pkl', 'wb') as f: + pickle.dump(self.q_table, f) + print("Q-table saved.") + + def load_q_table(self): + if os.path.exists('q_table.pkl'): + with open('q_table.pkl', 'rb') as f: + self.q_table = pickle.load(f) + print("Q-table loaded.") + else: + print("No saved Q-table found. Starting fresh.") + + def train(self, game, episodes=10000): + print("Training the agent...") + for episode in range(episodes): + state = game.reset() + done = False + + while not done: + available_actions = game.get_available_actions() + action = self.choose_action(state, available_actions) + + next_state, reward, done = game.make_move(action) + next_available_actions = game.get_available_actions() if not done else [] + + self.learn(state, action, reward, next_state, next_available_actions, done) + + state = next_state + + if (episode + 1) % 1000 == 0: + print(f"Episode {episode + 1}/{episodes} completed.") + + self.save_q_table() + print("Training completed!") + + def play(self, game): + state = game.reset() + done = False + + while not done: + available_actions = game.get_available_actions() + action = self.choose_action(state, available_actions) + print(f"Agent plays at position {action}") + + next_state, reward, done = game.make_move(action) + state = next_state + game.print_board() + + if not done: + print("\nYour turn:") + human_action = game.get_human_move() + next_state, reward, done = game.make_move(human_action) + state = next_state + game.print_board() + + game.print_board() + if game.winner == 1: + print("Agent wins!") + elif game.winner == -1: + print("You win!") + else: + print("It's a draw!") \ No newline at end of file diff --git a/Expert/26_Reinforcement_Learning_Game_Agent/game.py b/Expert/26_Reinforcement_Learning_Game_Agent/game.py new file mode 100644 index 0000000..944222a --- /dev/null +++ b/Expert/26_Reinforcement_Learning_Game_Agent/game.py @@ -0,0 +1,71 @@ +import numpy as np + +class TicTacToe: + def __init__(self): + self.board = np.zeros((3, 3), dtype=int) + self.current_player = 1 # 1 for X, -1 for O + self.winner = None + self.game_over = False + + def reset(self): + self.board = np.zeros((3, 3), dtype=int) + self.current_player = 1 + self.winner = None + self.game_over = False + return self.get_state() + + def get_state(self): + return self.board.flatten() + + def get_available_actions(self): + return [i for i in range(9) if self.board[i//3, i%3] == 0] + + def make_move(self, action): + if self.game_over: + return self.get_state(), 0, True + + row, col = action // 3, action % 3 + if self.board[row, col] != 0: + return self.get_state(), -10, True # Invalid move penalty + + self.board[row, col] = self.current_player + + if self.check_winner(): + self.winner = self.current_player + self.game_over = True + return self.get_state(), 1, True + elif len(self.get_available_actions()) == 0: + self.game_over = True + return self.get_state(), 0.5, True # Draw + else: + self.current_player = -self.current_player + return self.get_state(), 0, False + + def check_winner(self): + # Check rows, columns, and diagonals + for i in range(3): + if abs(sum(self.board[i, :])) == 3 or abs(sum(self.board[:, i])) == 3: + return True + if abs(self.board[0, 0] + self.board[1, 1] + self.board[2, 2]) == 3: + return True + if abs(self.board[0, 2] + self.board[1, 1] + self.board[2, 0]) == 3: + return True + return False + + def print_board(self): + symbols = {0: ' ', 1: 'X', -1: 'O'} + for i in range(3): + print(' | '.join(symbols[self.board[i, j]] for j in range(3))) + if i < 2: + print('---------') + + def get_human_move(self): + while True: + try: + move = int(input("Enter your move (0-8): ")) + if move in self.get_available_actions(): + return move + else: + print("Invalid move. Try again.") + except ValueError: + print("Please enter a number between 0-8.") \ No newline at end of file diff --git a/Expert/26_Reinforcement_Learning_Game_Agent/main.py b/Expert/26_Reinforcement_Learning_Game_Agent/main.py new file mode 100644 index 0000000..a2a4b63 --- /dev/null +++ b/Expert/26_Reinforcement_Learning_Game_Agent/main.py @@ -0,0 +1,39 @@ +from game import TicTacToe +from agent import QLearningAgent + +def main(): + game = TicTacToe() + agent = QLearningAgent() + + print("Reinforcement Learning Tic-Tac-Toe Agent") + print("The agent uses Q-learning to play Tic-Tac-Toe against you.") + print() + + while True: + print("Menu:") + print("1. Train the agent") + print("2. Play against the agent") + print("3. Exit") + + choice = input("Enter your choice: ") + + if choice == "1": + episodes = int(input("Enter number of training episodes (default 10000): ") or "10000") + agent.train(game, episodes) + elif choice == "2": + print("You are O, Agent is X. You go second.") + print("Board positions:") + print("0 | 1 | 2") + print("---------") + print("3 | 4 | 5") + print("---------") + print("6 | 7 | 8") + print() + agent.play(game) + elif choice == "3": + break + else: + print("Invalid choice. Please try again.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Expert/26_Reinforcement_Learning_Game_Agent/requirements.txt b/Expert/26_Reinforcement_Learning_Game_Agent/requirements.txt new file mode 100644 index 0000000..37dbd1c --- /dev/null +++ b/Expert/26_Reinforcement_Learning_Game_Agent/requirements.txt @@ -0,0 +1 @@ +numpy==1.24.3 \ No newline at end of file diff --git a/Hard/25_Discord_Bot.py b/Hard/25_Discord_Bot.py new file mode 100644 index 0000000..a88e95f --- /dev/null +++ b/Hard/25_Discord_Bot.py @@ -0,0 +1,88 @@ +import discord +from discord.ext import commands +import random +import datetime + +intents = discord.Intents.default() +intents.message_content = True + +bot = commands.Bot(command_prefix='!', intents=intents) + +@bot.event +async def on_ready(): + print(f'{bot.user} has connected to Discord!') + +@bot.command(name='hello', help='Responds with a greeting') +async def hello(ctx): + await ctx.send(f'Hello {ctx.author.mention}!') + +@bot.command(name='roll', help='Rolls a dice. Usage: !roll [number of sides]') +async def roll(ctx, sides: int = 6): + if sides < 2: + await ctx.send("Number of sides must be at least 2!") + return + result = random.randint(1, sides) + await ctx.send(f'{ctx.author.mention} rolled a {result} on a {sides}-sided die!') + +@bot.command(name='flip', help='Flips a coin') +async def flip(ctx): + result = random.choice(['Heads', 'Tails']) + await ctx.send(f'{ctx.author.mention} flipped {result}!') + +@bot.command(name='time', help='Shows current time') +async def time(ctx): + current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + await ctx.send(f'Current time: {current_time}') + +@bot.command(name='ping', help='Shows bot latency') +async def ping(ctx): + latency = round(bot.latency * 1000) + await ctx.send(f'Pong! Latency: {latency}ms') + +@bot.command(name='quote', help='Provides an inspirational quote') +async def quote(ctx): + quotes = [ + "The only way to do great work is to love what you do. - Steve Jobs", + "Believe you can and you're halfway there. - Theodore Roosevelt", + "The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt", + "You miss 100% of the shots you don't take. - Wayne Gretzky", + "The best way to predict the future is to create it. - Peter Drucker" + ] + quote = random.choice(quotes) + await ctx.send(quote) + +@bot.command(name='serverinfo', help='Shows server information') +async def serverinfo(ctx): + server = ctx.guild + embed = discord.Embed(title=f"{server.name} Info", color=0x00ff00) + embed.add_field(name="Server ID", value=server.id, inline=True) + embed.add_field(name="Member Count", value=server.member_count, inline=True) + embed.add_field(name="Created At", value=server.created_at.strftime("%Y-%m-%d"), inline=True) + embed.set_thumbnail(url=server.icon.url if server.icon else None) + await ctx.send(embed=embed) + +@bot.command(name='userinfo', help='Shows user information') +async def userinfo(ctx, member: discord.Member = None): + if member is None: + member = ctx.author + + embed = discord.Embed(title=f"{member.name}#{member.discriminator}", color=member.color) + embed.add_field(name="ID", value=member.id, inline=True) + embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d"), inline=True) + embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d"), inline=True) + embed.set_thumbnail(url=member.avatar.url if member.avatar else None) + await ctx.send(embed=embed) + +@bot.event +async def on_message(message): + if message.author == bot.user: + return + + # Respond to mentions + if bot.user.mentioned_in(message): + await message.channel.send(f"Hello {message.author.mention}! How can I help you?") + + await bot.process_commands(message) + +# Replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token +bot.run('YOUR_BOT_TOKEN_HERE') \ No newline at end of file diff --git a/Hard/25_Discord_Bot_requirements.txt b/Hard/25_Discord_Bot_requirements.txt new file mode 100644 index 0000000..446ed9b --- /dev/null +++ b/Hard/25_Discord_Bot_requirements.txt @@ -0,0 +1 @@ +discord.py==2.3.2 \ No newline at end of file diff --git a/Hard/26_Machine_Learning_Image_Classifier.py b/Hard/26_Machine_Learning_Image_Classifier.py new file mode 100644 index 0000000..0b29029 --- /dev/null +++ b/Hard/26_Machine_Learning_Image_Classifier.py @@ -0,0 +1,112 @@ +from tensorflow import keras +import numpy as np +from PIL import Image + +class ImageClassifier: + def __init__(self): + self.model = None + self.load_or_train_model() + + def load_or_train_model(self): + try: + self.model = keras.models.load_model('mnist_model.h5') + print("Model loaded from file.") + except: + print("Training new model...") + self.train_model() + + def train_model(self): + # Load MNIST dataset + (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() + + # Preprocess data + x_train = x_train.astype('float32') / 255.0 + x_test = x_test.astype('float32') / 255.0 + x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)) + x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)) + + # Build model + self.model = keras.Sequential([ + keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), + keras.layers.MaxPooling2D((2, 2)), + keras.layers.Conv2D(64, (3, 3), activation='relu'), + keras.layers.MaxPooling2D((2, 2)), + keras.layers.Flatten(), + keras.layers.Dense(64, activation='relu'), + keras.layers.Dense(10, activation='softmax') + ]) + + # Compile model + self.model.compile(optimizer='adam', + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + + # Train model + self.model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test)) + + # Save model + self.model.save('mnist_model.h5') + print("Model trained and saved.") + + def preprocess_image(self, image_path): + # Load and preprocess image + img = Image.open(image_path).convert('L') # Convert to grayscale + img = img.resize((28, 28)) + img_array = np.array(img) + img_array = img_array.astype('float32') / 255.0 + img_array = img_array.reshape((1, 28, 28, 1)) + return img_array + + def classify_image(self, image_path): + if self.model is None: + print("Model not loaded.") + return None + + img_array = self.preprocess_image(image_path) + prediction = self.model.predict(img_array) + predicted_class = np.argmax(prediction) + confidence = np.max(prediction) + + return predicted_class, confidence + + def test_accuracy(self): + if self.model is None: + print("Model not loaded.") + return + + (_, _), (x_test, y_test) = keras.datasets.mnist.load_data() + x_test = x_test.astype('float32') / 255.0 + x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)) + + test_loss, test_acc = self.model.evaluate(x_test, y_test, verbose=2) + print(f"Test accuracy: {test_acc}") + +def main(): + classifier = ImageClassifier() + + print("Image Classifier for Handwritten Digits (MNIST)") + print("Commands:") + print("1. Test model accuracy") + print("2. Classify an image (provide path to 28x28 grayscale image)") + print("3. Exit") + + while True: + choice = input("Enter choice: ") + + if choice == "1": + classifier.test_accuracy() + elif choice == "2": + image_path = input("Enter image path: ") + try: + predicted_class, confidence = classifier.classify_image(image_path) + print(f"Predicted digit: {predicted_class}") + print(f"Confidence: {confidence:.2%}") + except Exception as e: + print(f"Error classifying image: {e}") + elif choice == "3": + break + else: + print("Invalid choice.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Hard/26_Machine_Learning_Image_Classifier_requirements.txt b/Hard/26_Machine_Learning_Image_Classifier_requirements.txt new file mode 100644 index 0000000..998b821 --- /dev/null +++ b/Hard/26_Machine_Learning_Image_Classifier_requirements.txt @@ -0,0 +1,4 @@ +tensorflow==2.15.0 +numpy==1.24.3 +matplotlib==3.7.2 +Pillow==10.0.1 \ No newline at end of file diff --git a/Medium/19_Todo_List_Manager.py b/Medium/19_Todo_List_Manager.py new file mode 100644 index 0000000..edc1b03 --- /dev/null +++ b/Medium/19_Todo_List_Manager.py @@ -0,0 +1,117 @@ +import json +import os +from datetime import datetime + +class TodoList: + def __init__(self, filename="todo_list.json"): + self.filename = filename + self.tasks = self.load_tasks() + + def load_tasks(self): + if os.path.exists(self.filename): + with open(self.filename, 'r') as f: + return json.load(f) + return [] + + def save_tasks(self): + with open(self.filename, 'w') as f: + json.dump(self.tasks, f, indent=2) + + def add_task(self, description, priority="medium"): + task = { + "id": len(self.tasks) + 1, + "description": description, + "priority": priority, + "completed": False, + "created_at": datetime.now().isoformat() + } + self.tasks.append(task) + self.save_tasks() + print(f"Task added: {description}") + + def list_tasks(self, show_completed=False): + if not self.tasks: + print("No tasks found.") + return + + for task in self.tasks: + if not show_completed and task["completed"]: + continue + status = "[✓]" if task["completed"] else "[ ]" + print(f"{task['id']}. {status} {task['description']} (Priority: {task['priority']})") + + def complete_task(self, task_id): + for task in self.tasks: + if task["id"] == task_id: + task["completed"] = True + task["completed_at"] = datetime.now().isoformat() + self.save_tasks() + print(f"Task {task_id} marked as completed.") + return + print(f"Task {task_id} not found.") + + def delete_task(self, task_id): + for i, task in enumerate(self.tasks): + if task["id"] == task_id: + del self.tasks[i] + self.save_tasks() + print(f"Task {task_id} deleted.") + return + print(f"Task {task_id} not found.") + + def search_tasks(self, keyword): + results = [task for task in self.tasks if keyword.lower() in task["description"].lower()] + if results: + for task in results: + status = "[✓]" if task["completed"] else "[ ]" + print(f"{task['id']}. {status} {task['description']} (Priority: {task['priority']})") + else: + print("No tasks found matching the keyword.") + +def main(): + todo = TodoList() + + while True: + print("\nTodo List Manager") + print("1. Add task") + print("2. List tasks") + print("3. Complete task") + print("4. Delete task") + print("5. Search tasks") + print("6. Show all tasks (including completed)") + print("7. Exit") + + choice = input("Choose an option: ") + + if choice == "1": + description = input("Enter task description: ") + priority = input("Enter priority (high/medium/low): ").lower() + if priority not in ["high", "medium", "low"]: + priority = "medium" + todo.add_task(description, priority) + elif choice == "2": + todo.list_tasks() + elif choice == "3": + try: + task_id = int(input("Enter task ID to complete: ")) + todo.complete_task(task_id) + except ValueError: + print("Invalid task ID.") + elif choice == "4": + try: + task_id = int(input("Enter task ID to delete: ")) + todo.delete_task(task_id) + except ValueError: + print("Invalid task ID.") + elif choice == "5": + keyword = input("Enter search keyword: ") + todo.search_tasks(keyword) + elif choice == "6": + todo.list_tasks(show_completed=True) + elif choice == "7": + break + else: + print("Invalid choice. Please try again.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Medium/20_Chess_Game.py b/Medium/20_Chess_Game.py new file mode 100644 index 0000000..741b241 --- /dev/null +++ b/Medium/20_Chess_Game.py @@ -0,0 +1,160 @@ +class ChessBoard: + def __init__(self): + self.board = self.initialize_board() + self.current_player = 'white' + + def initialize_board(self): + board = [[' ' for _ in range(8)] for _ in range(8)] + + # Place pawns + for i in range(8): + board[1][i] = 'P' # White pawns + board[6][i] = 'p' # Black pawns + + # Place other pieces + pieces = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'] + for i, piece in enumerate(pieces): + board[0][i] = piece # White pieces + board[7][i] = piece.lower() # Black pieces + + return board + + def print_board(self): + print(" a b c d e f g h") + print(" +----------------") + for i in range(7, -1, -1): + print(f"{i+1}|", end="") + for j in range(8): + print(f"{self.board[i][j]}|", end="") + print(f"{i+1}") + print(" +----------------") + print(" a b c d e f g h") + + def is_valid_move(self, start, end): + start_row, start_col = self.algebraic_to_coords(start) + end_row, end_col = self.algebraic_to_coords(end) + + if not (0 <= start_row < 8 and 0 <= start_col < 8 and 0 <= end_row < 8 and 0 <= end_col < 8): + return False + + piece = self.board[start_row][start_col] + if piece == ' ': + return False + + # Check if it's the correct player's turn + if self.current_player == 'white' and piece.islower(): + return False + if self.current_player == 'black' and piece.isupper(): + return False + + # Basic move validation (simplified) + if piece.upper() == 'P': # Pawn + return self.is_valid_pawn_move(start_row, start_col, end_row, end_col, piece) + elif piece.upper() == 'R': # Rook + return self.is_valid_rook_move(start_row, start_col, end_row, end_col) + elif piece.upper() == 'N': # Knight + return self.is_valid_knight_move(start_row, start_col, end_row, end_col) + elif piece.upper() == 'B': # Bishop + return self.is_valid_bishop_move(start_row, start_col, end_row, end_col) + elif piece.upper() == 'Q': # Queen + return self.is_valid_queen_move(start_row, start_col, end_row, end_col) + elif piece.upper() == 'K': # King + return self.is_valid_king_move(start_row, start_col, end_row, end_col) + + return False + + def is_valid_pawn_move(self, start_row, start_col, end_row, end_col, piece): + direction = 1 if piece.isupper() else -1 + start_rank = 1 if piece.isupper() else 6 + + # Forward move + if start_col == end_col: + if end_row == start_row + direction and self.board[end_row][end_col] == ' ': + return True + if start_row == start_rank and end_row == start_row + 2 * direction and self.board[end_row][end_col] == ' ' and self.board[start_row + direction][end_col] == ' ': + return True + # Capture + elif abs(start_col - end_col) == 1 and end_row == start_row + direction: + if self.board[end_row][end_col] != ' ': + return True + + return False + + def is_valid_rook_move(self, start_row, start_col, end_row, end_col): + if start_row != end_row and start_col != end_col: + return False + return self.is_path_clear(start_row, start_col, end_row, end_col) + + def is_valid_knight_move(self, start_row, start_col, end_row, end_col): + row_diff = abs(start_row - end_row) + col_diff = abs(start_col - end_col) + return (row_diff == 2 and col_diff == 1) or (row_diff == 1 and col_diff == 2) + + def is_valid_bishop_move(self, start_row, start_col, end_row, end_col): + if abs(start_row - end_row) != abs(start_col - end_col): + return False + return self.is_path_clear(start_row, start_col, end_row, end_col) + + def is_valid_queen_move(self, start_row, start_col, end_row, end_col): + if not (start_row == end_row or start_col == end_col or abs(start_row - end_row) == abs(start_col - end_col)): + return False + return self.is_path_clear(start_row, start_col, end_row, end_col) + + def is_valid_king_move(self, start_row, start_col, end_row, end_col): + return abs(start_row - end_row) <= 1 and abs(start_col - end_col) <= 1 + + def is_path_clear(self, start_row, start_col, end_row, end_col): + row_step = 0 if start_row == end_row else (1 if end_row > start_row else -1) + col_step = 0 if start_col == end_col else (1 if end_col > start_col else -1) + + current_row, current_col = start_row + row_step, start_col + col_step + while current_row != end_row or current_col != end_col: + if self.board[current_row][current_col] != ' ': + return False + current_row += row_step + current_col += col_step + return True + + def make_move(self, start, end): + if not self.is_valid_move(start, end): + return False + + start_row, start_col = self.algebraic_to_coords(start) + end_row, end_col = self.algebraic_to_coords(end) + + self.board[end_row][end_col] = self.board[start_row][start_col] + self.board[start_row][start_col] = ' ' + + self.current_player = 'black' if self.current_player == 'white' else 'white' + return True + + def algebraic_to_coords(self, algebraic): + col = ord(algebraic[0].lower()) - ord('a') + row = int(algebraic[1]) - 1 + return row, col + +def main(): + board = ChessBoard() + + while True: + board.print_board() + print(f"\n{board.current_player.capitalize()}'s turn") + + move = input("Enter move (e.g., e2e4) or 'quit' to exit: ").strip() + + if move.lower() == 'quit': + break + + if len(move) != 4: + print("Invalid move format. Use format like e2e4.") + continue + + start, end = move[:2], move[2:] + + if board.make_move(start, end): + print("Move made successfully.") + else: + print("Invalid move. Try again.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Medium/todo_list.json b/Medium/todo_list.json new file mode 100644 index 0000000..2a130c3 --- /dev/null +++ b/Medium/todo_list.json @@ -0,0 +1,9 @@ +[ + { + "id": 1, + "description": "Buy groceries", + "priority": "high", + "completed": false, + "created_at": "2026-01-31T18:38:55.093118" + } +] \ No newline at end of file diff --git a/Readme.md b/Readme.md index bf04b1b..4c783c8 100644 --- a/Readme.md +++ b/Readme.md @@ -1,6 +1,6 @@ # Awesome Python Project Ideas for All Skill Levels -This repository offers a curated collection of engaging Python project ideas, thoughtfully categorized by difficulty: Beginner (Easy), Intermediate (Medium), and Advanced. Whether you're just starting your Python journey or looking for a challenging endeavor, you'll find inspiration here to enhance your coding skills and build your portfolio. Dive in and start creating! +This repository offers a curated collection of engaging Python project ideas, thoughtfully categorized by difficulty: Beginner (Easy), Intermediate (Medium), Advanced (Hard), and Expert. Whether you're just starting your Python journey or looking for a challenging endeavor, you'll find inspiration here to enhance your coding skills and build your portfolio. Dive in and start creating! --- @@ -24,105 +24,125 @@ Implement the well-known game where the user competes against the computer. This Create a text-based interactive story where the user's decisions dictate the narrative path and outcome. This project focuses on branching logic and user input. +### #5 - Hangman Game + +A word guessing game with ASCII art hangman display. Players guess letters to reveal a hidden word before the hangman is complete. + --- ## Intermediate (Medium) folder These projects involve more complex concepts and libraries, suitable for those with a solid grasp of Python basics. -### #5 - Password Manager +### #6 - Password Manager Build a secure application to store and manage multiple passwords. This involves encryption techniques and file handling for data persistence. **Key Technology:** [Fernet Cryptography Documentation](https://cryptography.io/en/latest/fer/) -### #6 - PIG +### #7 - PIG Develop a two-player dice game with simple rules. This project involves game logic and scorekeeping. -### #7 - Madlibs Generator +### #8 - Madlibs Generator Create a script that takes user input for various parts of speech and inserts them into a template story, generating humorous and unique results. This focuses on string manipulation. -### #8 - Timed Math Challenge +### #9 - Timed Math Challenge Design a program that presents users with math problems of varying difficulty and tracks their response time and accuracy. -### #9 - Slot Machine +### #10 - Slot Machine Simulate a basic slot machine with different symbols and payout rules. This project involves random number generation and conditional logic for determining wins. -### #10 - Turtle Racing +### #11 - Turtle Racing Explore Python's `turtle` graphics library to create a visual race between multiple animated turtles. **Helpful Resource:** [Turtle Graphics Documentation](https://docs.python.org/3/library/turtle.html) -### #11 - WPM Typing Test +### #12 - WPM Typing Test Build a command-line application that tests the user's typing speed and accuracy. This might involve handling user input in real-time. **Useful Resource:** [Curses Library Documentation](https://docs.python.org/3/howto/curses.html) -### #12 - Alarm Clock +### #13 - Alarm Clock Develop a simple alarm clock that allows the user to set an alarm and plays a sound at the specified time. -### #13 - Password Generator +### #14 - Password Generator Create a more robust password generator that allows users to customize password length and include various character types (uppercase, lowercase, numbers, symbols). -### #14 - Shortest Path Finder +### #15 - Shortest Path Finder Implement a pathfinding algorithm like Dijkstra's or A\* to find the shortest route between two points on a grid or graph. -### #15 - NBA Stats & Current Scores +### #16 - NBA Stats & Current Scores Utilize an external API to fetch and display real-time or recent statistics and scores from NBA games. -### #16 - Currency Converter +### #17 - Currency Converter Build a tool that converts amounts between different currencies using a public exchange rate API. **Suggested API:** [Free Currency Converter API](https://free.currencyconverterapi.com/) -### #17 - YouTube Video Downloader +### #18 - YouTube Video Downloader Create a script that allows users to download YouTube videos (be mindful of the platform's terms of service). -### #18 - Automated File Backup +### #19 - Automated File Backup Develop a program that automatically backs up specified files or directories to a designated location at scheduled intervals. +### #20 - Todo List Manager + +A command-line task management application with priorities, search functionality, and persistent storage using JSON. + +### #21 - Chess Game + +A two-player chess game with move validation, board display, and proper game rules implementation. + --- ## Advanced (Hard) folder These projects demand a deeper understanding of Python and often involve more complex algorithms, libraries, or system interactions. -### #19 - Mastermind/4 Color Match +### #22 - Mastermind/4 Color Match Implement the logic for the code-breaking game Mastermind, where the player tries to guess a secret sequence of colors. -### #20 - Aim Trainer +### #23 - Aim Trainer Develop a graphical game that challenges the user's aiming skills, potentially using libraries like Pygame. -### #21 - Advanced Python Scripting +### #24 - Advanced Python Scripting This category encompasses more intricate scripting tasks, such as system automation, network analysis tools, or sophisticated data processing pipelines. -### #22- Ebay Price Tracker +### #25 - Ebay Price Tracker -Create a tool that monitors eBay listings for price changes. This will combine web scraping with data visualization +Create a tool that monitors eBay listings for price changes. This will combine web scraping with data visualization. -### #23- Personal Finance Tracker +### #26 - Personal Finance Tracker Develop an application to track expenses and income. This project will involve database management and user interface design. -### #24- Web Scraper - Build a tool that extracts data from websites. This project will teach you about web requests and data parsing. +### #27 - Web Scraper + +Build a tool that extracts data from websites. This project will teach you about web requests and data parsing. + +### #28 - Discord Bot + +A feature-rich Discord bot with commands for games, utilities, server information, and user management. +### #29 - Machine Learning Image Classifier + +A convolutional neural network that classifies handwritten digits using TensorFlow and the MNIST dataset. --- @@ -130,6 +150,17 @@ Develop an application to track expenses and income. This project will involve d These projects are for the masters of Python. They involve advanced concepts like Artificial Intelligence, complex algorithms, and system-level programming. -### #25 - Self-Driving Car Simulation +### #30 - Self-Driving Car Simulation Create a simulation of a self-driving car using Reinforcement Learning and Computer Vision. This project will require you to build a physics engine, implement a neural network for the car's brain, and train it to navigate a track without crashing. + +### #26 - Reinforcement Learning Game Agent + +A Q-learning agent that learns to play Tic-Tac-Toe through reinforcement learning, with separate game logic, agent implementation, and training/playback interface. + + + + +**Happy Coding! 🚀** + +If you build something amazing with these projects, share it with the community by creating an issue or pull request. Let's learn and grow together!