Category: Projects

https://cdn3d.iconscout.com/3d/premium/thumb/project-task-management-3d-illustration-download-in-png-blend-fbx-gltf-file-formats–development-checklist-list-design-pack-business-illustrations-4496029.png

  • Weather Forecast Application

    Get API Key

    1. Sign up at OpenWeatherMap and create an API key.
    2. Note the API key, as you will need it to make requests.

    Step 2: Install Required Packages

    You’ll need the requests library to make API calls. You can install it using pip:

    bashCopy codepip install requests
    

    Step 3: Create the Weather Application

    Create a file named weather_forecast.py and add the following code:

    pythonCopy codeimport requests
    
    class WeatherForecast:
    
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "http://api.openweathermap.org/data/2.5/weather"
    def get_weather(self, city):
        """Fetch the weather data for the given city."""
        try:
            params = {
                'q': city,
                'appid': self.api_key,
                'units': 'metric'  # Change to 'imperial' for Fahrenheit
            }
            response = requests.get(self.base_url, params=params)
            response.raise_for_status()  # Raise an error for bad responses
            return response.json()
        except requests.exceptions.HTTPError as e:
            print(f"HTTP error: {e}")
            return None
        except Exception as e:
            print(f"Error fetching weather data: {e}")
            return None
    def display_weather(self, city):
        """Display the weather information."""
        weather_data = self.get_weather(city)
        if weather_data:
            city_name = weather_data['name']
            temperature = weather_data['main']['temp']
            description = weather_data['weather'][0]['description']
            humidity = weather_data['main']['humidity']
            wind_speed = weather_data['wind']['speed']
            print(f"\nWeather in {city_name}:")
            print(f"Temperature: {temperature}°C")
            print(f"Description: {description.capitalize()}")
            print(f"Humidity: {humidity}%")
            print(f"Wind Speed: {wind_speed} m/s")
        else:
            print("Could not retrieve weather data.")
    def main():
    api_key = input("Enter your OpenWeatherMap API key: ")
    weather_app = WeatherForecast(api_key)
    while True:
        city = input("\nEnter city name (or 'quit' to exit): ")
        if city.lower() == 'quit':
            print("Exiting the application.")
            break
        weather_app.display_weather(city)
    if __name__ == "__main__":
    main()

    Step 4: Running the Weather Application

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved weather_forecast.py.
    3. Run the script using the command:bashCopy codepython weather_forecast.py

    How It Works

    • API Integration: The application fetches weather data from OpenWeatherMap using an API call based on the city name provided by the user.
    • Data Display: It displays the temperature, weather description, humidity, and wind speed.
    • User Input: The user can enter a city name to get the weather or type quit to exit.
  • Custom Shell

    Create the Shell

    Create a file named custom_shell.py and add the following code:

    pythonCopy codeimport os
    import subprocess
    
    class CustomShell:
    
    def __init__(self):
        self.running = True
    def run(self):
        while self.running:
            try:
                command = input(f"{os.getcwd()}$ ").strip()
                self.process_command(command)
            except KeyboardInterrupt:
                print("\nExiting the shell.")
                self.running = False
    def process_command(self, command):
        if command.lower() in ['exit', 'quit']:
            self.running = False
            return
        elif command.startswith('cd '):
            self.change_directory(command[3:])
        else:
            self.execute_command(command)
    def change_directory(self, path):
        try:
            os.chdir(path)
            print(f"Changed directory to {os.getcwd()}")
        except Exception as e:
            print(f"cd: {e}")
    def execute_command(self, command):
        try:
            # Execute the command
            result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"Error: {e.stderr.strip()}")
    if __name__ == "__main__":
    shell = CustomShell()
    shell.run()

    Step 2: Running the Custom Shell

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved custom_shell.py.
    3. Run the script using the command:bashCopy codepython custom_shell.py

    How It Works

    • Command Input: The shell prompts you to enter a command.
    • Command Processing:
      • Exit Command: You can type exit or quit to exit the shell.
      • Change Directory: Use cd <directory> to change the current working directory.
      • Execute Command: Any other command is executed using the subprocess module.
    • Error Handling: The shell handles errors gracefully, providing feedback if a command fails.

    Example Usage

    1. Change Directory: Type cd path/to/directory to navigate to a different directory.
    2. Execute Commands: Type commands like ls (or dir on Windows) to list files, or echo Hello World to print a message.
    3. Exit: Type exit or quit to close the shell.
  • Image Processing Library

    Install Pillow

    First, make sure you have Pillow installed. You can install it using pip:

    bashCopy codepip install Pillow
    

    Step 2: Create the Image Processing Library

    Create a file named image_processing.py and add the following code:

    pythonCopy codefrom PIL import Image, ImageFilter
    
    class SimpleImageProcessor:
    
    def __init__(self, image_path):
        self.image_path = image_path
        self.image = self.load_image()
    def load_image(self):
        """Load an image from the specified path."""
        try:
            image = Image.open(self.image_path)
            print(f"Loaded image: {self.image_path}")
            return image
        except Exception as e:
            print(f"Error loading image: {e}")
            return None
    def save_image(self, output_path):
        """Save the current image to a specified path."""
        try:
            self.image.save(output_path)
            print(f"Image saved to: {output_path}")
        except Exception as e:
            print(f"Error saving image: {e}")
    def resize_image(self, width, height):
        """Resize the image to the specified width and height."""
        if self.image is not None:
            self.image = self.image.resize((width, height))
            print(f"Resized image to: {width}x{height}")
    def rotate_image(self, angle):
        """Rotate the image by the specified angle."""
        if self.image is not None:
            self.image = self.image.rotate(angle)
            print(f"Rotated image by: {angle} degrees")
    def apply_blur(self):
        """Apply a blur filter to the image."""
        if self.image is not None:
            self.image = self.image.filter(ImageFilter.BLUR)
            print("Applied blur filter to the image.")
    def show_image(self):
        """Display the current image."""
        if self.image is not None:
            self.image.show()
    def main():
    image_path = input("Enter the path of the image file: ")
    processor = SimpleImageProcessor(image_path)
    while True:
        print("\nImage Processing Options:")
        print("1. Resize Image")
        print("2. Rotate Image")
        print("3. Apply Blur")
        print("4. Show Image")
        print("5. Save Image")
        print("6. Exit")
        choice = input("Choose an option (1-6): ")
        if choice == '1':
            width = int(input("Enter new width: "))
            height = int(input("Enter new height: "))
            processor.resize_image(width, height)
        elif choice == '2':
            angle = int(input("Enter rotation angle: "))
            processor.rotate_image(angle)
        elif choice == '3':
            processor.apply_blur()
        elif choice == '4':
            processor.show_image()
        elif choice == '5':
            output_path = input("Enter output file path: ")
            processor.save_image(output_path)
        elif choice == '6':
            print("Exiting the image processor.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    Step 3: Running the Image Processing Library

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved image_processing.py.
    3. Run the script using the command:bashCopy codepython image_processing.py
  • Task Scheduler

    Create the Scheduler

    Create a file named task_scheduler.py and add the following code:

    pythonCopy codeimport time
    import json
    import os
    from threading import Thread
    from datetime import datetime, timedelta
    
    class TaskScheduler:
    
    def __init__(self, filename='tasks.json'):
        self.filename = filename
        self.tasks = self.load_tasks()
        self.running = True
        self.thread = Thread(target=self.run_tasks)
        self.thread.start()
    def load_tasks(self):
        if os.path.exists(self.filename):
            with open(self.filename, 'r') as file:
                return json.load(file)
        return &#91;]
    def save_tasks(self):
        with open(self.filename, 'w') as file:
            json.dump(self.tasks, file)
    def add_task(self, task_name, run_time):
        task = {
            'name': task_name,
            'run_time': run_time
        }
        self.tasks.append(task)
        self.save_tasks()
        print(f"Task '{task_name}' scheduled for {run_time}.")
    def view_tasks(self):
        if not self.tasks:
            print("No tasks scheduled.")
            return
        print("\nScheduled Tasks:")
        for i, task in enumerate(self.tasks, 1):
            print(f"{i}. {task&#91;'name']} - Scheduled for: {task&#91;'run_time']}")
    def run_tasks(self):
        while self.running:
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M')
            for task in self.tasks:
                if task&#91;'run_time'] == current_time:
                    print(f"Running task: {task&#91;'name']}")
                    self.tasks.remove(task)
                    self.save_tasks()
            time.sleep(60)  # Check every minute
    def stop(self):
        self.running = False
        self.thread.join()
    def main():
    scheduler = TaskScheduler()
    
    while True:
        print("\nTask Scheduler")
        print("1. Add Task")
        print("2. View Tasks")
        print("3. Quit")
        
        choice = input("Choose an option (1-3): ")
        if choice == '1':
            task_name = input("Enter the task name: ")
            run_time = input("Enter the run time (YYYY-MM-DD HH:MM): ")
            scheduler.add_task(task_name, run_time)
        elif choice == '2':
            scheduler.view_tasks()
        elif choice == '3':
            scheduler.stop()
            print("Exiting the task scheduler.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    Step 2: Running the Task Scheduler

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved task_scheduler.py.
    3. Run the script using the command:bashCopy codepython task_scheduler.py

    How It Works

    • Task Scheduling: You can add tasks by specifying the name and the time to run (in YYYY-MM-DD HH:MM format). Tasks will be stored in a JSON file (tasks.json).
    • Task Execution: The scheduler checks every minute to see if any tasks need to be executed based on the current time.
    • Threading: A separate thread runs the task-checking loop, allowing the main program to accept user input simultaneously.

    Example Usage

    1. Add a Task: Choose option 1, enter a task name, and specify the time you want it to run.
    2. View Scheduled Tasks: Choose option 2 to see all your scheduled tasks.
    3. Quit: Choose option 3 to exit the scheduler.
  • Text-Based Adventure Game

    Create the Game

    Create a file named adventure_game.py and add the following code:

    pythonCopy codeclass AdventureGame:
    
    def __init__(self):
        self.is_running = True
        self.current_room = 'start'
        self.inventory = &#91;]
    def start(self):
        print("Welcome to the Adventure Game!")
        print("Type 'help' for a list of commands.")
        while self.is_running:
            self.command_handler()
    def command_handler(self):
        command = input(f"\nYou are in {self.current_room}. What do you want to do? ").lower()
        if command == 'help':
            self.show_help()
        elif command == 'look':
            self.look_around()
        elif command.startswith('go '):
            self.move(command&#91;3:])
        elif command.startswith('take '):
            self.take_item(command&#91;5:])
        elif command == 'inventory':
            self.show_inventory()
        elif command == 'quit':
            self.is_running = False
            print("Thank you for playing!")
        else:
            print("Unknown command. Type 'help' for a list of commands.")
    def show_help(self):
        print("\nAvailable commands:")
        print(" - look: Look around your current room.")
        print(" - go &#91;direction]: Move to a different room (north, south, east, west).")
        print(" - take &#91;item]: Take an item from the room.")
        print(" - inventory: Show your inventory.")
        print(" - quit: Exit the game.")
    def look_around(self):
        if self.current_room == 'start':
            print("You are in a dimly lit room. There is a door to the north.")
            print("There is a shiny key on the table.")
        elif self.current_room == 'hallway':
            print("You are in a long hallway. There are doors to the east and west.")
        elif self.current_room == 'treasure_room':
            print("You are in a room filled with gold and jewels! There is a door to the south.")
    def move(self, direction):
        if self.current_room == 'start' and direction == 'north':
            self.current_room = 'hallway'
            print("You move north into the hallway.")
        elif self.current_room == 'hallway' and direction == 'east':
            self.current_room = 'treasure_room'
            print("You move east into the treasure room.")
        elif self.current_room == 'hallway' and direction == 'west':
            self.current_room = 'start'
            print("You move west back to the start room.")
        else:
            print("You can't go that way.")
    def take_item(self, item):
        if self.current_room == 'start' and item == 'key':
            self.inventory.append('key')
            print("You take the shiny key.")
        else:
            print("There's nothing to take here.")
    def show_inventory(self):
        if not self.inventory:
            print("Your inventory is empty.")
        else:
            print("You have: " + ', '.join(self.inventory))
    if __name__ == "__main__":
    game = AdventureGame()
    game.start()

    Step 2: Running the Game

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved adventure_game.py.
    3. Run the script using the command:bashCopy codepython adventure_game.py

    How the Game Works

    • Rooms: The game features three rooms: start, hallway, and treasure_room. You can move between them and interact with items.
    • Commands: Players can use commands such as look, go, take, inventory, and quit.
    • Inventory System: Players can pick up items (like a key) and view their inventory.

    Example Commands

    1. Look around: Type look to see what’s in your current room.
    2. Move: Type go north to move to the hallway.
    3. Take an item: Type take key to pick up the key in the start room.
    4. Check inventory: Type inventory to see what items you have.
  • Personal Finance Tracker

    Create the Finance Tracker

    Create a file named finance_tracker.py and add the following code:

    pythonCopy codeimport json
    import os
    
    class FinanceTracker:
    
    def __init__(self, filename='finance_data.json'):
        self.filename = filename
        self.transactions = self.load_data()
    def load_data(self):
        if os.path.exists(self.filename):
            with open(self.filename, 'r') as file:
                return json.load(file)
        return &#91;]
    def save_data(self):
        with open(self.filename, 'w') as file:
            json.dump(self.transactions, file)
    def add_transaction(self, amount, category, description):
        transaction = {
            'amount': amount,
            'category': category,
            'description': description
        }
        self.transactions.append(transaction)
        self.save_data()
        print("Transaction added!")
    def view_transactions(self):
        if not self.transactions:
            print("No transactions found.")
            return
        print("\nTransactions:")
        for i, transaction in enumerate(self.transactions, 1):
            print(f"{i}. {transaction&#91;'amount']} - {transaction&#91;'category']}: {transaction&#91;'description']}")
    def summarize(self):
        total_income = sum(t&#91;'amount'] for t in self.transactions if t&#91;'amount'] &gt; 0)
        total_expense = sum(t&#91;'amount'] for t in self.transactions if t&#91;'amount'] &lt; 0)
        balance = total_income + total_expense
        print(f"\nTotal Income: {total_income}")
        print(f"Total Expense: {total_expense}")
        print(f"Balance: {balance}")
    def main():
    tracker = FinanceTracker()
    
    while True:
        print("\nPersonal Finance Tracker")
        print("1. Add Transaction")
        print("2. View Transactions")
        print("3. Summarize")
        print("4. Exit")
        
        choice = input("Choose an option (1-4): ")
        if choice == '1':
            amount = float(input("Enter the transaction amount (use negative for expenses): "))
            category = input("Enter the transaction category: ")
            description = input("Enter a description: ")
            tracker.add_transaction(amount, category, description)
        elif choice == '2':
            tracker.view_transactions()
        elif choice == '3':
            tracker.summarize()
        elif choice == '4':
            print("Exiting the tracker.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    Step 2: Running the Finance Tracker

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved finance_tracker.py.
    3. Run the script using the command:bashCopy codepython finance_tracker.py

    Features of the Tracker

    • Add Transaction: You can add income or expense transactions. Income should be entered as a positive amount, while expenses should be negative.
    • View Transactions: Displays all recorded transactions with their details.
    • Summarize: Provides a summary of total income, total expenses, and the overall balance.
    • Data Persistence: Transactions are saved in a JSON file (finance_data.json) so that you can access them even after closing the application.
  • Game Engine

    Install Pygame

    First, make sure you have Python installed. Then, install Pygame by running:

    bashCopy codepip install pygame
    

    Step 2: Create the Game Engine

    Create a file named game_engine.py and add the following code:

    pythonCopy codeimport pygame
    import sys
    
    class GameEngine:
    
    def __init__(self, width, height, title):
        pygame.init()
        self.width = width
        self.height = height
        self.title = title
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption(self.title)
        self.clock = pygame.time.Clock()
        self.running = True
    def run(self):
        while self.running:
            self.handle_events()
            self.update()
            self.draw()
            self.clock.tick(60)  # Limit the frame rate to 60 FPS
        pygame.quit()
        sys.exit()
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
    def update(self):
        """Update game state. Override this in subclasses."""
        pass
    def draw(self):
        """Draw on the screen. Override this in subclasses."""
        self.screen.fill((0, 0, 0))  # Clear screen with black
        pygame.display.flip()
    class MyGame(GameEngine):
    def __init__(self):
        super().__init__(800, 600, "My Game")
    def update(self):
        # Update game logic here
        pass
    def draw(self):
        super().draw()
        # Draw game elements here
        font = pygame.font.Font(None, 36)
        text = font.render("Hello, Pygame!", True, (255, 255, 255))
        self.screen.blit(text, (350, 280))
    if __name__ == "__main__":
    game = MyGame()
    game.run()

    Step 3: Running the Game Engine

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved game_engine.py.
    3. Run the script using the command:bashCopy codepython game_engine.py

    How It Works

    • Game Engine Class: The GameEngine class initializes Pygame, creates a window, and runs the game loop, which handles events, updates game logic, and draws the screen.
    • MyGame Class: This class inherits from GameEngine and can be customized for your specific game. You can override the update and draw methods to implement your game logic and rendering.
    • Event Handling: The handle_events method checks for the quit event to close the game.

    Additional Features to Consider

    This basic structure provides a foundation for your game engine. You can enhance it by adding features like:

    • Sprite Management: Create a class to manage game sprites and animations.
    • Collision Detection: Implement collision detection between game objects.
    • Sound Management: Add sound effects and background music.
    • Input Handling: Extend input handling to manage keyboard and mouse actions.
    • Game States: Create a system to manage different game states (menu, playing, paused, etc.).
  • File Compression Tool

    Setup Your Environment

    Make sure you have Python installed on your machine. You can check this by running:

    bashCopy codepython --version
    

    If you need to install Python, you can download it from python.org.

    Step 2: Create the Compression Tool

    Create a file named file_compression_tool.py and add the following code:

    pythonCopy codeimport zipfile
    import os
    
    def compress_file(input_file, output_zip):
    
    """Compress a single file into a ZIP file."""
    with zipfile.ZipFile(output_zip, 'w') as zipf:
        zipf.write(input_file, os.path.basename(input_file))
    print(f"Compressed '{input_file}' into '{output_zip}'.")
    def decompress_file(input_zip, output_dir):
    """Decompress a ZIP file into a specified directory."""
    with zipfile.ZipFile(input_zip, 'r') as zipf:
        zipf.extractall(output_dir)
    print(f"Decompressed '{input_zip}' into '{output_dir}'.")
    def main():
    while True:
        print("\nFile Compression Tool")
        print("1. Compress a file")
        print("2. Decompress a file")
        print("3. Exit")
        
        choice = input("Choose an option (1-3): ")
        if choice == '1':
            input_file = input("Enter the path of the file to compress: ")
            output_zip = input("Enter the name of the output ZIP file: ")
            compress_file(input_file, output_zip)
        elif choice == '2':
            input_zip = input("Enter the path of the ZIP file to decompress: ")
            output_dir = input("Enter the output directory: ")
            decompress_file(input_zip, output_dir)
        elif choice == '3':
            print("Exiting the tool.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    Step 3: Running the Tool

    1. Open your terminal (or command prompt).
    2. Navigate to the directory where you saved file_compression_tool.py.
    3. Run the script using the command:bashCopy codepython file_compression_tool.py

    How It Works

    • Compress a File: When you choose to compress a file, you’ll be prompted to provide the path of the file you want to compress and the name of the output ZIP file. The script will create a ZIP file containing the specified file.
    • Decompress a File: If you choose to decompress a file, you’ll need to specify the path of the ZIP file and the directory where you want to extract the files.

    Example Usage

    1. To compress a file named example.txt into example.zip, you would select option 1, input the file path, and then the desired ZIP file name.
    2. To decompress example.zip into a folder called output, choose option 2, input the ZIP file path, and the output directory.
  • Chat Application

    Backend Setup (Node.js)

    Step 1: Install Node.js and Required Packages

    First, make sure you have Node.js installed. Then, create a new directory for your project and run the following commands to set up your backend:

    bashCopy codemkdir chat-app
    cd chat-app
    npm init -y
    npm install express socket.io
    

    Step 2: Create Server File

    Create a file named server.js and add the following code:

    javascriptCopy codeconst express = require('express');
    const http = require('http');
    const socketIo = require('socket.io');
    
    const app = express();
    const server = http.createServer(app);
    const io = socketIo(server);
    
    app.use(express.static('public'));
    
    io.on('connection', (socket) => {
    
    console.log('New user connected');
    socket.on('chat message', (msg) =&gt; {
        io.emit('chat message', msg);
    });
    socket.on('disconnect', () =&gt; {
        console.log('User disconnected');
    });
    }); const PORT = process.env.PORT || 3000; server.listen(PORT, () => {
    console.log(Server is running on http://localhost:${PORT});
    });

    2. Frontend Setup

    Step 1: Create Frontend Files

    Inside your project directory, create a folder named public and create two files: index.html and style.css.

    Step 2: Create index.html

    Add the following code to index.html:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;link rel="stylesheet" href="style.css"&gt;
    &lt;title&gt;Chat Application&lt;/title&gt;
    </head> <body>
    &lt;div class="chat-container"&gt;
        &lt;ul id="messages"&gt;&lt;/ul&gt;
        &lt;form id="form" action=""&gt;
            &lt;input id="input" autocomplete="off" /&gt;&lt;button&gt;Send&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
    &lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    </body> </html>

    Step 3: Create style.css

    Add some basic styling in style.css:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    } .chat-container {
    width: 400px;
    margin: 50px auto;
    background: white;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    padding: 20px;
    } ul {
    list-style-type: none;
    padding: 0;
    max-height: 300px;
    overflow-y: scroll;
    } li {
    padding: 8px;
    margin-bottom: 5px;
    background: #e1e1e1;
    border-radius: 4px;
    } form {
    display: flex;
    } input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    }

    Step 4: Create script.js

    Add the following code in script.js:

    javascriptCopy codeconst socket = io();
    
    const form = document.getElementById('form');
    const input = document.getElementById('input');
    const messages = document.getElementById('messages');
    
    form.addEventListener('submit', function(e) {
    
    e.preventDefault();
    if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
    }
    }); socket.on('chat message', function(msg) {
    const item = document.createElement('li');
    item.textContent = msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
    });

    3. Running the Application

    Now that you have everything set up, you can run your chat application.

    1. Open your terminal and navigate to your project directory.
    2. Run the server:bashCopy codenode server.js
    3. Open your web browser and go to http://localhost:3000.

    4. Test the Chat Application

    You can open multiple tabs or different browsers to test real-time communication. Messages sent from one tab should appear in the others instantly!

  • Tic-Tac-Toe Game

    A simple console-based Tic-Tac-Toe game.

    cppCopy code#include <iostream>
    using namespace std;
    
    char board[3][3] = { {'1','2','3'},{'4','5','6'},{'7','8','9'} };
    char player = 'X';
    
    void printBoard() {
    
    cout &lt;&lt; endl;
    for (int i = 0; i &lt; 3; i++) {
        for (int j = 0; j &lt; 3; j++) {
            cout &lt;&lt; board&#91;i]&#91;j] &lt;&lt; " ";
        }
        cout &lt;&lt; endl;
    }
    } bool isWinner() {
    for (int i = 0; i &lt; 3; i++) {
        if (board&#91;i]&#91;0] == board&#91;i]&#91;1] &amp;&amp; board&#91;i]&#91;1] == board&#91;i]&#91;2])
            return true;
        if (board&#91;0]&#91;i] == board&#91;1]&#91;i] &amp;&amp; board&#91;1]&#91;i] == board&#91;2]&#91;i])
            return true;
    }
    if (board&#91;0]&#91;0] == board&#91;1]&#91;1] &amp;&amp; board&#91;1]&#91;1] == board&#91;2]&#91;2])
        return true;
    if (board&#91;0]&#91;2] == board&#91;1]&#91;1] &amp;&amp; board&#91;1]&#91;1] == board&#91;2]&#91;0])
        return true;
    return false;
    } int main() {
    int move;
    for (int turns = 0; turns &lt; 9; turns++) {
        printBoard();
        cout &lt;&lt; "Player " &lt;&lt; player &lt;&lt; ", enter your move (1-9): ";
        cin &gt;&gt; move;
        int row = (move - 1) / 3;
        int col = (move - 1) % 3;
        if (move &lt; 1 || move &gt; 9 || board&#91;row]&#91;col] != (move + '0')) {
            cout &lt;&lt; "Invalid move! Try again." &lt;&lt; endl;
            turns--;
            continue;
        }
        board&#91;row]&#91;col] = player;
        if (isWinner()) {
            printBoard();
            cout &lt;&lt; "Player " &lt;&lt; player &lt;&lt; " wins!" &lt;&lt; endl;
            return 0;
        }
        player = (player == 'X') ? 'O' : 'X';
    }
    printBoard();
    cout &lt;&lt; "It's a draw!" &lt;&lt; endl;
    return 0;
    }