C/C++ language Course codes

 1)basic codes 

#include <iostream>
#include <string>
using namespace std;

int main() {
    cout << "Hello World" << endl;

    // Data types
    short sa = 1000;
    cout << "The value of sa is: " << sa << endl;

    short a;
    int b;
    float score = 62.13;

    cout << "The value of score is: " << score << endl;

    // Input
    cout << "Enter the value of a: ";
    cin >> a;

    cout << "Enter the value of b: ";
    cin >> b;

    // Arithmetic
    cout << "a + b = " << a + b << endl;
    cout << "a - b = " << a - b << endl;
    cout << "a * b = " << a * b << endl;
    cout << "a / b = " << a / b << endl;
    cout << "a / b (float) = " << (float)a / b << endl;

    // If-else
    int age;
    cout << "Enter your age: ";
    cin >> age;

    if (age >= 18)
        cout << "You are an adult" << endl;
    else
        cout << "You are a teenager" << endl;

    // Switch
    switch (age) {
        case 18:
            cout << "You are 18" << endl;
            break;
        case 20:
            cout << "You are 20" << endl;
            break;
        default:
            cout << "Age is " << age << endl;
    }

    // While loop
    int index = 0;
    while (index < 5) {
        cout << "While loop index: " << index << endl;
        index++;
    }

    // Do-while
    int j = 0;
    do {
        cout << "Do-while index: " << j << endl;
        j++;
    } while (j < 5);

    // For loop
    for (int i = 0; i < 5; i++) {
        cout << "For loop index: " << i << endl;
    }

    // Arrays
    int arr[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++) {
        cout << "arr[" << i << "] = " << arr[i] << endl;
    }

    // Marks input
    int marks[5];
    for (int i = 0; i < 5; i++) {
        cout << "Enter marks[" << i << "]: ";
        cin >> marks[i];
    }

    // String
    string name = "Krishna";
    cout << "Name: " << name << endl;
    cout << "Length: " << name.length() << endl;
    cout << "Size: " << name.size() << endl;
    cout << "Substring: " << name.substr(0, 5) << endl;

    return 0;
}

2)float int all basics 

#include <iostream>  

#include <string>    
using namespace std;
void myFunction(string fname) {
    cout << fname << " abc" << endl;
}

int main() {

    cout << "Krishna" << endl;
    int x, y, z;
    x = y = z = 50;
    cout << x + y + z << endl;
    const int minutesPerHour = 60;
    cout << minutesPerHour << endl;
    int mynum = 6;
    float myFloatNum = 5.99;
    double myDoubleNum = 9.98;
    char myletter = 'D';
    bool myBoolean = true;
    string mystring = "Hello";
    cout << "float: " << myFloatNum << endl;
    cout << "int: " << mynum << endl;
    cout << "double: " << myDoubleNum << endl;
    cout << "char: " << myletter << endl;
    cout << "bool: " << myBoolean << endl;
    cout << "string: " << mystring << endl;
    string name = "Krishna";
    int roll_no = 38;
    cout << "Name: " << name << endl;
    cout << "Roll No: " << roll_no << endl;

    if (20 > 15) {
        cout << "20 IS GREATER THAN 15" << endl;
    }

    else if (20 < 15) {
        cout << "15 is less than 20" << endl;
    }

    else {
        cout << "Both are equal to each other" << endl;
    }

    float f1 = 35e3;    
    double d1 = 12E6;  

    cout << "f1: " << f1 << endl;
    cout << "d1: " << d1 << endl;

    myFunction("Lion");
    myFunction("Camel");
    myFunction("Elephant");

    for (int i = 0; i < 5; i++){
        cout << i << "\n";
        i++;
    }

    int i= 0;
    while(i<10){
        cout << i << endl;
        i++;
    }
    return 0;
}

3)Tic tac Toe.cpp on P5.js

let board = [
  ['','',''],
  ['','',''],
  ['','','']
];

let players = ['X', 'O'];
let currentPlayer;
let available = [];

function setup() {
  createCanvas(400, 400);
  frameRate(1);

  currentPlayer = floor(random(players.length));

  for (let j = 0; j < 3; j++) {
    for (let i = 0; i < 3; i++) {
      available.push([i, j]);
    }
  }
}

function equals3(a, b, c) {
  return a == b && b == c && a != '';
}

function checkWinner() {
  let winner = null;

  // rows
  for (let i = 0; i < 3; i++) {
    if (equals3(board[i][0], board[i][1], board[i][2])) {
      winner = board[i][0];
    }
  }

  // columns
  for (let i = 0; i < 3; i++) {
    if (equals3(board[0][i], board[1][i], board[2][i])) {
      winner = board[0][i];
    }
  }

  // diagonals
  if (equals3(board[0][0], board[1][1], board[2][2])) {
    winner = board[0][0];
  }

  if (equals3(board[2][0], board[1][1], board[0][2])) {
    winner = board[2][0];
  }

  if (winner == null && available.length == 0) {
    return 'Tie';
  } else {
    return winner;
  }
}

function nextTurn() {
  let index = floor(random(available.length));
  let spot = available.splice(index, 1)[0];
  let i = spot[0];
  let j = spot[1];

  board[j][i] = players[currentPlayer];
  currentPlayer = (currentPlayer + 1) % players.length;
}

function draw() {
  background(255);

  let w = width / 3;
  let h = height / 3;

  strokeWeight(4);
  line(w, 0, w, height);
  line(w * 2, 0, w * 2, height);
  line(0, h, width, h);
  line(0, h * 2, width, h * 2);

  for (let j = 0; j < 3; j++) {
    for (let i = 0; i < 3; i++) {
      let x = w * i + w / 2;
      let y = h * j + h / 2;
      let spot = board[j][i];

      if (spot == 'O') {
        noFill();
        ellipse(x, y, w / 2);
      } else if (spot == 'X') {
        let r = w / 4;
        line(x - r, y - r, x + r, y + r);
        line(x - r, y + r, x + r, y - r);
      }
    }
  }

  let result = checkWinner();
  if (result != null) {
    noLoop();
    createP(result).style('font-size', '32pt');
  } else {
    nextTurn();
  }
}

4)TicTacToe.cpp

#include <iostream>
using namespace std;

char board[3][3] = {
    {'1', '2', '3'},
    {'4', '5', '6'},
    {'7', '8', '9'}
};

char currentPlayer = 'X';

void drawBoard() {
    system("cls");
    cout << "\nTIC TAC TOE (C++)\n\n";

    for (int i = 0; i < 3; i++) {
        cout << " ";
        for (int j = 0; j < 3; j++) {
            cout << board[i][j];
            if (j < 2) cout << " | ";
        }
        cout << "\n";
        if (i < 2) cout << "---|---|---\n";
    }
    cout << endl;
}

bool checkWin() {
    for (int i = 0; i < 3; i++) {
        if (board[i][0] == currentPlayer &&
            board[i][1] == currentPlayer &&
            board[i][2] == currentPlayer)
            return true;

        if (board[0][i] == currentPlayer &&
            board[1][i] == currentPlayer &&
            board[2][i] == currentPlayer)
            return true;
    }

    if (board[0][0] == currentPlayer &&
        board[1][1] == currentPlayer &&
        board[2][2] == currentPlayer)
        return true;

    if (board[0][2] == currentPlayer &&
        board[1][1] == currentPlayer &&
        board[2][0] == currentPlayer)
        return true;

    return false;
}

bool isDraw() {
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            if (board[i][j] != 'X' && board[i][j] != 'O')
                return false;
    return true;
}

void makeMove() {
    int choice;
    cout << "Player " << currentPlayer << ", enter position (1-9): ";
    cin >> choice;

    int row = (choice - 1) / 3;
    int col = (choice - 1) % 3;

    if (choice < 1 || choice > 9 ||
        board[row][col] == 'X' ||
        board[row][col] == 'O') {
        cout << "Invalid move! Try again.\n";
        system("pause");
        makeMove();
    } else {
        board[row][col] = currentPlayer;
    }
}

int main() {
    while (true) {
        drawBoard();
        makeMove();

        if (checkWin()) {
            drawBoard();
            cout << "Player " << currentPlayer << " wins!\n";
            break;
        }

        if (isDraw()) {
            drawBoard();
            cout << "It's a draw!\n";
            break;
        }

        currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
    }

    system("pause");
    return 0;
}

5)Login.cpp

#include <iostream>
#include <fstream>
using namespace std;

class User {
private:
    string username, password, email;
    fstream file;

public:
    void signup();
    void login();
    void forgot();
};

int main() {
    User obj;
    char choice;

    cout << "\n1 - Login";
    cout << "\n2 - Signup";
    cout << "\n3 - Forgot Password";
    cout << "\n4 - Exit";
    cout << "\nEnter your choice: ";
    cin >> choice;
    cin.ignore(); // IMPORTANT

    switch (choice) {
        case '1':
            obj.login();
            break;
        case '2':
            obj.signup();
            break;
        case '3':
            obj.forgot();
            break;
        case '4':
            cout << "Exit";
            break;
        default:
            cout << "Invalid choice";
    }
    return 0;
}

// ---------------- SIGNUP ----------------
void User::signup() {
    cout << "\nEnter Username: ";
    getline(cin, username);
    cout << "Enter Password: ";
    getline(cin, password);
    cout << "Enter Email: ";
    getline(cin, email);

    file.open("records.txt", ios::out | ios::app);
    file << username << " " << password << " " << email << endl;
    file.close();

    cout << "\nAccount created successfully!\n";
}

// ---------------- LOGIN ----------------
void User::login() {
    string u, p, e;
    string searchUser, searchPass;

    cout << "\nEnter Username: ";
    getline(cin, searchUser);
    cout << "Enter Password: ";
    getline(cin, searchPass);

    file.open("records.txt", ios::in);

    bool found = false;
    while (file >> u >> p >> e) {
        if (u == searchUser && p == searchPass) {
            cout << "\nLogin Successful!";
            cout << "\nUsername: " << u;
            cout << "\nEmail: " << e << endl;
            found = true;
            break;
        }
    }

    if (!found) {
        cout << "\nLogin Failed!";
    }

    file.close();
}

// ---------------- FORGOT ----------------
void User::forgot() {
    string searchUser;
    string u, p, e;

    cout << "\nEnter your Username: ";
    getline(cin, searchUser);

    file.open("records.txt", ios::in);

    bool found = false;
    while (file >> u >> p >> e) {
        if (u == searchUser) {
            cout << "\nAccount Found!";
            cout << "\nPassword: " << p;
            cout << "\nEmail: " << e << endl;
            found = true;
            break;
        }
    }

    if (!found) {
        cout << "\nAccount not found!";
    }

    file.close();
}

6)Library-Registration.cpp

#include <iostream>
#include <fstream>
using namespace std;

class Library {
private:
    int bookId, quantity;
    string bookName, author;
    fstream file;

public:
    void menu();
    void addBook();
    void showBooks();
    void searchBook();
    void deleteBook();
    void updateBook();
};

int main() {
    Library obj;
    obj.menu();
    return 0;
}

// ---------------- MENU ----------------
void Library::menu() {
    int choice;
    do {
        cout << "\n======= LIBRARY MANAGEMENT SYSTEM =======\n";
        cout << "1. Show All Books\n";
        cout << "2. Add Book\n";
        cout << "3. Search Book\n";
        cout << "4. Update Book\n";
        cout << "5. Delete Book\n";
        cout << "6. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1: showBooks(); break;
            case 2: addBook(); break;
            case 3: searchBook(); break;
            case 4: updateBook(); break;
            case 5: deleteBook(); break;
            case 6: cout << "Exiting...\n"; break;
            default: cout << "Invalid choice!\n";
        }
    } while (choice != 6);
}

// ---------------- ADD BOOK ----------------
void Library::addBook() {
    cin.ignore();
    cout << "\nEnter Book ID: ";
    cin >> bookId;
    cin.ignore();

    cout << "Enter Book Name: ";
    getline(cin, bookName);

    cout << "Enter Author Name: ";
    getline(cin, author);

    cout << "Enter Quantity: ";
    cin >> quantity;

    file.open("library.txt", ios::out | ios::app);
    file << bookId << " " << bookName << " " << author << " " << quantity << endl;
    file.close();

    cout << "Book added successfully!\n";
}

// ---------------- SHOW BOOKS ----------------
void Library::showBooks() {
    file.open("library.txt", ios::in);
    if (!file) {
        cout << "No books found!\n";
        return;
    }

    cout << "\nID\tBook\tAuthor\tQuantity\n";
    while (file >> bookId >> bookName >> author >> quantity) {
        cout << bookId << "\t" << bookName << "\t" << author << "\t" << quantity << endl;
    }
    file.close();
}

// ---------------- SEARCH BOOK ----------------
void Library::searchBook() {
    int searchId;
    bool found = false;

    cout << "\nEnter Book ID to search: ";
    cin >> searchId;

    file.open("library.txt", ios::in);
    while (file >> bookId >> bookName >> author >> quantity) {
        if (bookId == searchId) {
            cout << "\nBook Found!\n";
            cout << "ID: " << bookId << endl;
            cout << "Name: " << bookName << endl;
            cout << "Author: " << author << endl;
            cout << "Quantity: " << quantity << endl;
            found = true;
            break;
        }
    }

    if (!found)
        cout << "Book not found!\n";

    file.close();
}

// ---------------- DELETE BOOK ----------------
void Library::deleteBook() {
    int deleteId;
    bool found = false;

    cout << "\nEnter Book ID to delete: ";
    cin >> deleteId;

    file.open("library.txt", ios::in);
    fstream temp("temp.txt", ios::out);

    while (file >> bookId >> bookName >> author >> quantity) {
        if (bookId != deleteId) {
            temp << bookId << " " << bookName << " " << author << " " << quantity << endl;
        } else {
            found = true;
        }
    }

    file.close();
    temp.close();
    remove("library.txt");
    rename("temp.txt", "library.txt");

    if (found)
        cout << "Book deleted successfully!\n";
    else
        cout << "Book not found!\n";
}

// ---------------- UPDATE BOOK ----------------
void Library::updateBook() {
    int updateId;
    bool found = false;

    cout << "\nEnter Book ID to update: ";
    cin >> updateId;

    file.open("library.txt", ios::in);
    fstream temp("temp.txt", ios::out);

    while (file >> bookId >> bookName >> author >> quantity) {
        if (bookId == updateId) {
            cout << "Enter new Book Name: ";
            cin.ignore();
            getline(cin, bookName);

            cout << "Enter new Author: ";
            getline(cin, author);

            cout << "Enter new Quantity: ";
            cin >> quantity;

            temp << bookId << " " << bookName << " " << author << " " << quantity << endl;
            found = true;
        } else {
            temp << bookId << " " << bookName << " " << author << " " << quantity << endl;
        }
    }

    file.close();
    temp.close();
    remove("library.txt");
    rename("temp.txt", "library.txt");

    if (found)
        cout << "Book updated successfully!\n";
    else
        cout << "Book not found!\n";
}

7)Student Management System.cpp

#include <iostream>
#include <fstream>
using namespace std;

class Student {
private:
    int roll, age;
    string name, course;
    fstream file;

public:
    void menu();
    void addStudent();
    void displayStudent();
    void updateStudent();
    void deleteStudent();
};

int main() {
    Student s;
    s.menu();
    return 0;
}

// ---------------- MENU ----------------
void Student::menu() {
    int choice;
    do {
        cout << "\n======= STUDENT MANAGEMENT SYSTEM =======\n";
        cout << "1. Add Student Record\n";
        cout << "2. Display Student Records\n";
        cout << "3. Update Student Record\n";
        cout << "4. Delete Student Record\n";
        cout << "5. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1: addStudent(); break;
            case 2: displayStudent(); break;
            case 3: updateStudent(); break;
            case 4: deleteStudent(); break;
            case 5: cout << "Exiting...\n"; break;
            default: cout << "Invalid choice!\n";
        }
    } while (choice != 5);
}

// ---------------- ADD STUDENT ----------------
void Student::addStudent() {
    cin.ignore();
    cout << "\nEnter Roll Number: ";
    cin >> roll;
    cin.ignore();

    cout << "Enter Name: ";
    getline(cin, name);

    cout << "Enter Age: ";
    cin >> age;
    cin.ignore();

    cout << "Enter Course: ";
    getline(cin, course);

    file.open("students.txt", ios::out | ios::app);
    file << roll << " " << name << " " << age << " " << course << endl;
    file.close();

    cout << "Student added successfully!\n";
}

// ---------------- DISPLAY STUDENTS ----------------
void Student::displayStudent() {
    file.open("students.txt", ios::in);
    if (!file) {
        cout << "No student records found!\n";
        return;
    }

    cout << "\nRoll\tName\tAge\tCourse\n";
    while (file >> roll >> name >> age >> course) {
        cout << roll << "\t" << name << "\t" << age << "\t" << course << endl;
    }
    file.close();
}

// ---------------- UPDATE STUDENT ----------------
void Student::updateStudent() {
    int searchRoll;
    bool found = false;

    cout << "\nEnter Roll Number to update: ";
    cin >> searchRoll;

    file.open("students.txt", ios::in);
    fstream temp("temp.txt", ios::out);

    while (file >> roll >> name >> age >> course) {
        if (roll == searchRoll) {
            cout << "Enter New Name: ";
            cin.ignore();
            getline(cin, name);

            cout << "Enter New Age: ";
            cin >> age;
            cin.ignore();

            cout << "Enter New Course: ";
            getline(cin, course);

            temp << roll << " " << name << " " << age << " " << course << endl;
            found = true;
        } else {
            temp << roll << " " << name << " " << age << " " << course << endl;
        }
    }

    file.close();
    temp.close();
    remove("students.txt");
    rename("temp.txt", "students.txt");

    if (found)
        cout << "Student record updated successfully!\n";
    else
        cout << "Student not found!\n";
}

// ---------------- DELETE STUDENT ----------------
void Student::deleteStudent() {
    int searchRoll;
    bool found = false;

    cout << "\nEnter Roll Number to delete: ";
    cin >> searchRoll;

    file.open("students.txt", ios::in);
    fstream temp("temp.txt", ios::out);

    while (file >> roll >> name >> age >> course) {
        if (roll != searchRoll) {
            temp << roll << " " << name << " " << age << " " << course << endl;
        } else {
            found = true;
        }
    }

    file.close();
    temp.close();
    remove("students.txt");
    rename("temp.txt", "students.txt");

    if (found)
        cout << "Student record deleted successfully!\n";
    else
        cout << "Student not found!\n";
}

8) Strong Password.cpp

#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;

// Function to generate random password
string generatePassword(int length, bool useSpecial) {
    string password = "";
    string lower = "abcdefghijklmnopqrstuvwxyz";
    string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string digits = "0123456789";
    string special = "!@#$%^&*()_+-=[]{}|;:,.<>?";

    string characters = lower + upper + digits;
    if (useSpecial) characters += special;

    random_device rd;
    mt19937 generator(rd());
    uniform_int_distribution<int> distribution(0, characters.size() - 1);

    bool hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false;

    while (password.size() < length) {
        char c = characters[distribution(generator)];
        password += c;

        if (lower.find(c) != string::npos) hasLower = true;
        else if (upper.find(c) != string::npos) hasUpper = true;
        else if (digits.find(c) != string::npos) hasDigit = true;
        else if (special.find(c) != string::npos) hasSpecial = true;
    }

    // Ensure at least one of each type if special characters are included
    if (useSpecial) {
        if (!hasLower) password[0] = lower[distribution(generator) % lower.size()];
        if (!hasUpper) password[1 % length] = upper[distribution(generator) % upper.size()];
        if (!hasDigit) password[2 % length] = digits[distribution(generator) % digits.size()];
        if (!hasSpecial) password[3 % length] = special[distribution(generator) % special.size()];
    } else {
        if (!hasLower) password[0] = lower[distribution(generator) % lower.size()];
        if (!hasUpper) password[1 % length] = upper[distribution(generator) % upper.size()];
        if (!hasDigit) password[2 % length] = digits[distribution(generator) % digits.size()];
    }

    return password;
}

// Function to determine password strength
string passwordStrength(const string& pwd) {
    int score = 0;
    for (char c : pwd) {
        if (isdigit(c)) score += 1;
        else if (isupper(c)) score += 2;
        else if (islower(c)) score += 2;
        else score += 3;
    }
    if (score < 10) return "Weak";
    else if (score < 20) return "Medium";
    else return "Strong";
}

int main() {
    int length, count;
    char specialChoice;
    cout << "Enter the length of the password: ";
    cin >> length;
    cout << "Do you want special characters? (y/n): ";
    cin >> specialChoice;
    bool useSpecial = (specialChoice == 'y' || specialChoice == 'Y');

    cout << "How many passwords to generate? ";
    cin >> count;

    cout << "\nGenerated Passwords:\n";
    for (int i = 0; i < count; i++) {
        string pwd = generatePassword(length, useSpecial);
        cout << i + 1 << ": " << pwd << "  | Strength: " << passwordStrength(pwd) << endl;
    }

    return 0;
}

9)Geometry Calculator.cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int choice;
    char cont;

    do {
        cout << "------Area & Surface Area Calculator------" << endl;
        cout << "1 - Area of Circle" << endl;
        cout << "2 - Area of Rectangle" << endl;
        cout << "3 - Area of Triangle" << endl;
        cout << "4 - Area of Square" << endl;
        cout << "5 - Area of Parallelogram" << endl;
        cout << "6 - Area of Trapezoid" << endl;
        cout << "7 - Area of Rhombus" << endl;
        cout << "8 - Area of Cube (Surface Area)" << endl;
        cout << "9 - Area of Cylinder (Surface Area)" << endl;
        cout << "10 - Area of Cone (Surface Area)" << endl;
        cout << "11 - Area of Sphere (Surface Area)" << endl;
        cout << "12 - Area of Hemisphere (Surface Area)" << endl;
        cout << "13 - Area of Rectangular Prism (Surface Area)" << endl;
        cout << "14 - Area of Triangular Prism (Surface Area)" << endl;
        cout << "15 - Exit" << endl;

        cout << "Enter your choice: ";
        cin >> choice;

        switch(choice) {
            case 1: {
                double r;
                cout << "Enter radius of circle: ";
                cin >> r;
                cout << "Area of Circle: " << M_PI * r * r << endl;
                break;
            }
            case 2: {
                double l, w;
                cout << "Enter length and width: ";
                cin >> l >> w;
                cout << "Area of Rectangle: " << l * w << endl;
                break;
            }
            case 3: {
                double b, h;
                cout << "Enter base and height: ";
                cin >> b >> h;
                cout << "Area of Triangle: " << 0.5 * b * h << endl;
                break;
            }
            case 4: {
                double s;
                cout << "Enter side of square: ";
                cin >> s;
                cout << "Area of Square: " << s * s << endl;
                break;
            }
            case 5: {
                double b, h;
                cout << "Enter base and height of parallelogram: ";
                cin >> b >> h;
                cout << "Area of Parallelogram: " << b * h << endl;
                break;
            }
            case 6: {
                double a, b, h;
                cout << "Enter sides a, b and height of trapezoid: ";
                cin >> a >> b >> h;
                cout << "Area of Trapezoid: " << 0.5 * (a + b) * h << endl;
                break;
            }
            case 7: {
                double d1, d2;
                cout << "Enter diagonals of rhombus: ";
                cin >> d1 >> d2;
                cout << "Area of Rhombus: " << 0.5 * d1 * d2 << endl;
                break;
            }
            case 8: {
                double a;
                cout << "Enter side of cube: ";
                cin >> a;
                cout << "Surface Area of Cube: " << 6 * a * a << endl;
                break;
            }
            case 9: {
                double r, h;
                cout << "Enter radius and height of cylinder: ";
                cin >> r >> h;
                cout << "Surface Area of Cylinder: " << 2 * M_PI * r * (r + h) << endl;
                break;
            }
            case 10: {
                double r, h;
                cout << "Enter radius and slant height of cone: ";
                cin >> r >> h;
                cout << "Surface Area of Cone: " << M_PI * r * (r + h) << endl;
                break;
            }
            case 11: {
                double r;
                cout << "Enter radius of sphere: ";
                cin >> r;
                cout << "Surface Area of Sphere: " << 4 * M_PI * r * r << endl;
                break;
            }
            case 12: {
                double r;
                cout << "Enter radius of hemisphere: ";
                cin >> r;
                cout << "Surface Area of Hemisphere: " << 3 * M_PI * r * r << endl;
                break;
            }
            case 13: {
                double l, w, h;
                cout << "Enter length, width and height: ";
                cin >> l >> w >> h;
                cout << "Surface Area of Rectangular Prism: " << 2 * (l*w + w*h + h*l) << endl;
                break;
            }
            case 14: {
                double b, h, l;
                cout << "Enter base, height of triangle and length of prism: ";
                cin >> b >> h >> l;
                cout << "Surface Area of Triangular Prism: " << l * b + 2 * 0.5 * b * h << endl;
                break;
            }
            case 15:
                cout << "Exiting..." << endl;
                return 0;
            default:
                cout << "Invalid Choice" << endl;
        }

        cout << "Do you want to calculate another shape? (y/n): ";
        cin >> cont;
    } while(cont == 'y' || cont == 'Y');

    return 0;
}

10)Bank.cpp

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

class BankAccount {
private:
    long long accountNo;
    string name, fatherName, cnic, phone, email;
    double balance;

public:
    void createAccount() {
        srand(time(0));
        accountNo = 1000000000 + rand() % 9000000000;

        cin.ignore();
        cout << "Enter Your Name: ";
        getline(cin, name);

        cout << "Enter Your Father Name: ";
        getline(cin, fatherName);

        cout << "Enter Your CNIC: ";
        getline(cin, cnic);

        cout << "Enter Your Phone Number: ";
        getline(cin, phone);

        cout << "Enter Your Email: ";
        getline(cin, email);

        cout << "Enter Initial Deposit Amount: ";
        cin >> balance;

        saveToFile();
        cout << "\n----- Account Created Successfully -----\n";
        display();
    }

    void display() {
        cout << "\nAccount Number : " << accountNo;
        cout << "\nName           : " << name;
        cout << "\nFather Name    : " << fatherName;
        cout << "\nCNIC           : " << cnic;
        cout << "\nPhone          : " << phone;
        cout << "\nEmail          : " << email;
        cout << "\nBalance        : ₹" << balance << endl;
    }

    void saveToFile() {
        ofstream file("bank_records.txt", ios::app);
        file << accountNo << "|"
             << name << "|"
             << fatherName << "|"
             << cnic << "|"
             << phone << "|"
             << email << "|"
             << balance << endl;
        file.close();
    }

    static void displayAllAccounts() {
        ifstream file("bank_records.txt");
        if (!file) {
            cout << "No records found.\n";
            return;
        }

        string line;
        while (getline(file, line)) {
            cout << line << endl;
        }
        file.close();
    }

    static void searchAccount(long long searchAccNo) {
        ifstream file("bank_records.txt");
        string line;
        bool found = false;
        while (getline(file, line)) {
            if (line.find(to_string(searchAccNo)) != string::npos) {
                cout << "Account Found:\n" << line << endl;
                found = true;
                break;
            }
        }
        if (!found) cout << "Account not found!\n";
        file.close();
    }

    static void deposit(long long accNo, double amount) {
        fstream file("bank_records.txt", ios::in);
        string line, tempFile;
        bool found = false;

        while (getline(file, line)) {
            if (line.find(to_string(accNo)) != string::npos) {
                found = true;
                size_t pos = line.rfind('|');
                double balance = stod(line.substr(pos + 1));
                balance += amount;
                line = line.substr(0, pos + 1) + to_string(balance);
            }
            tempFile += line + "\n";
        }
        file.close();

        if (found) {
            ofstream out("bank_records.txt");
            out << tempFile;
            out.close();
            cout << "Deposit successful!\n";
        } else {
            cout << "Account not found!\n";
        }
    }
};

int main() {
    BankAccount bank;
    int choice;
    while (true) {
        cout << "\n===== BANK MANAGEMENT SYSTEM =====\n";
        cout << "1. Create Account\n";
        cout << "2. Display All Accounts\n";
        cout << "3. Search Account\n";
        cout << "4. Deposit Money\n";
        cout << "5. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                bank.createAccount();
                break;
            case 2:
                BankAccount::displayAllAccounts();
                break;
            case 3: {
                long long accNo;
                cout << "Enter Account Number to search: ";
                cin >> accNo;
                BankAccount::searchAccount(accNo);
                break;
            }
            case 4: {
                long long accNo;
                double amount;
                cout << "Enter Account Number: ";
                cin >> accNo;
                cout << "Enter Amount to Deposit: ";
                cin >> amount;
                BankAccount::deposit(accNo, amount);
                break;
            }
            case 5:
                cout << "Exiting...\n";
                return 0;
            default:
                cout << "Invalid choice! Try again.\n";
        }
    }
}

11)General-Store.cpp

#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;

struct Product {
    int id;
    string name;
    double price;
    int quantity;
};

class Store {
private:
    vector<Product> inventory;

    void loadInventory() {
        ifstream file("inventory.txt");
        if (!file) return;

        Product p;
        while (file >> p.id >> p.name >> p.price >> p.quantity) {
            inventory.push_back(p);
        }
        file.close();
    }

    void saveInventory() {
        ofstream file("inventory.txt");
        for (auto &p : inventory) {
            file << p.id << " " << p.name << " " << p.price << " " << p.quantity << endl;
        }
        file.close();
    }

public:
    Store() { loadInventory(); }

    void addProduct() {
        Product p;
        cout << "Enter Product ID: ";
        cin >> p.id;
        cin.ignore();
        cout << "Enter Product Name: ";
        getline(cin, p.name);
        cout << "Enter Product Price: ";
        cin >> p.price;
        cout << "Enter Quantity: ";
        cin >> p.quantity;

        inventory.push_back(p);
        saveInventory();
        cout << "Product Added Successfully!\n";
    }

    void displayInventory() {
        cout << left << setw(10) << "ID" << setw(20) << "Name" << setw(10)
             << "Price" << setw(10) << "Quantity" << endl;
        cout << "---------------------------------------------\n";
        for (auto &p : inventory) {
            cout << setw(10) << p.id << setw(20) << p.name << setw(10)
                 << p.price << setw(10) << p.quantity << endl;
        }
    }

    void updateProduct() {
        int id;
        cout << "Enter Product ID to update: ";
        cin >> id;
        bool found = false;
        for (auto &p : inventory) {
            if (p.id == id) {
                found = true;
                cout << "Enter new Name: ";
                cin.ignore();
                getline(cin, p.name);
                cout << "Enter new Price: ";
                cin >> p.price;
                cout << "Enter new Quantity: ";
                cin >> p.quantity;
                cout << "Product Updated Successfully!\n";
                saveInventory();
                break;
            }
        }
        if (!found) cout << "Product not found!\n";
    }

    void deleteProduct() {
        int id;
        cout << "Enter Product ID to delete: ";
        cin >> id;
        bool found = false;
        for (auto it = inventory.begin(); it != inventory.end(); ++it) {
            if (it->id == id) {
                inventory.erase(it);
                cout << "Product Deleted Successfully!\n";
                saveInventory();
                found = true;
                break;
            }
        }
        if (!found) cout << "Product not found!\n";
    }

    void makeSale() {
        int id, qty;
        double total = 0;
        char choice;
        do {
            cout << "Enter Product ID: ";
            cin >> id;
            cout << "Enter Quantity: ";
            cin >> qty;
            bool found = false;
            for (auto &p : inventory) {
                if (p.id == id) {
                    found = true;
                    if (p.quantity >= qty) {
                        total += qty * p.price;
                        p.quantity -= qty;
                        cout << "Added to bill: " << qty << " x " << p.name << endl;
                    } else {
                        cout << "Not enough stock!\n";
                    }
                    break;
                }
            }
            if (!found) cout << "Product not found!\n";
            cout << "Add more products? (y/n): ";
            cin >> choice;
        } while (choice == 'y' || choice == 'Y');

        cout << "\nTotal Bill Amount: ₹" << total << endl;
        saveInventory();
    }
};

int main() {
    Store store;
    int choice;

    do {
        cout << "\n===== GENERAL STORE MANAGEMENT SYSTEM =====\n";
        cout << "1. Add Product\n";
        cout << "2. Display Inventory\n";
        cout << "3. Update Product\n";
        cout << "4. Delete Product\n";
        cout << "5. Make Sale\n";
        cout << "6. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                store.addProduct();
                break;
            case 2:
                store.displayInventory();
                break;
            case 3:
                store.updateProduct();
                break;
            case 4:
                store.deleteProduct();
                break;
            case 5:
                store.makeSale();
                break;
            case 6:
                cout << "Exiting...\n";
                break;
            default:
                cout << "Invalid choice!\n";
        }
    } while (choice != 6);

    return 0;
}

12) Calculator.cpp

#include <iostream>
#include <cmath>
#include <limits>
using namespace std;

// Function to display the menu
void showMenu() {
    cout << "\n===== ADVANCED CALCULATOR =====\n";
    cout << "1. Addition (+)\n";
    cout << "2. Subtraction (-)\n";
    cout << "3. Multiplication (*)\n";
    cout << "4. Division (/)\n";
    cout << "5. Power (x^y)\n";
    cout << "6. Square Root (√x)\n";
    cout << "7. Factorial (n!)\n";
    cout << "8. Sine (sin)\n";
    cout << "9. Cosine (cos)\n";
    cout << "10. Tangent (tan)\n";
    cout << "11. Natural Logarithm (ln)\n";
    cout << "12. Logarithm Base 10 (log10)\n";
    cout << "13. Exit\n";
    cout << "===============================\n";
}

// Function to calculate factorial
long long factorial(int n) {
    if (n < 0) return -1;
    long long fact = 1;
    for (int i = 1; i <= n; i++)
        fact *= i;
    return fact;
}

int main() {
    int choice;
    double num1, num2;
    do {
        showMenu();
        cout << "Enter your choice: ";
        cin >> choice;

        switch(choice) {
            case 1:
                cout << "Enter two numbers: ";
                cin >> num1 >> num2;
                cout << "Result: " << num1 + num2 << endl;
                break;
            case 2:
                cout << "Enter two numbers: ";
                cin >> num1 >> num2;
                cout << "Result: " << num1 - num2 << endl;
                break;
            case 3:
                cout << "Enter two numbers: ";
                cin >> num1 >> num2;
                cout << "Result: " << num1 * num2 << endl;
                break;
            case 4:
                cout << "Enter two numbers: ";
                cin >> num1 >> num2;
                if (num2 != 0)
                    cout << "Result: " << num1 / num2 << endl;
                else
                    cout << "Error: Division by zero!\n";
                break;
            case 5:
                cout << "Enter base and exponent: ";
                cin >> num1 >> num2;
                cout << "Result: " << pow(num1, num2) << endl;
                break;
            case 6:
                cout << "Enter a number: ";
                cin >> num1;
                if (num1 >= 0)
                    cout << "Result: " << sqrt(num1) << endl;
                else
                    cout << "Error: Negative number!\n";
                break;
            case 7:
                cout << "Enter an integer: ";
                cin >> num1;
                if (num1 < 0 || floor(num1) != num1)
                    cout << "Error: Factorial not defined!\n";
                else
                    cout << "Result: " << factorial((int)num1) << endl;
                break;
            case 8:
                cout << "Enter angle in degrees: ";
                cin >> num1;
                cout << "Result: " << sin(num1 * M_PI / 180) << endl;
                break;
            case 9:
                cout << "Enter angle in degrees: ";
                cin >> num1;
                cout << "Result: " << cos(num1 * M_PI / 180) << endl;
                break;
            case 10:
                cout << "Enter angle in degrees: ";
                cin >> num1;
                cout << "Result: " << tan(num1 * M_PI / 180) << endl;
                break;
            case 11:
                cout << "Enter a number: ";
                cin >> num1;
                if (num1 > 0)
                    cout << "Result: " << log(num1) << endl;
                else
                    cout << "Error: Logarithm undefined!\n";
                break;
            case 12:
                cout << "Enter a number: ";
                cin >> num1;
                if (num1 > 0)
                    cout << "Result: " << log10(num1) << endl;
                else
                    cout << "Error: Logarithm undefined!\n";
                break;
            case 13:
                cout << "Exiting calculator...\n";
                break;
            default:
                cout << "Invalid choice! Try again.\n";
        }

    } while(choice != 13);

    return 0;
}

13)SnakeGame.cpp

#include <iostream>
#include <conio.h>   // For _kbhit() and _getch()
#include <windows.h> // For Sleep()
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

bool gameOver;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
vector<pair<int,int>> snake; // Snake body

void Setup() {
    srand(time(0));
    gameOver = false;
    dir = STOP;
    x = width / 2;
    y = height / 2;
    snake.clear();
    snake.push_back({x, y});
    fruitX = rand() % width;
    fruitY = rand() % height;
    score = 0;
}

void Draw() {
    system("cls"); // clear screen

    // Top border
    for(int i = 0; i < width + 2; i++) cout << "#";
    cout << endl;

    for(int i = 0; i < height; i++) {
        for(int j = 0; j < width; j++) {
            if(j == 0) cout << "#"; // left border

            bool printed = false;

            // Print snake
            for(int k = 0; k < snake.size(); k++) {
                if(snake[k].first == j && snake[k].second == i) {
                    cout << "O";
                    printed = true;
                    break;
                }
            }

            // Print fruit
            if(fruitX == j && fruitY == i && !printed) {
                cout << "F";
                printed = true;
            }

            if(!printed) cout << " ";

            if(j == width - 1) cout << "#"; // right border
        }
        cout << endl;
    }

    // Bottom border
    for(int i = 0; i < width + 2; i++) cout << "#";
    cout << endl;

    cout << "Score: " << score << endl;
}

void Input() {
    if (_kbhit()) {
        switch (_getch()) {
            case 'a': if(dir != RIGHT) dir = LEFT; break;
            case 'd': if(dir != LEFT) dir = RIGHT; break;
            case 'w': if(dir != DOWN) dir = UP; break;
            case 's': if(dir != UP) dir = DOWN; break;
            case 'x': gameOver = true; break;
        }
    }
}

void Logic() {
    int prevX = snake[0].first;
    int prevY = snake[0].second;
    int prev2X, prev2Y;

    // Move head
    switch(dir) {
        case LEFT: x--; break;
        case RIGHT: x++; break;
        case UP: y--; break;
        case DOWN: y++; break;
        default: break;
    }
    snake[0] = {x, y};

    // Move body
    for(int i = 1; i < snake.size(); i++) {
        prev2X = snake[i].first;
        prev2Y = snake[i].second;
        snake[i] = {prevX, prevY};
        prevX = prev2X;
        prevY = prev2Y;
    }

    // Wall collision
    if(x < 0 || x >= width || y < 0 || y >= height) gameOver = true;

    // Self collision
    for(int i = 1; i < snake.size(); i++) {
        if(snake[i].first == x && snake[i].second == y)
            gameOver = true;
    }

    // Fruit collision
    if(x == fruitX && y == fruitY) {
        score += 10;

        // Spawn new fruit not on snake
        bool valid;
        do {
            valid = true;
            fruitX = rand() % width;
            fruitY = rand() % height;
            for(auto s : snake) {
                if(s.first == fruitX && s.second == fruitY) {
                    valid = false;
                    break;
                }
            }
        } while(!valid);

        snake.push_back({-1,-1}); // add new tail
    }
}

int main() {
    Setup();
    while(!gameOver) {
        Draw();
        Input();
        Logic();
        Sleep(100); // adjust speed here
    }
    cout << "Game Over! Final Score: " << score << endl;
    return 0;
}

14)Carrom.cpp for SFML

# Install vcpkg if you don't have it

git clone https://github.com/Microsoft/vcpkg.git

cd vcpkg

.\bootstrap-vcpkg.bat

# Install SFML

.\vcpkg install sfml

# Integrate with Visual Studio

.\vcpkg integrate install   

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <memory>

constexpr float PI = 3.14159265358979323846f;
constexpr float FRICTION = 0.98f;
constexpr float BOARD_SIZE = 800.0f;
constexpr float POCKET_SIZE = 40.0f;
constexpr float STRIKER_SIZE = 25.0f;
constexpr float COIN_SIZE = 20.0f;
constexpr float MAX_POWER = 500.0f;
constexpr float MIN_POWER = 50.0f;

enum class CoinType {
    NONE, WHITE, BLACK, QUEEN, STRIKER
};

enum class Player {
    PLAYER1, PLAYER2
};

enum class GameState {
    MENU, PLAYING, POWER_SELECTION, AIMING, TURN_OVER, GAME_OVER
};

class Coin {
private:
    sf::CircleShape shape;
    CoinType type;
    sf::Vector2f velocity;
    bool inPlay;
    float mass;
   
public:
    Coin(CoinType t, float x, float y) : type(t), velocity(0, 0), inPlay(true) {
        float radius = (t == CoinType::STRIKER) ? STRIKER_SIZE : COIN_SIZE;
        shape.setRadius(radius);
        shape.setOrigin(radius, radius);
        shape.setPosition(x, y);
       
        switch(t) {
            case CoinType::WHITE:
                shape.setFillColor(sf::Color::White);
                shape.setOutlineColor(sf::Color::Black);
                mass = 1.0f;
                break;
            case CoinType::BLACK:
                shape.setFillColor(sf::Color::Black);
                shape.setOutlineColor(sf::Color::White);
                mass = 1.0f;
                break;
            case CoinType::QUEEN:
                shape.setFillColor(sf::Color::Red);
                shape.setOutlineColor(sf::Color::Yellow);
                mass = 1.2f;
                break;
            case CoinType::STRIKER:
                shape.setFillColor(sf::Color::Cyan);
                shape.setOutlineColor(sf::Color::Blue);
                mass = 1.5f;
                break;
        }
        shape.setOutlineThickness(2);
    }
   
    void update(float deltaTime) {
        if (!inPlay) return;
       
        velocity *= FRICTION;
        if (std::abs(velocity.x) < 0.1f && std::abs(velocity.y) < 0.1f) {
            velocity = sf::Vector2f(0, 0);
        }
       
        shape.move(velocity * deltaTime);
       
        // Boundary collision
        float radius = shape.getRadius();
        sf::Vector2f pos = shape.getPosition();
       
        if (pos.x - radius < 0) {
            pos.x = radius;
            velocity.x = -velocity.x * 0.8f;
        }
        if (pos.x + radius > BOARD_SIZE) {
            pos.x = BOARD_SIZE - radius;
            velocity.x = -velocity.x * 0.8f;
        }
        if (pos.y - radius < 0) {
            pos.y = radius;
            velocity.y = -velocity.y * 0.8f;
        }
        if (pos.y + radius > BOARD_SIZE) {
            pos.y = BOARD_SIZE - radius;
            velocity.y = -velocity.y * 0.8f;
        }
       
        shape.setPosition(pos);
    }
   
    void applyForce(sf::Vector2f force) {
        velocity += force / mass;
    }
   
    bool isInPlay() const { return inPlay; }
    void setInPlay(bool play) { inPlay = play; }
    CoinType getType() const { return type; }
    sf::Vector2f getPosition() const { return shape.getPosition(); }
    float getRadius() const { return shape.getRadius(); }
    sf::CircleShape getShape() const { return shape; }
    sf::Vector2f getVelocity() const { return velocity; }
   
    bool checkPocketCollision(const sf::Vector2f& pocketPos) {
        if (!inPlay) return false;
       
        float dx = shape.getPosition().x - pocketPos.x;
        float dy = shape.getPosition().y - pocketPos.y;
        float distance = std::sqrt(dx * dx + dy * dy);
       
        if (distance < POCKET_SIZE) {
            inPlay = false;
            return true;
        }
        return false;
    }
   
    bool checkCollision(Coin& other) {
        if (!inPlay || !other.inPlay) return false;
       
        float dx = shape.getPosition().x - other.shape.getPosition().x;
        float dy = shape.getPosition().y - other.shape.getPosition().y;
        float distance = std::sqrt(dx * dx + dy * dy);
        float minDistance = shape.getRadius() + other.shape.getRadius();
       
        if (distance < minDistance) {
            // Normalize collision vector
            float nx = dx / distance;
            float ny = dy / distance;
           
            // Relative velocity
            sf::Vector2f dv = velocity - other.velocity;
            float velocityAlongNormal = dv.x * nx + dv.y * ny;
           
            if (velocityAlongNormal > 0) return false;
           
            // Calculate impulse
            float restitution = 0.8f;
            float impulse = -(1 + restitution) * velocityAlongNormal;
            impulse /= (1 / mass + 1 / other.mass);
           
            // Apply impulse
            sf::Vector2f impulseVec(nx * impulse, ny * impulse);
            velocity += impulseVec / mass;
            other.velocity -= impulseVec / other.mass;
           
            // Position correction
            float percent = 0.2f;
            float slop = 0.01f;
            float correction = std::max(distance - minDistance, 0.0f) * percent;
            sf::Vector2f correctionVec = sf::Vector2f(nx, ny) * correction;
           
            shape.move(-correctionVec * (other.mass / (mass + other.mass)));
            other.shape.move(correctionVec * (mass / (mass + other.mass)));
           
            return true;
        }
        return false;
    }
};

class CarromGame {
private:
    sf::RenderWindow window;
    sf::Font font;
    GameState currentState;
    Player currentPlayer;
    std::vector<std::unique_ptr<Coin>> coins;
    std::vector<sf::Vector2f> pockets;
   
    // Game variables
    int player1Score;
    int player2Score;
    int foulsPlayer1;
    int foulsPlayer2;
    bool queenPocketed;
    Player queenClaimedBy;
    float power;
    float aimAngle;
    sf::Vector2f strikerPosition;
    bool isAiming;
    bool isPowerIncreasing;
   
    // Sounds
    sf::SoundBuffer strikeBuffer;
    sf::SoundBuffer pocketBuffer;
    sf::SoundBuffer collisionBuffer;
    sf::Sound strikeSound;
    sf::Sound pocketSound;
    sf::Sound collisionSound;
   
    // UI Elements
    sf::RectangleShape powerBar;
    sf::RectangleShape powerFill;
    sf::CircleShape aimIndicator;
    sf::VertexArray aimLine;
    sf::Text scoreText;
    sf::Text turnText;
    sf::Text powerText;
    sf::Text instructionText;
   
    void initializeBoard() {
        // Create pockets at corners and center of sides
        pockets.push_back(sf::Vector2f(POCKET_SIZE, POCKET_SIZE));
        pockets.push_back(sf::Vector2f(BOARD_SIZE - POCKET_SIZE, POCKET_SIZE));
        pockets.push_back(sf::Vector2f(POCKET_SIZE, BOARD_SIZE - POCKET_SIZE));
        pockets.push_back(sf::Vector2f(BOARD_SIZE - POCKET_SIZE, BOARD_SIZE - POCKET_SIZE));
        pockets.push_back(sf::Vector2f(BOARD_SIZE / 2, POCKET_SIZE));
        pockets.push_back(sf::Vector2f(BOARD_SIZE / 2, BOARD_SIZE - POCKET_SIZE));
       
        // Arrange coins in center circle
        float centerX = BOARD_SIZE / 2;
        float centerY = BOARD_SIZE / 2;
       
        // Add Queen at center
        coins.push_back(std::make_unique<Coin>(CoinType::QUEEN, centerX, centerY));
       
        // White coins in inner circle
        for (int i = 0; i < 6; i++) {
            float angle = i * (2 * PI / 6);
            float x = centerX + cos(angle) * 60;
            float y = centerY + sin(angle) * 60;
            coins.push_back(std::make_unique<Coin>(CoinType::WHITE, x, y));
        }
       
        // Black coins in middle circle
        for (int i = 0; i < 6; i++) {
            float angle = i * (2 * PI / 6);
            float x = centerX + cos(angle) * 120;
            float y = centerY + sin(angle) * 120;
            coins.push_back(std::make_unique<Coin>(CoinType::BLACK, x, y));
        }
       
        // Remaining coins in outer circle
        std::vector<CoinType> outerCoins = {
            CoinType::WHITE, CoinType::BLACK, CoinType::WHITE,
            CoinType::BLACK, CoinType::WHITE, CoinType::BLACK
        };
       
        for (int i = 0; i < 6; i++) {
            float angle = i * (2 * PI / 6);
            float x = centerX + cos(angle) * 180;
            float y = centerY + sin(angle) * 180;
            coins.push_back(std::make_unique<Coin>(outerCoins[i], x, y));
        }
       
        // Add striker for current player
        strikerPosition = sf::Vector2f(BOARD_SIZE / 2, BOARD_SIZE - 100);
        coins.push_back(std::make_unique<Coin>(CoinType::STRIKER, strikerPosition.x, strikerPosition.y));
    }
   
    void initializeUI() {
        // Power bar
        powerBar.setSize(sf::Vector2f(200, 20));
        powerBar.setPosition(50, BOARD_SIZE + 30);
        powerBar.setFillColor(sf::Color::Transparent);
        powerBar.setOutlineColor(sf::Color::White);
        powerBar.setOutlineThickness(2);
       
        powerFill.setSize(sf::Vector2f(0, 20));
        powerFill.setPosition(50, BOARD_SIZE + 30);
        powerFill.setFillColor(sf::Color::Green);
       
        // Aim indicator
        aimIndicator.setRadius(5);
        aimIndicator.setFillColor(sf::Color::Yellow);
        aimIndicator.setOrigin(5, 5);
       
        // Aim line
        aimLine.setPrimitiveType(sf::LinesStrip);
        aimLine.resize(2);
       
        // Text setup
        scoreText.setFont(font);
        scoreText.setCharacterSize(24);
        scoreText.setFillColor(sf::Color::White);
       
        turnText.setFont(font);
        turnText.setCharacterSize(24);
        turnText.setFillColor(sf::Color::Yellow);
       
        powerText.setFont(font);
        powerText.setCharacterSize(20);
        powerText.setFillColor(sf::Color::Green);
       
        instructionText.setFont(font);
        instructionText.setCharacterSize(18);
        instructionText.setFillColor(sf::Color::Cyan);
    }
   
    void updateUI() {
        std::stringstream ss;
        ss << "Player 1: " << player1Score << "  |  Player 2: " << player2Score;
        scoreText.setString(ss.str());
        scoreText.setPosition(BOARD_SIZE / 2 - scoreText.getLocalBounds().width / 2, BOARD_SIZE + 10);
       
        ss.str("");
        ss << "Turn: Player " << (currentPlayer == Player::PLAYER1 ? "1" : "2");
        turnText.setString(ss.str());
        turnText.setPosition(50, 10);
       
        ss.str("");
        ss << "Power: " << static_cast<int>(power);
        powerText.setString(ss.str());
        powerText.setPosition(260, BOARD_SIZE + 30);
       
        // Update instruction based on state
        switch(currentState) {
            case GameState::AIMING:
                instructionText.setString("Click and drag to aim, Space to set power");
                break;
            case GameState::POWER_SELECTION:
                instructionText.setString("Hold Space to increase power, Release to strike");
                break;
            case GameState::TURN_OVER:
                instructionText.setString("Space to continue...");
                break;
            default:
                instructionText.setString("");
        }
        instructionText.setPosition(BOARD_SIZE / 2 - instructionText.getLocalBounds().width / 2, BOARD_SIZE + 60);
       
        // Update power bar
        powerFill.setSize(sf::Vector2f((power / MAX_POWER) * 200, 20));
       
        // Update aim indicator
        if (currentState == GameState::AIMING && isAiming) {
            aimLine[0].position = strikerPosition;
            aimLine[0].color = sf::Color::Yellow;
            aimLine[1].position = sf::Vector2f(
                strikerPosition.x + cos(aimAngle) * 200,
                strikerPosition.y + sin(aimAngle) * 200
            );
            aimLine[1].color = sf::Color::Yellow;
           
            aimIndicator.setPosition(
                strikerPosition.x + cos(aimAngle) * 100,
                strikerPosition.y + sin(aimAngle) * 100
            );
        }
    }
   
    void checkPocketCollisions() {
        Coin* striker = nullptr;
        bool strikerPocketed = false;
        bool queenPocketedThisTurn = false;
        int whitePocketed = 0;
        int blackPocketed = 0;
       
        for (auto& coin : coins) {
            if (!coin->isInPlay()) continue;
           
            for (const auto& pocket : pockets) {
                if (coin->checkPocketCollision(pocket)) {
                    // Play pocket sound
                    pocketSound.play();
                   
                    if (coin->getType() == CoinType::STRIKER) {
                        strikerPocketed = true;
                        striker = coin.get();
                    } else if (coin->getType() == CoinType::QUEEN) {
                        queenPocketedThisTurn = true;
                        queenPocketed = true;
                    } else if (coin->getType() == CoinType::WHITE) {
                        whitePocketed++;
                    } else if (coin->getType() == CoinType::BLACK) {
                        blackPocketed++;
                    }
                    break;
                }
            }
        }
       
        // Handle scoring and fouls
        if (strikerPocketed) {
            // Foul: striker pocketed
            if (currentPlayer == Player::PLAYER1) {
                foulsPlayer1++;
                player1Score = std::max(0, player1Score - 1);
            } else {
                foulsPlayer2++;
                player2Score = std::max(0, player2Score - 1);
            }
            endTurn();
            return;
        }
       
        // Score points
        if (currentPlayer == Player::PLAYER1) {
            player1Score += whitePocketed;
            player2Score += blackPocketed;
        } else {
            player1Score += blackPocketed;
            player2Score += whitePocketed;
        }
       
        // Handle Queen pocketing
        if (queenPocketedThisTurn) {
            queenClaimedBy = currentPlayer;
        }
       
        // Check if all coins are pocketed
        checkGameEnd();
    }
   
    void checkGameEnd() {
        bool whiteRemaining = false;
        bool blackRemaining = false;
       
        for (const auto& coin : coins) {
            if (!coin->isInPlay()) continue;
            if (coin->getType() == CoinType::WHITE) whiteRemaining = true;
            if (coin->getType() == CoinType::BLACK) blackRemaining = true;
        }
       
        if (!whiteRemaining || !blackRemaining) {
            // Add bonus for Queen if claimed properly
            if (queenPocketed && queenClaimedBy == currentPlayer) {
                if (currentPlayer == Player::PLAYER1) {
                    player1Score += 3;
                } else {
                    player2Score += 3;
                }
            }
            currentState = GameState::GAME_OVER;
        }
    }
   
    void endTurn() {
        currentState = GameState::TURN_OVER;
       
        // Switch player if no coins pocketed or foul occurred
        bool coinPocketed = false;
        for (const auto& coin : coins) {
            if (!coin->isInPlay() && coin->getType() != CoinType::STRIKER) {
                coinPocketed = true;
                break;
            }
        }
       
        if (!coinPocketed) {
            currentPlayer = (currentPlayer == Player::PLAYER1) ? Player::PLAYER2 : Player::PLAYER1;
        }
    }
   
    void resetForNextTurn() {
        // Remove striker and add new one
        for (auto it = coins.begin(); it != coins.end(); ) {
            if ((*it)->getType() == CoinType::STRIKER) {
                it = coins.erase(it);
            } else {
                ++it;
            }
        }
       
        // Place striker based on player
        if (currentPlayer == Player::PLAYER1) {
            strikerPosition = sf::Vector2f(BOARD_SIZE / 2, BOARD_SIZE - 100);
        } else {
            strikerPosition = sf::Vector2f(BOARD_SIZE / 2, 100);
        }
       
        coins.push_back(std::make_unique<Coin>(CoinType::STRIKER, strikerPosition.x, strikerPosition.y));
       
        currentState = GameState::AIMING;
        power = MIN_POWER;
        isAiming = false;
    }
   
    void handleCollisions() {
        // Check collisions between all coins
        for (size_t i = 0; i < coins.size(); i++) {
            if (!coins[i]->isInPlay()) continue;
           
            for (size_t j = i + 1; j < coins.size(); j++) {
                if (!coins[j]->isInPlay()) continue;
               
                if (coins[i]->checkCollision(*coins[j])) {
                    collisionSound.play();
                }
            }
        }
    }
   
public:
    CarromGame() : window(sf::VideoMode(800, 900), "Advanced Carrom Game", sf::Style::Close),
                   currentState(GameState::PLAYING),
                   currentPlayer(Player::PLAYER1),
                   player1Score(0), player2Score(0),
                   foulsPlayer1(0), foulsPlayer2(0),
                   queenPocketed(false),
                   power(MIN_POWER),
                   aimAngle(0),
                   isAiming(false),
                   isPowerIncreasing(true) {
       
        window.setFramerateLimit(60);
        srand(static_cast<unsigned>(time(nullptr)));
       
        // Load font
        if (!font.loadFromFile("arial.ttf")) {
            std::cerr << "Failed to load font, using default" << std::endl;
        }
       
        // Load sounds
        if (!strikeBuffer.loadFromFile("strike.wav")) {
            std::cerr << "Failed to load strike sound" << std::endl;
        }
        if (!pocketBuffer.loadFromFile("pocket.wav")) {
            std::cerr << "Failed to load pocket sound" << std::endl;
        }
        if (!collisionBuffer.loadFromFile("collision.wav")) {
            std::cerr << "Failed to load collision sound" << std::endl;
        }
       
        strikeSound.setBuffer(strikeBuffer);
        pocketSound.setBuffer(pocketBuffer);
        collisionSound.setBuffer(collisionBuffer);
       
        initializeBoard();
        initializeUI();
    }
   
    void run() {
        sf::Clock clock;
       
        while (window.isOpen()) {
            float deltaTime = clock.restart().asSeconds();
           
            processEvents();
            update(deltaTime);
            render();
        }
    }
   
    void processEvents() {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
           
            if (event.type == sf::Event::KeyPressed) {
                if (event.key.code == sf::Keyboard::Escape) {
                    window.close();
                }
               
                if (event.key.code == sf::Keyboard::Space) {
                    if (currentState == GameState::AIMING) {
                        currentState = GameState::POWER_SELECTION;
                        power = MIN_POWER;
                        isPowerIncreasing = true;
                    } else if (currentState == GameState::TURN_OVER) {
                        resetForNextTurn();
                    }
                }
               
                if (event.key.code == sf::Keyboard::R) {
                    // Reset game
                    coins.clear();
                    initializeBoard();
                    player1Score = player2Score = 0;
                    foulsPlayer1 = foulsPlayer2 = 0;
                    queenPocketed = false;
                    currentState = GameState::PLAYING;
                    currentPlayer = Player::PLAYER1;
                    resetForNextTurn();
                }
            }
           
            if (event.type == sf::Event::KeyReleased) {
                if (event.key.code == sf::Keyboard::Space) {
                    if (currentState == GameState::POWER_SELECTION) {
                        // Strike the striker
                        Coin* striker = nullptr;
                        for (auto& coin : coins) {
                            if (coin->getType() == CoinType::STRIKER) {
                                striker = coin.get();
                                break;
                            }
                        }
                       
                        if (striker) {
                            sf::Vector2f force(cos(aimAngle) * power, sin(aimAngle) * power);
                            striker->applyForce(force);
                            strikeSound.play();
                            currentState = GameState::PLAYING;
                        }
                    }
                }
            }
           
            if (event.type == sf::Event::MouseButtonPressed) {
                if (event.mouseButton.button == sf::Mouse::Left) {
                    if (currentState == GameState::AIMING) {
                        isAiming = true;
                        aimAngle = atan2f(
                            event.mouseButton.y - strikerPosition.y,
                            event.mouseButton.x - strikerPosition.x
                        );
                    }
                }
            }
           
            if (event.type == sf::Event::MouseMoved) {
                if (isAiming && currentState == GameState::AIMING) {
                    aimAngle = atan2f(
                        event.mouseMove.y - strikerPosition.y,
                        event.mouseMove.x - strikerPosition.x
                    );
                }
            }
           
            if (event.type == sf::Event::MouseButtonReleased) {
                if (event.mouseButton.button == sf::Mouse::Left) {
                    isAiming = false;
                }
            }
        }
    }
   
    void update(float deltaTime) {
        if (currentState == GameState::POWER_SELECTION) {
            // Update power
            float powerSpeed = 200.0f * deltaTime;
            if (isPowerIncreasing) {
                power += powerSpeed;
                if (power >= MAX_POWER) {
                    power = MAX_POWER;
                    isPowerIncreasing = false;
                }
            } else {
                power -= powerSpeed;
                if (power <= MIN_POWER) {
                    power = MIN_POWER;
                    isPowerIncreasing = true;
                }
            }
        }
       
        // Update all coins
        for (auto& coin : coins) {
            coin->update(deltaTime);
        }
       
        // Handle collisions
        handleCollisions();
       
        // Check pocket collisions
        checkPocketCollisions();
       
        // Check if all coins stopped moving
        if (currentState == GameState::PLAYING) {
            bool allStopped = true;
            for (const auto& coin : coins) {
                if (coin->isInPlay() &&
                    std::abs(coin->getVelocity().x) > 0.1f ||
                    std::abs(coin->getVelocity().y) > 0.1f) {
                    allStopped = false;
                    break;
                }
            }
           
            if (allStopped) {
                endTurn();
            }
        }
       
        updateUI();
    }
   
    void render() {
        window.clear(sf::Color(139, 69, 19)); // Brown board color
       
        // Draw board boundaries
        sf::RectangleShape board(sf::Vector2f(BOARD_SIZE, BOARD_SIZE));
        board.setFillColor(sf::Color(222, 184, 135)); // Light brown
        board.setOutlineColor(sf::Color(101, 67, 33));
        board.setOutlineThickness(10);
        window.draw(board);
       
        // Draw center circle
        sf::CircleShape centerCircle(50);
        centerCircle.setOrigin(50, 50);
        centerCircle.setPosition(BOARD_SIZE / 2, BOARD_SIZE / 2);
        centerCircle.setFillColor(sf::Color::Transparent);
        centerCircle.setOutlineColor(sf::Color::Red);
        centerCircle.setOutlineThickness(2);
        window.draw(centerCircle);
       
        // Draw pockets
        for (const auto& pocket : pockets) {
            sf::CircleShape pocketShape(POCKET_SIZE);
            pocketShape.setOrigin(POCKET_SIZE, POCKET_SIZE);
            pocketShape.setPosition(pocket);
            pocketShape.setFillColor(sf::Color::Black);
            window.draw(pocketShape);
        }
       
        // Draw coins
        for (const auto& coin : coins) {
            if (coin->isInPlay()) {
                window.draw(coin->getShape());
            }
        }
       
        // Draw UI elements
        if (currentState == GameState::AIMING && isAiming) {
            window.draw(aimLine);
            window.draw(aimIndicator);
        }
       
        window.draw(powerBar);
        window.draw(powerFill);
        window.draw(scoreText);
        window.draw(turnText);
        window.draw(powerText);
        window.draw(instructionText);
       
        // Draw game over screen
        if (currentState == GameState::GAME_OVER) {
            sf::RectangleShape overlay(sf::Vector2f(BOARD_SIZE, BOARD_SIZE));
            overlay.setFillColor(sf::Color(0, 0, 0, 200));
            window.draw(overlay);
           
            sf::Text gameOverText;
            gameOverText.setFont(font);
            gameOverText.setCharacterSize(48);
            gameOverText.setFillColor(sf::Color::Yellow);
            gameOverText.setString("GAME OVER");
            gameOverText.setPosition(BOARD_SIZE / 2 - gameOverText.getLocalBounds().width / 2,
                                    BOARD_SIZE / 2 - 50);
            window.draw(gameOverText);
           
            std::stringstream ss;
            ss << "Winner: Player " << (player1Score > player2Score ? "1" : "2");
            sf::Text winnerText;
            winnerText.setFont(font);
            winnerText.setCharacterSize(36);
            winnerText.setFillColor(sf::Color::Cyan);
            winnerText.setString(ss.str());
            winnerText.setPosition(BOARD_SIZE / 2 - winnerText.getLocalBounds().width / 2,
                                  BOARD_SIZE / 2 + 20);
            window.draw(winnerText);
           
            sf::Text restartText;
            restartText.setFont(font);
            restartText.setCharacterSize(24);
            restartText.setFillColor(sf::Color::White);
            restartText.setString("Press R to restart");
            restartText.setPosition(BOARD_SIZE / 2 - restartText.getLocalBounds().width / 2,
                                   BOARD_SIZE / 2 + 80);
            window.draw(restartText);
        }
       
        window.display();
    }
};

int main() {
    CarromGame game;
    game.run();
    return 0;
}

15)Carrom.cpp without SFML

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <conio.h>
#include <windows.h>

using namespace std;

const int BOARD_SIZE = 20;
const char EMPTY = '.';
const char WHITE = 'W';
const char BLACK = 'B';
const char QUEEN = 'Q';
const char STRIKER = 'S';
const char POCKET = 'O';

class CarromBoard {
private:
    char board[BOARD_SIZE][BOARD_SIZE];
    int player1Score;
    int player2Score;
    int currentPlayer; // 1 or 2
    bool gameOver;
    int strikerX, strikerY;
    float strikerAngle;
    float strikerPower;
   
    struct Coin {
        int x, y;
        char type;
        bool inPlay;
        float vx, vy;
    };
   
    vector<Coin> coins;
   
public:
    CarromBoard() : player1Score(0), player2Score(0), currentPlayer(1),
                   gameOver(false), strikerAngle(0), strikerPower(0) {
        initializeBoard();
    }
   
    void initializeBoard() {
        // Clear board
        for(int i = 0; i < BOARD_SIZE; i++) {
            for(int j = 0; j < BOARD_SIZE; j++) {
                board[i][j] = EMPTY;
            }
        }
       
        // Set pockets
        board[0][0] = POCKET;
        board[0][BOARD_SIZE-1] = POCKET;
        board[BOARD_SIZE-1][0] = POCKET;
        board[BOARD_SIZE-1][BOARD_SIZE-1] = POCKET;
        board[0][BOARD_SIZE/2] = POCKET;
        board[BOARD_SIZE-1][BOARD_SIZE/2] = POCKET;
       
        coins.clear();
       
        // Add Queen at center
        coins.push_back({BOARD_SIZE/2, BOARD_SIZE/2, QUEEN, true, 0, 0});
        board[BOARD_SIZE/2][BOARD_SIZE/2] = QUEEN;
       
        // Add coins in circle pattern
        int centerX = BOARD_SIZE/2;
        int centerY = BOARD_SIZE/2;
       
        // White coins
        for(int i = 0; i < 3; i++) {
            int x = centerX + i - 1;
            int y = centerY - 2;
            coins.push_back({x, y, WHITE, true, 0, 0});
            board[y][x] = WHITE;
        }
       
        // Black coins
        for(int i = 0; i < 3; i++) {
            int x = centerX + i - 1;
            int y = centerY + 2;
            coins.push_back({x, y, BLACK, true, 0, 0});
            board[y][x] = BLACK;
        }
       
        // Additional coins
        coins.push_back({centerX-2, centerY, WHITE, true, 0, 0});
        board[centerY][centerX-2] = WHITE;
        coins.push_back({centerX+2, centerY, BLACK, true, 0, 0});
        board[centerY][centerX+2] = BLACK;
       
        // Place striker for player 1 (bottom)
        strikerX = BOARD_SIZE/2;
        strikerY = BOARD_SIZE - 2;
        board[strikerY][strikerX] = STRIKER;
    }
   
    void displayBoard() {
        system("cls");
        cout << "============================\n";
        cout << "      ADVANCED CARROM\n";
        cout << "============================\n\n";
       
        // Display scores
        cout << "Player 1 (White): " << player1Score << " points\n";
        cout << "Player 2 (Black): " << player2Score << " points\n";
        cout << "Current Player: Player " << currentPlayer << "\n\n";
       
        // Display board with border
        cout << "   ";
        for(int i = 0; i < BOARD_SIZE; i++) {
            cout << (i % 10) << " ";
        }
        cout << "\n";
       
        for(int i = 0; i < BOARD_SIZE; i++) {
            cout << (i < 10 ? " " : "") << i << " ";
            for(int j = 0; j < BOARD_SIZE; j++) {
                cout << board[i][j] << " ";
            }
            cout << "\n";
        }
       
        cout << "\nLegend: ";
        cout << WHITE << "-White ";
        cout << BLACK << "-Black ";
        cout << QUEEN << "-Queen ";
        cout << STRIKER << "-Striker ";
        cout << POCKET << "-Pocket\n";
       
        cout << "\nStriker Angle: " << strikerAngle * 180 / 3.14159 << " degrees";
        cout << "\nStriker Power: " << strikerPower;
        cout << "\n\n";
    }
   
    void displayAimingGuide() {
        cout << "Aiming Guide:\n";
        cout << "  W - Increase angle\n";
        cout << "  S - Decrease angle\n";
        cout << "  A - Decrease power\n";
        cout << "  D - Increase power\n";
        cout << "  Space - Strike!\n";
        cout << "  R - Reset aim\n";
        cout << "  Q - Quit\n";
       
        // Show direction indicator
        cout << "\nDirection: ";
        if(strikerAngle >= -0.2 && strikerAngle <= 0.2) cout << "UP";
        else if(strikerAngle > 0.2 && strikerAngle < 1.4) cout << "UP-RIGHT";
        else if(strikerAngle >= 1.4 && strikerAngle <= 1.8) cout << "RIGHT";
        else if(strikerAngle > 1.8 && strikerAngle < 2.8) cout << "DOWN-RIGHT";
        else if(strikerAngle >= -1.8 && strikerAngle <= -1.4) cout << "LEFT";
        else if(strikerAngle > -1.4 && strikerAngle < -0.2) cout << "UP-LEFT";
        else cout << "DOWN-LEFT";
        cout << "\n";
    }
   
    void aimStrike() {
        strikerAngle = 0;
        strikerPower = 5;
        char input;
        bool aiming = true;
       
        while(aiming) {
            displayBoard();
            displayAimingGuide();
           
            input = _getch();
           
            switch(toupper(input)) {
                case 'W':
                    strikerAngle -= 0.2;
                    break;
                case 'S':
                    strikerAngle += 0.2;
                    break;
                case 'A':
                    if(strikerPower > 1) strikerPower--;
                    break;
                case 'D':
                    if(strikerPower < 10) strikerPower++;
                    break;
                case ' ':
                    executeStrike();
                    aiming = false;
                    break;
                case 'R':
                    strikerAngle = 0;
                    strikerPower = 5;
                    break;
                case 'Q':
                    gameOver = true;
                    aiming = false;
                    break;
            }
           
            // Keep angle within bounds
            if(strikerAngle > 3.14159) strikerAngle -= 2 * 3.14159;
            if(strikerAngle < -3.14159) strikerAngle += 2 * 3.14159;
        }
    }
   
    void executeStrike() {
        // Calculate strike velocity
        float vx = cos(strikerAngle) * strikerPower;
        float vy = sin(strikerAngle) * strikerPower;
       
        // Update striker position
        board[strikerY][strikerX] = EMPTY;
        strikerX += vx;
        strikerY += vy;
       
        // Keep striker in bounds
        if(strikerX < 0) strikerX = 0;
        if(strikerX >= BOARD_SIZE) strikerX = BOARD_SIZE - 1;
        if(strikerY < 0) strikerY = 0;
        if(strikerY >= BOARD_SIZE) strikerY = BOARD_SIZE - 1;
       
        // Check collisions
        simulatePhysics(vx, vy);
       
        // Update board
        updateBoard();
       
        // Check for pocketed coins
        checkPockets();
       
        // Switch player if no coins pocketed
        switchPlayerIfNeeded();
    }
   
    void simulatePhysics(float vx, float vy) {
        // Simple physics simulation
        for(auto& coin : coins) {
            if(!coin.inPlay) continue;
           
            // Check if striker hits this coin
            float dx = coin.x - strikerX;
            float dy = coin.y - strikerY;
            float distance = sqrt(dx*dx + dy*dy);
           
            if(distance < 2) { // Collision
                // Transfer some momentum
                coin.vx = vx * 0.7;
                coin.vy = vy * 0.7;
               
                // Move coin
                int newX = coin.x + coin.vx;
                int newY = coin.y + coin.vy;
               
                // Check bounds
                if(newX >= 0 && newX < BOARD_SIZE && newY >= 0 && newY < BOARD_SIZE) {
                    coin.x = newX;
                    coin.y = newY;
                }
            }
        }
    }
   
    void updateBoard() {
        // Clear board
        for(int i = 0; i < BOARD_SIZE; i++) {
            for(int j = 0; j < BOARD_SIZE; j++) {
                if(board[i][j] != POCKET) {
                    board[i][j] = EMPTY;
                }
            }
        }
       
        // Place coins
        for(const auto& coin : coins) {
            if(coin.inPlay && coin.x >= 0 && coin.x < BOARD_SIZE &&
               coin.y >= 0 && coin.y < BOARD_SIZE) {
                board[coin.y][coin.x] = coin.type;
            }
        }
       
        // Place striker
        if(strikerX >= 0 && strikerX < BOARD_SIZE &&
           strikerY >= 0 && strikerY < BOARD_SIZE) {
            board[strikerY][strikerX] = STRIKER;
        }
    }
   
    void checkPockets() {
        vector<int> toRemove;
       
        for(int i = 0; i < coins.size(); i++) {
            if(!coins[i].inPlay) continue;
           
            // Check if coin is in pocket
            if(board[coins[i].y][coins[i].x] == POCKET) {
                coins[i].inPlay = false;
               
                // Add score
                if(coins[i].type == WHITE) {
                    if(currentPlayer == 1) player1Score++;
                    else player2Score++;
                } else if(coins[i].type == BLACK) {
                    if(currentPlayer == 1) player2Score++;
                    else player1Score++;
                } else if(coins[i].type == QUEEN) {
                    // Queen gives bonus
                    if(currentPlayer == 1) player1Score += 3;
                    else player2Score += 3;
                }
            }
        }
    }
   
    void switchPlayerIfNeeded() {
        // Count coins pocketed this turn
        int coinsPocketed = 0;
        for(const auto& coin : coins) {
            if(!coin.inPlay) coinsPocketed++;
        }
       
        // If no coins pocketed or striker pocketed, switch player
        if(coinsPocketed == 0 || board[strikerY][strikerX] == POCKET) {
            currentPlayer = (currentPlayer == 1) ? 2 : 1;
           
            // Reset striker position for new player
            board[strikerY][strikerX] = EMPTY;
            if(currentPlayer == 1) {
                strikerX = BOARD_SIZE/2;
                strikerY = BOARD_SIZE - 2;
            } else {
                strikerX = BOARD_SIZE/2;
                strikerY = 2;
            }
            board[strikerY][strikerX] = STRIKER;
        }
       
        // Check if all coins are pocketed
        bool allPocketed = true;
        for(const auto& coin : coins) {
            if(coin.type != QUEEN && coin.inPlay) {
                allPocketed = false;
                break;
            }
        }
       
        if(allPocketed) {
            gameOver = true;
        }
    }
   
    void playGame() {
        while(!gameOver) {
            displayBoard();
            aimStrike();
        }
       
        displayGameOver();
    }
   
    void displayGameOver() {
        system("cls");
        cout << "============================\n";
        cout << "        GAME OVER!\n";
        cout << "============================\n\n";
       
        cout << "Final Scores:\n";
        cout << "Player 1: " << player1Score << " points\n";
        cout << "Player 2: " << player2Score << " points\n\n";
       
        if(player1Score > player2Score) {
            cout << "Player 1 WINS! 🏆\n";
        } else if(player2Score > player1Score) {
            cout << "Player 2 WINS! 🏆\n";
        } else {
            cout << "It's a TIE! 🤝\n";
        }
       
        cout << "\nPress any key to exit...";
        _getch();
    }
};

int main() {
    CarromBoard game;
    game.playGame();
    return 0;
}

16)Chess.cpp for SFML 

Project Folder/

├── ChessGame.cpp

├── images/

│   ├── board.png

│   └── figures.png

└── sounds/

    ├── move.wav

    └── capture.wav

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace sf;
using namespace std;

const int SIZE = 56;
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;

Sprite f[32]; // figures
int board[8][8] = {
    -1, -2, -3, -4, -5, -3, -2, -1,
    -6, -6, -6, -6, -6, -6, -6, -6,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    6, 6, 6, 6, 6, 6, 6, 6,
    1, 2, 3, 4, 5, 3, 2, 1
};

enum PieceType {
    KING = 1, QUEEN = 2, BISHOP = 3, KNIGHT = 4, ROOK = 5, PAWN = 6
};

string position = "";
bool isMove = false;
int selectedPiece = -1;
float dx = 0, dy = 0;
Vector2f oldPos, newPos;
bool whiteTurn = true;

string toChessNote(Vector2f p) {
    string s = "";
    s += char(p.x / SIZE + 97);
    s += char(7 - p.y / SIZE + 49);
    return s;
}

Vector2f toCoord(char a, char b) {
    int x = int(a) - 97;
    int y = 7 - (int(b) - 49);
    return Vector2f(x * SIZE, y * SIZE);
}

void move(string str) {
    Vector2f oldPos = toCoord(str[0], str[1]);
    Vector2f newPos = toCoord(str[2], str[3]);

    // Capture piece
    for (int i = 0; i < 32; i++) {
        if (f[i].getPosition() == newPos) {
            f[i].setPosition(-100, -100);
            break;
        }
    }

    // Move piece
    for (int i = 0; i < 32; i++) {
        if (f[i].getPosition() == oldPos) {
            f[i].setPosition(newPos);
            break;
        }
    }
}

void loadPosition(Texture &t1) {
    int k = 0;
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            int n = board[i][j];
            if (n == 0) continue;
           
            int x = abs(n) - 1;
            int y = n > 0 ? 1 : 0;
            f[k].setTexture(t1);
            f[k].setTextureRect(IntRect(x * SIZE, y * SIZE, SIZE, SIZE));
            f[k].setPosition(j * SIZE, i * SIZE);
            k++;
        }
    }
   
    // Apply saved moves
    for (size_t i = 0; i < position.length(); i += 5) {
        if (i + 4 <= position.length()) {
            move(position.substr(i, 4));
        }
    }
}

bool isValidMove(Vector2f oldPos, Vector2f newPos, int pieceType, bool isWhite) {
    int oldX = oldPos.x / SIZE;
    int oldY = oldPos.y / SIZE;
    int newX = newPos.x / SIZE;
    int newY = newPos.y / SIZE;
   
    int dx = abs(newX - oldX);
    int dy = abs(newY - oldY);
   
    switch (abs(pieceType)) {
        case PAWN: // Pawn
            if (isWhite) {
                if (oldY == 6 && dy == 2 && dx == 0) return true;
                if (dy == 1 && dx == 0) return true;
                if (dy == 1 && dx == 1) return true; // Capture
            } else {
                if (oldY == 1 && dy == 2 && dx == 0) return true;
                if (dy == 1 && dx == 0) return true;
                if (dy == 1 && dx == 1) return true; // Capture
            }
            break;
           
        case ROOK: // Rook
            return (dx == 0 || dy == 0);
           
        case KNIGHT: // Knight
            return (dx == 1 && dy == 2) || (dx == 2 && dy == 1);
           
        case BISHOP: // Bishop
            return (dx == dy);
           
        case QUEEN: // Queen
            return (dx == 0 || dy == 0 || dx == dy);
           
        case KING: // King
            return (dx <= 1 && dy <= 1);
    }
   
    return false;
}

void drawBoard(RenderWindow &window, Sprite &sBoard) {
    window.clear();
    window.draw(sBoard);
   
    // Draw pieces
    for (int i = 0; i < 32; i++) {
        window.draw(f[i]);
    }
   
    // Draw coordinates
    Font font;
    if (font.loadFromFile("arial.ttf")) {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                Text text;
                text.setFont(font);
                text.setCharacterSize(12);
                text.setFillColor(Color::Black);
               
                // Files (a-h)
                if (i == 7) {
                    text.setString(string(1, char('a' + j)));
                    text.setPosition(j * SIZE + 5, (i + 1) * SIZE - 15);
                    window.draw(text);
                }
               
                // Ranks (1-8)
                if (j == 0) {
                    text.setString(to_string(8 - i));
                    text.setPosition(5, i * SIZE + 5);
                    window.draw(text);
                }
            }
        }
    }
   
    // Draw turn indicator
    Text turnText;
    turnText.setFont(font);
    turnText.setCharacterSize(20);
    turnText.setFillColor(whiteTurn ? Color::White : Color::Black);
    turnText.setString(whiteTurn ? "White's Turn" : "Black's Turn");
    turnText.setPosition(WINDOW_WIDTH - 150, 10);
   
    RectangleShape turnBg(Vector2f(140, 30));
    turnBg.setFillColor(whiteTurn ? Color::Black : Color::White);
    turnBg.setPosition(WINDOW_WIDTH - 150, 10);
    turnBg.setOutlineColor(Color::Red);
    turnBg.setOutlineThickness(2);
   
    window.draw(turnBg);
    window.draw(turnText);
   
    // Draw move history
    Text moveText;
    moveText.setFont(font);
    moveText.setCharacterSize(14);
    moveText.setFillColor(Color::White);
    moveText.setPosition(10, WINDOW_HEIGHT - 100);
   
    string moveHistory = "Moves: " + position;
    if (moveHistory.length() > 100) {
        moveHistory = "..." + moveHistory.substr(moveHistory.length() - 100);
    }
    moveText.setString(moveHistory);
   
    RectangleShape historyBg(Vector2f(WINDOW_WIDTH - 20, 90));
    historyBg.setFillColor(Color(0, 0, 0, 200));
    historyBg.setPosition(10, WINDOW_HEIGHT - 100);
   
    window.draw(historyBg);
    window.draw(moveText);
}

int main() {
    RenderWindow window(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Chess Game");
   
    // Load textures
    Texture t1, t2;
    if (!t1.loadFromFile("images/figures.png")) {
        cout << "Error loading figures.png" << endl;
        return -1;
    }
    if (!t2.loadFromFile("images/board.png")) {
        cout << "Error loading board.png" << endl;
        return -1;
    }
   
    Sprite sBoard(t2);
   
    // Scale board to fit window
    float scaleX = float(WINDOW_WIDTH) / (SIZE * 8);
    float scaleY = float(WINDOW_HEIGHT - 100) / (SIZE * 8);
    sBoard.setScale(scaleX, scaleY);
   
    loadPosition(t1);
   
    // Sound
    SoundBuffer moveBuffer, captureBuffer;
    Sound moveSound, captureSound;
   
    if (moveBuffer.loadFromFile("sounds/move.wav")) {
        moveSound.setBuffer(moveBuffer);
    }
    if (captureBuffer.loadFromFile("sounds/capture.wav")) {
        captureSound.setBuffer(captureBuffer);
    }
   
    while (window.isOpen()) {
        Vector2i pos = Mouse::getPosition(window);
       
        Event e;
        while (window.pollEvent(e)) {
            if (e.type == Event::Closed) {
                window.close();
            }
           
            // Undo move
            if (e.type == Event::KeyPressed) {
                if (e.key.code == Keyboard::BackSpace) {
                    if (position.length() >= 5) {
                        position.erase(position.length() - 5, 5);
                        loadPosition(t1);
                        whiteTurn = !whiteTurn;
                    }
                }
               
                // Reset game
                if (e.key.code == Keyboard::R) {
                    position = "";
                    loadPosition(t1);
                    whiteTurn = true;
                }
            }
           
            // Drag and drop
            if (e.type == Event::MouseButtonPressed) {
                if (e.mouseButton.button == Mouse::Left) {
                    for (int i = 0; i < 32; i++) {
                        if (f[i].getGlobalBounds().contains(pos.x, pos.y)) {
                            // Check if it's the correct player's turn
                            int pieceType = board[int(f[i].getPosition().y / SIZE)][int(f[i].getPosition().x / SIZE)];
                            bool isWhite = pieceType > 0;
                           
                            if ((isWhite && whiteTurn) || (!isWhite && !whiteTurn)) {
                                isMove = true;
                                selectedPiece = i;
                                dx = pos.x - f[i].getPosition().x;
                                dy = pos.y - f[i].getPosition().y;
                                oldPos = f[i].getPosition();
                                break;
                            }
                        }
                    }
                }
            }
           
            if (e.type == Event::MouseButtonReleased) {
                if (e.mouseButton.button == Mouse::Left && isMove) {
                    isMove = false;
                   
                    Vector2f p = f[selectedPiece].getPosition() + Vector2f(SIZE / 2, SIZE / 2);
                    Vector2f newPos = Vector2f(SIZE * int(p.x / SIZE), SIZE * int(p.y / SIZE));
                   
                    // Check if move is valid
                    int pieceType = board[int(oldPos.y / SIZE)][int(oldPos.x / SIZE)];
                    bool isWhite = pieceType > 0;
                   
                    if (isValidMove(oldPos, newPos, pieceType, isWhite)) {
                        // Check if capture
                        bool capture = false;
                        for (int i = 0; i < 32; i++) {
                            if (i != selectedPiece && f[i].getPosition() == newPos) {
                                capture = true;
                                break;
                            }
                        }
                       
                        if (capture) {
                            captureSound.play();
                        } else {
                            moveSound.play();
                        }
                       
                        string str = toChessNote(oldPos) + toChessNote(newPos);
                        move(str);
                        position += str + " ";
                        whiteTurn = !whiteTurn;
                    } else {
                        // Invalid move, return to original position
                        f[selectedPiece].setPosition(oldPos);
                    }
                }
            }
        }
       
        // Computer move (simple example)
        if (Keyboard::isKeyPressed(Keyboard::Space) && !whiteTurn) {
            // Simple AI: move a random piece
            vector<int> blackPieces;
            for (int i = 0; i < 32; i++) {
                if (f[i].getPosition().x >= 0 && f[i].getPosition().y >= 0) {
                    Vector2f pos = f[i].getPosition();
                    int pieceType = board[int(pos.y / SIZE)][int(pos.x / SIZE)];
                    if (pieceType < 0) { // Black piece
                        blackPieces.push_back(i);
                    }
                }
            }
           
            if (!blackPieces.empty()) {
                int randomPiece = blackPieces[rand() % blackPieces.size()];
                Vector2f oldPos = f[randomPiece].getPosition();
               
                // Try random moves
                for (int attempt = 0; attempt < 10; attempt++) {
                    int dx = (rand() % 3) - 1; // -1, 0, or 1
                    int dy = (rand() % 3) - 1; // -1, 0, or 1
                   
                    int newX = int(oldPos.x / SIZE) + dx;
                    int newY = int(oldPos.y / SIZE) + dy;
                   
                    if (newX >= 0 && newX < 8 && newY >= 0 && newY < 8) {
                        Vector2f newPos(newX * SIZE, newY * SIZE);
                        int pieceType = board[int(oldPos.y / SIZE)][int(oldPos.x / SIZE)];
                       
                        if (isValidMove(oldPos, newPos, pieceType, false)) {
                            string str = toChessNote(oldPos) + toChessNote(newPos);
                            move(str);
                            position += str + " ";
                            whiteTurn = true;
                            break;
                        }
                    }
                }
            }
        }
       
        // Update piece position while dragging
        if (isMove) {
            f[selectedPiece].setPosition(pos.x - dx, pos.y - dy);
        }
       
        // Draw everything
        drawBoard(window, sBoard);
        window.display();
    }
   
    return 0;
}

17)Coming soon...

Post a Comment

0 Comments