Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Реализовать программу на C++ “Игра: очередь в магазине”. В магазин заходит от 5 от 15…

  1. User

    Реализовать программу на C++ “Игра: очередь в магазине”. В магазин заходит от 5 от 15 клиентов. Затем они подходят к кассе и их начинают обслуживать по правилу FIFO со случайной задержкой от 1 секунды до 3 секунд - в это время пробивается от 1 до 15 ед. товаров. Количество клиентов и касс задает игрок, может задать рандомно и может через пользовательский ввод. Реализуйте класс клиента. Реализуйте двусвязный список, который поможет работать с классом клиентов. Реализуйте класс Касса, который обрабатывает клиентов одного за другим по правилам FIFO. Реализуйте игромеханические правила для Кассы: Примеры:

    1. Изменяемое количество касс или “Марина, выйди на кассу!”
    2. Отменить все покупки, которые пытались пробить на кассе и пробивать их заново правило “Галя, отмена!” Важно: Не используй слишком замудрённые строки кода или библиотеки. Напиши так, словно это написал студент 1-ого курса, который только изучает язык C++
  2. Assistant

    Here's a simple C++ program called "Game: Shop Queue" that simulates clients in a store being processed at cash registers. The code includes the features you've requested, written in a straightforward manner suitable for someone learning C++.

    #include <iostream>
    #include <cstdlib> // For rand() and srand()
    #include <ctime>   // For time()
    #include <thread>  // For this_thread::sleep_for
    #include <chrono>  // For chrono::seconds
    #include <vector>  // For std::vector
    
    // Client class representing a customer in the store
    class Client {
    public:
        int id;     // Client ID
        int items;  // Number of items the client has
        Client* next;
        Client* prev;
    
        Client(int id, int items) : id(id), items(items), next(nullptr), prev(nullptr) {}
    };
    
    // Doubly linked list to manage the queue of clients
    class ClientList {
    public:
        Client* head;
        Client* tail;
    
        ClientList() : head(nullptr), tail(nullptr) {}
    
        // Add a client to the end of the list
        void addClient(Client* client) {
            if (!head) {
                head = tail = client;
            } else {
                tail->next = client;
                client->prev = tail;
                tail = client;
            }
        }
    
        // Remove and return the client at the front of the list
        Client* popClient() {
            if (!head) return nullptr;
            Client* client = head;
            head = head->next;
            if (head)
                head->prev = nullptr;
            else
                tail = nullptr;
            client->next = nullptr;
            client->prev = nullptr;
            return client;
        }
    
        // Check if the list is empty
        bool isEmpty() {
            return head == nullptr;
        }
    };
    
    // CashRegister class representing a cash register in the store
    class CashRegister {
    public:
        int id;          // Cash register ID
        bool cancelled;  // Flag to handle "Galia, cancellation!"
    
        CashRegister(int id) : id(id), cancelled(false) {}
    
        // Process a client
        void processClient(Client* client) {
            std::cout << "Cash register " << id << " is processing client " << client->id
                      << " with " << client->items << " items.\n";
    
            int i = 0;
            while (i < client->items) {
                if (cancelled) {
                    std::cout << "Processing cancelled. Restarting scanning for client " << client->id << ".\n";
                    i = 0;           // Restart scanning items
                    cancelled = false;  // Reset the cancelled flag
                }
                int delay = 1 + rand() % 3;  // Random delay between 1 and 3 seconds
                std::cout << "Scanning item " << i + 1 << "/" << client->items
                          << " for client " << client->id << ".\n";
                std::this_thread::sleep_for(std::chrono::seconds(delay));
                i++;
            }
            std::cout << "Finished processing client " << client->id << " at cash register " << id << ".\n";
        }
    
        // Set the cancelled flag to true to trigger cancellation
        void cancelProcessing() {
            cancelled = true;
        }
    };
    
    int main() {
        srand(static_cast<unsigned int>(time(0)));  // Seed the random number generator
    
        int numClients = 0;
        int numRegisters = 0;
        char choice;
    
        // Ask the user if they want to set the numbers manually or randomly
        std::cout << "Do you want to set the number of clients and cash registers manually? (y/n): ";
        std::cin >> choice;
    
        if (choice == 'y' || choice == 'Y') {
            // User input for number of clients and registers
            std::cout << "Enter number of clients (5 to 15): ";
            std::cin >> numClients;
            if (numClients < 5 || numClients > 15) {
                numClients = 5 + rand() % 11;  // Random number between 5 and 15
                std::cout << "Invalid input. Number of clients set to " << numClients << ".\n";
            }
            std::cout << "Enter number of cash registers: ";
            std::cin >> numRegisters;
            if (numRegisters < 1) {
                numRegisters = 1;
                std::cout << "Invalid input. Number of cash registers set to 1.\n";
            }
        } else {
            // Randomly set number of clients and registers
            numClients = 5 + rand() % 11;      // Random number between 5 and 15
            numRegisters = 1 + rand() % 5;     // Random number between 1 and 5
            std::cout << "Randomly set number of clients to " << numClients
                      << " and cash registers to " << numRegisters << ".\n";
        }
    
        // Generate clients with random number of items and add them to the client list
        ClientList clientList;
        for (int i = 0; i < numClients; i++) {
            int items = 1 + rand() % 15;  // Random number of items between 1 and 15
            Client* client = new Client(i + 1, items);
            clientList.addClient(client);
        }
    
        // Create cash registers
        std::vector<CashRegister*> registers;
        for (int i = 0; i < numRegisters; i++) {
            registers.push_back(new CashRegister(i + 1));
        }
    
        // Process clients in FIFO order
        int currentRegister = 0;
        while (!clientList.isEmpty()) {
            Client* client = clientList.popClient();
            // Assign client to a cash register
            CashRegister* reg = registers[currentRegister];
            reg->processClient(client);
    
            // After processing, offer game mechanic options
            char option;
            std::cout << "--------------------------------------\n";
            std::cout << "Enter 'm' to call 'Marina, go to the cash register!' (change number of cash registers).\n";
            std::cout << "Enter 'g' to call 'Galia, cancellation!' (cancel and reprocess the last client).\n";
            std::cout << "Enter any other key to continue to the next client.\n";
            std::cin >> option;
    
            if (option == 'm' || option == 'M') {
                // Change the number of cash registers
                int newRegisters;
                std::cout << "Enter new number of cash registers: ";
                std::cin >> newRegisters;
                if (newRegisters < 1) {
                    newRegisters = 1;
                    std::cout << "Invalid input. Number of cash registers set to 1.\n";
                }
                // Adjust the cash register list
                if (newRegisters > registers.size()) {
                    // Add new cash registers
                    for (int i = registers.size(); i < newRegisters; i++) {
                        registers.push_back(new CashRegister(i + 1));
                    }
                } else if (newRegisters < registers.size()) {
                    // Remove extra cash registers
                    for (int i = registers.size() - 1; i >= newRegisters; i--) {
                        delete registers[i];
                        registers.pop_back();
                    }
                }
                std::cout << "Number of cash registers is now " << registers.size() << ".\n";
            } else if (option == 'g' || option == 'G') {
                // Cancel and reprocess the last client
                std::cout << "'Galia, cancellation!' invoked. Restarting scanning for client " << client->id << ".\n";
                reg->cancelProcessing();
                reg->processClient(client);
            }
    
            // Move to the next cash register
            currentRegister = (currentRegister + 1) % registers.size();
    
            // Clean up the client
            delete client;
        }
    
        // Clean up cash registers
        for (auto reg : registers) {
            delete reg;
        }
    
        std::cout << "All clients have been processed. Thank you!\n";
        return 0;
    }
    

    Explanation:

    • Client Class: Represents a customer with an ID and a number of items. It includes pointers for a doubly linked list implementation.
    • ClientList Class: Manages the queue of clients using a doubly linked list. It provides methods to add and remove clients.
    • CashRegister Class: Represents a cash register that processes clients. It has a method to process a client, simulating the scanning of items with delays. It also includes a mechanism to cancel and restart processing.
    • Main Function:
      • Prompts the user to set the number of clients and cash registers manually or randomly.
      • Generates clients with random numbers of items and adds them to the client list.
      • Processes each client in FIFO order, assigning them to cash registers in a rotating fashion.
      • After each client is processed, the program offers the player the option to:
        • Change the number of cash registers ("Marina, go to the cash register!").
        • Cancel and reprocess the last client's purchases ("Galia, cancellation!").
      • Cleans up dynamically allocated memory before exiting.

    Game Mechanics:

    1. "Marina, go to the cash register!":

      • Allows the player to change the number of cash registers during the game.
      • The program adjusts the number of cash registers accordingly, either adding new ones or removing existing ones.
    2. "Galia, cancellation!":

      • Enables the player to cancel all purchases being processed for the last client and start scanning them again.
      • The cash register's cancelled flag triggers the cancellation, and the client is reprocessed.

    Important Notes:

    • Random delays simulate the time taken to scan each item, ranging from 1 to 3 seconds.
    • The number of items each client has is randomly set between 1 and 15.
    • The program avoids using complex C++ features or libraries, making it suitable for someone new to the language.

    Sample Output:

    When you run the program, it will interactively prompt you and display messages similar to the following:

    Do you want to set the number of clients and cash registers manually? (y/n): n
    Randomly set number of clients to 12 and cash registers to 3.
    Cash register 1 is processing client 1 with 7 items.
    Scanning item 1/7 for client 1.
    Scanning item 2/7 for client 1.
    ...
    Finished processing client 1 at cash register 1.
    --------------------------------------
    Enter 'm' to call 'Marina, go to the cash register!' (change number of cash registers).
    Enter 'g' to call 'Galia, cancellation!' (cancel and reprocess the last client).
    Enter any other key to continue to the next client.
    

    You can then input 'm', 'g', or any other key to continue processing the next client.

    Disclaimer:

    This program is a simplified simulation and is designed for educational purposes to demonstrate basic C++ programming concepts, such as classes, linked lists, and simple control flow structures.