Showing posts with label C source code. Show all posts
Showing posts with label C source code. Show all posts

Sunday, March 30, 2025

Develop Tetris Game in C programming Without Graphics Library and Full Source Code

 Tetrix game is created in C programming without using graphic library. We draw shapes only using # character and played on command window. User can play game using up, left, right, and down arrow key. The up key rotate Tetrimino (Shapes) in clockwise direction, left key move Tetrimino (Shapes) in left direction toward negative x-axis, right key move Tetrimino (Shapes) in right direction toward positive x-axis, and down key rotate Tetrimino (Shapes) in anticlockwise direction. By default, Tetrimino (Shapes) will move 1 unit downward toward negative y-axis in each frame of the game.  The score is calculated based on the number of rows filled with boxes. 

The main objective of this project is to provide knowledge and technique about creating Tetris game in C programming, provide basic knowledge of linear algebra used to rotate and translate shapes. User can use any graphics library to draw window, and shapes to make it similar to commercial games. However, the algorithm of the game is same in all Tetris game available in market.  

In this article, I will explain the following items:

  • Coordinate system of the game
  • Usage of linear algebra to rotate and translate shapes.
  • Data Structure used in the game
  • Collision detection and score checking Techniques


Also, Download the final version of the game Download Project from GitHub.

I have explained the game in following two articles:

Part 1: Tetriminos (Shapes), Coordinate System, Rotation and Translate

Part 2: Data Structure, Collision detection and Score checking Techniques

Part 2: Teris Game in C programming | Data Structure, Collision detection and Score checking Techniques

Previous Page 

Data Structure

This is a 2D game where the primary object is a box. A combination of 4 boxes forms a Tetrimino (shape). Boxes are arranged on the Tetris board from the bottom upward.

Board Specifications
  • The Tetris board has a size of 11 columns (x-axis) by 21 rows (y-axis).
  • Tetriminos are arranged on the board such that if an entire row is filled with boxes, the player earns points.
Box Representation
  • Each box is defined by 2D (x, y) coordinates, which determine where it is drawn.
  • To represent boxes and Tetriminos (shapes), the game uses three structure variables:
    • Point2D
    • Tetriminos
    • TetrisBox

Part 1: Teris Game in C programming | Tetriminos (Shapes), Coordinate System, Rotation and Translation of Tetriminos (Shapes)

Previous Page                                                                                                                  Next Page

Tetriminos (Shapes)

In this Tetris game, I use 7 shapes. While some versions only include 5 shapes, I’ve added two extra ones: the J and S shapes, which are mirror opposites of the L and Z shapes, respectively.

Each shape consists of 4 blocks, and each block is called a Mino (short for monomino). A group of 4 Minos forms a Tetrimino (also known as Tetromino or Tetramino). For consistency, I’ll use the term Tetrimino throughout this article.


Coordinate System

To simplify game development, I’ve designed a gotoxy(x, y) function that relocates the coordinate system’s origin (0, 0) from the default top-left corner of the command window to a more convenient central position at (36, -12).

How It Works:
  1. Coordinate Transformation:
    • The function offsets input coordinates:
      • x becomes x + 36
      • y becomes y + 12
    • This allows negative coordinates (e.g., (-36, 12) maps to the original (0, 0)).
  1. Purpose:
    • Centering (0, 0) simplifies calculations for symmetric gameplay elements (e.g., rotating Tetriminos around the origin).
    • Negative coordinates enable intuitive positioning relative to the new origin.

Sunday, February 2, 2025

Part 2: Tic Tac Toe game in C programing | Source Code explanation

Previous Page

Watch this tutorial in YouTube.


In this article, we will discuss the following main topics. I encourage you to watch YouTube video to understand the source code in detail.

  • Technique to switch players.
  • Logic to check winner player.
  • Calculate computer player best move.

Technique to switch players

I have assigned the value 0 to the first player and the value 1 to the second player, regardless of who plays first. If the human chooses to play first, the value 0 is assigned to the human variable, and the value 1 is assigned to the computer variable, and vice versa. Throughout the project, the system checks the current player against the human or computer variable to determine the player type. The first player always uses "X," while the second player uses "O." However, the value assigned to a box depends on the player type: the value of a box chosen by the human is 3, and the value of a box chosen by the computer is 5.

Part 1: Tic Tac Toe game in C programing | Flowchart, Algorithm of Computer Player, and Data Structure

Previous Page                                                                                                              Next Page

Watch this tutorial in YouTube.

Flowchart



Explanation of Flowchart:

Start: The game process begins here.

Display Game Menu: The user can choose to play first or second.

Initialize Game: Initialize the human or computer as the first or second player. Set up the Tic-Tac-Toe board and assign initial values to the players.

Wednesday, December 4, 2024

Part 2: Snake Game in C | Snake Collision Detection, Calculate next position and Changing direction

Previous page 

In this section, we will discuss the following items.

  • Techniques to change direction of the snake based on user input.
  • Techniques to calculate the snake's next position.
  • Techniques to check for snake collision with window and its body.

Snake direction and food

We are using the gotoxy(int x, int y) function to move the snake on the screen. The top left corner of the PC window starts at (0,0). The right side of the screen is positive x-axis, and the bottom of the screen is positive y-axis. However, we can represent the direction of snake in all four directions by positive and negative axes (-x, 0), (x, 0), (0, -y), and (0, y). For the left arrow key, set direction as negative x-axis (-x,0), for the right arrow key set direction as positive x-axis (x,0), for the up arrow key set direction as negative y-axis (-y,0), and for the down arrow key set direction as positive y-axis (y,0). When the direction is changed, the snake will move perpendicular to current position, so we don't have to use both x, and y coordinates values. The coordinates system of the PC window is shown in the image below.

Part 1: Snake Game in C | Flowchart, Data Structure and Algorithm

Previous page                                                                                                                 Next Page

Flowchart

Flowchart: Snake Game in C


Explanation of Flowchart:

Start: The process begins here.

Initialize game: Initialize Snake Direction, food, snake, window, variables, and others

Monday, June 3, 2024

Part 4: Library management in C| Pagination, Dynamic Memory allocation, write Comma Separated Values (CSV) file

Previous Page

In this part, we will create pagination in C programming to view large set of books data. In college there might be thousands of books. We can't display all items on the screen, so we need to create techniques to display small set of data at a time and allow users to select next page or previous page to view data which is called pagination. Also, we will discuss to manage large set of books data and write books data into CSV file.

Here, we will discuss following items:

  • Pagination: Users can explore large set of data by selecting next or previous page of data.
  • Dynamic Memory allocation: Dynamic numbers of books are loaded into the memory, modify or delete book details from the memory using dynamic memory allocation.
  • Write Comma Separated Values (CSV): Export large set of books data into CSV file.
Please follow the source code of header file userMenu.h and loadCsvData.h. 

Pagination:
We have three main functions to implement pagination features. The main technique is to load data into computer memory (RAM). The number of data which can be loaded in memory depend upon size of the memory. However, we will not get memory problem to load couple of thousands of data. In this application I haven't used large set of data however this technique can be used for any size of data.
The name of the functions are readBooks(), viewAllBooks(), and viewBooksByPage().  

Part 3: Library management in C| Read Comma Separated Values (CSV) file and Student Login System

Previous Page                                                                                                                           Next Page

In this application we have two scenarios where we read CSV files. First to read Students data and second to read books data. Students need to provide student id to login application. We read the students data from csv file and compare the student id. Also, we read large set of books data from csv file.

Sample student csv data:



Sample books csv data:


The header file loadCsvData.h is written to load csv files student data and books data. There are four main functions which reads the files.


static int getStudentID(char stuId[MAX_ID], struct stuProfile *st);
static int  loadStuValues(char *line, char *sFields[STU_COL_NUM]);
int readBooks();
static int  loadBookValues(char *line, char *lFields[BK_COL_NUM]);
int getRowCount(FILE *fpl);

Part 2: Library management in C | Username/Password Login System and Manage Admin Accounts

Previous Page                                                                                                                              Next Page

In this part, we will learn the techniques to implement a username and password login system and manage user accounts.

When a user runs the application for the first time in admin mode, the application requests the user to create an admin account. However, from the second run onwards, the user has to log in using their account details. After logging into admin mode, the user can add or modify multiple admin accounts. To identify the application’s first run, it will check if the admin account file exists in the system. If the file doesn’t exist, then the application calls the create account function. Otherwise, if the file exists, it will call the Admin login function.


int checkFirstLogin(){
    int flag=1;

    fa = fopen(DATA_FILE,"rb");

    if(fa!= NULL){
        flag= 0;
    }
    fclose(fa);

    return flag;

}

Part 1: Library management in C | Flowchart and Function Stack Call Diagram

Previous Page                                                                                                                            Next Page

The application is represented by three mainMenu, adminMenu and studentMenu flowchart. The mainMenu flowchart represents the options provided to the user to choose application mode and user security. The adminMenu flowchart represents the all the tasks that administrator can perform, and the studentMenu flowchart represents the tasks that students can perform.

Main Menu flowchart

Friday, November 3, 2023

Chapter 2: Contact Management in C | File Handling

 <<Previous Chapter

If you remember we have categoried all the functions into two types user functions and operational functions. Here I will explain the operational function and its usage in user functions one by one.

First, let's define Variables and Data Structure.


// Define Constant Variables
#define ESC 27
#define MAX_NAME_SZ 15
#define MAX_NUM_SZ 25
#define READ_ARRAY_SZ 15
#define DATA_FILE "dataFile.dat"
#define TEMP_FILE "tempFile.dat"

//Define data structure

struct data{
    char fName[MAX_NAME_SZ];
    char lName[MAX_NAME_SZ];
    char mPhone[MAX_NUM_SZ];
    char wPhone[MAX_NUM_SZ];
    char hPhone[MAX_NUM_SZ];
};
We will use struct data types to store contact information. It has only five fields First Name (fName), Last Name (lName), Mobile Phone (mPhone), Work Phone (wPhone), Home Phone (hPhone), and all these variables are char types. We can't set primary key as in database but we will choose Mobile Phone i.e mPhone as a primary key and will make sure that Mobile Phone number will not be a null value or duplicate while adding data into the file.

Wednesday, November 1, 2023

Chapter 1: Contact Management in C | Flow Chart and Functions

<<Previous Chapter                                                                                                            Next Chapter>> 

Application Flow Chart:




Functions: 
We will divide the above application into two kinds of functions. The first type of function is user functions which interact with the user to get input and display output, the second type of function is operational functions which do the actual tasks. 

The list of user functions is as follows:
  • mainMenu(): It displays the options to the user. 
  • viewItems(): It displays the list of contact information on the screen. 
  • addItems(): It requests the user to input contact information added to the file.
  • updateItems(): It requests the user to update the contact information in the file.
  • deleteItems(): It requests the user to delete the contact information in the file.
  • readData(): It requests the user to input contact information.

Saturday, March 28, 2020

Quiz Game in C Part 3: Final Game Play and score



In previous articles, we created functions, multi-dimensional character array to store questions, options, and answers. Up to this point, we have everything ready to finish gameplay.
Here we will use the following techniques:

  • Create for loop to display question one by one
  • Create another infinite loop inside for loop to check the answer given by the user. The loop breaks only if the user-provided an answer is within options (a, b, c and d)  otherwise it will loop infinitely. 
  • Calculate the score for the correct answer provided.
  • Use gotoxy to manage text indentation.

Quiz game in C Part 2: Multi-dimensional C array

Previous Page                                                                                                                    Next Page


In this article, we will discuss the gameplay() function but not all only the usages of one dimension, two-dimension, and third dimension character array. Choosing the correct dimension of the array is very important to store information effectively. We have to display a question, four options and store the correct answer to compare the answer provided by the user. Remember these three information are connected to each other if we mismatch the order then the game will go wrong. 
Here, we will declare three character array to store questions, four options, and answer in the same order of the array index.

Question is a string which is an array of character and we will ask 10 questions in total. We create a two-dimension character array, the first index is a total number of questions i.e 10 and the second index is the length of a string.
    char question[10][250];
    strcpy(question[0], "This is question no 1");
    strcpy(question[1], "This is question no 2");
    strcpy(question[2], "This is question no 3");
    strcpy(question[3], "This is question no 4");
    strcpy(question[4], "This is question no 5");
    strcpy(question[5], "This is question no 6");
    strcpy(question[6], "This is question no 7");
    strcpy(question[7], "This is question no 8");
    strcpy(question[8], "This is question no 9");
    strcpy(question[9], "This is question no 10");
We can't assign string using "=" to the two-dimension array and correct way to use it is strcpy() function.

Quiz Game in C part 1 - Flow Chart and Main Menu


Previous Page                                                                                                                           Next Page


Application Flow Chart:

Start: Quiz program start
Main Menu: Program display menu to the user to start the game or to quit.
User Input: The application stops to get user input.
Decision Tree: If user input is S then Quiz game start else if user input is Q then the program will quit.
Quiz Game: User gets 10 questions one by one and each correct score is marked as 1.
Display Score: It display final score after ending the game and the user is directed to the main menu.
Stop: End of the game.

Sunday, August 5, 2012

C project on Medical Store Management System with source

This is large and complete c project built for medical store management system. In this project you can keep details of customer , suppliers and medicine. You can view the report and billing information also. You can add,edit, delete and search the record also. This project is also console application without graphics compile in code::blocks IDE with MinGW compiler.
Whole project is completely based on file handling all the record are store in file. You learn how to store the data ,editing data, searching data and deleting data using file. You can see the following feature in this projects.
1. Supplier Info
2.Customer Info
3.Medicine
4.Report
5.Bill

Thursday, June 28, 2012

Code::blocks Project Bank Management System in C programming

Bank Management System project is design and programmed by Ravi Agrawal, Sagar Sharma and Sawal Maskey student of IOE as a first year mini project in c. This program may not be used as a Banking software but programmer tries to implement all the features of Bank. Program is completely password protected and has a two mode Admin and Staff mode. Bank administrator can login as admin user name is “admin” and password is “ioe” for admin mode. For staff mode three  user name is available which is written in USER.DAT which you can see download this project. The list of user name and passwor for staff mode is given below: 

School Project Personal Diary Management in C programming

This project is similar to the project Contact Management in C. In this project, I am reusing all the code from it. I created this Personal Diary Management project just by renaming printed messages, adding a few functions, and modifying existing functions slightly.

Please go through the Contact Management project if you haven't. In this project, I have explained the techniques of file handling in C.

So, in this project, I will explain the changes that I have made.

Let's start with describing data structure.
// Define Constant Variables
#define ESC 27
#define REF_SZ 10
#define DATE_SZ 64
#define MIN_TEXT_SZ 50
#define MAX_TEST_SZ 500
#define READ_ARRAY_SZ 15
#define DATA_FILE "dataFile.dat"
#define TEMP_FILE "tempFile.dat"

//Define data structure

struct data{
    char refNum[REF_SZ]; //Unique reference number and auto-incremented
    char noteDate[DATE_SZ]; //Auto populated using system date and time
    char eventDate[DATE_SZ]; //Event date
    char location[MIN_TEXT_SZ]; //Location of event happened
    char eventDesc[MIN_TEXT_SZ]; //Event short description
    char notes[MAX_TEST_SZ]; //Notes of the Event
};
I am using 6 variables in a structure. The variable "refNum" will be unique and it is auto-increment. The variable "noteDate" is to store note added date and it is also auto-populated using system date and time. 

Other variables are:
  • eventDate: Event date. It can be any format chosen by the user
  • location: Location of event happened.
  • eventDesc: Event short description.
  • notes: Notes of the event. Maximum character is 500.
Although the variable refNum is auto-incremented, I haven't defined it as an integer. Rather than storing number value only, I decided to add '#R' as an initial character so that the unique reference value will look like "#R10001" instead of "1000".

To achieve this we have to create two separate small functions which I will describe below.

Function: getNextRef()
//Get next reference number

int getNextRef(){

    struct data a;
    int num=0;
    fp = fopen(DATA_FILE,"rb");

    if(fp!= NULL){

        fseek(fp,0,SEEK_END);

        fseek(fp,ftell(fp)-sizeof(a),0);
        fread(&a,sizeof(a),1,fp);

        // converting string to number
        for (int i = 0; a.refNum[i + 2] != '\0'; i++) {
            num = num * 10 + (a.refNum[i + 2] - 48);
        }
        fclose(fp);
        return num;

    } else {

        return 10000;
    }
}
This function will read the last item from the file and read the reference number which is the previous reference number and also the highest value. It will remove the first two characters, convert the remaining numbers into an integer data type, and return it. This function will be executed at the start of the application so if it does not find a file then it will return 1000. 

Function: calRefNum(char *buff, int num)
//Calculate next reference number
static void calRefNum(char *buff, int num){

    char tmpRef[REF_SZ];
    char refNum[REF_SZ] = {'#','R'};
    sprintf(tmpRef,"%d",num);
    strcat(refNum, tmpRef);
    strcpy(buff,refNum);
}
This function converts the reference number into char data type, concatenates with the "#R" initial character, and assigns it to a character pointer which is used while adding notes.

Apart from these changes I have made a few changes in readData(), add(), and view() functions. Once you compile and run it you will understand the changes.

Please download the source code from the GitHub Download Source Code.

You can also watch a video about this project on YouTube.


Telecom Billing Management System in c with source code

This Mini project is compile in gcc compiler with code::blocks IDE. This project can be a good reference for those student who are doing there school project in c.Architecture of this project is very simple and easy to understand the code. Just file handling is used to store the data and corresponding function are made to manipulate the data.
The tasks provide in this program are:-
1. A : for adding new records.
2. L : for list of records.
3. M : for modifying records.
4. P : for payment.
5. S : for searching records.
6. D : for deleting records.
User are provide the above tasks.They can add records,modify and view records. Searching and deleting facilities is also provided.

Download Project from GitHub