How To Make A Game Of 15 Puzzle In C

Introduction

The 15 puzzle is a popular sliding puzzle game where players arrange numbered tiles in a 4×4 grid, with one empty space. The objective is to rearrange the tiles from a given scrambled initial state to reach a target configuration, usually with the numbers arranged in ascending order from left to right, top to bottom.

Implementation

To implement the 15 puzzle game in C, we can use a two-dimensional array to represent the game board. Each element of the array represents a tile, with the value 0 representing the empty space. We can use nested loops to iterate over the array and display the tiles on the screen.

#include <stdio.h>



void displayBoard(int board[][4]) {

for (int i = 0; i < 4; i++) {

for (int j = 0; j < 4; j++) {

printf("%2d ", board[i][j]);

}

printf("\n");

}

}



int main() {

int board[4][4] = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12},

{13, 14, 15, 0}

};



displayBoard(board);



return 0;

}

In the above code, we have defined the displayBoard function that takes the game board as input and prints it on the console. The main function initializes the game board with a sample configuration and calls the displayBoard function to show it on the screen.

Game Logic

To make the game interactive, we need to implement the logic for moving the tiles. This involves taking user input to select a tile and then swapping it with the adjacent empty space. We can use the scanf function to read user input and update the game board accordingly.

#include <stdio.h>



void displayBoard(int board[][4]) {

for (int i = 0; i < 4; i++) {

for (int j = 0; j < 4; j++) {

printf("%2d ", board[i][j]);

}

printf("\n");

}

}



void swapTiles(int board[][4], int row1, int col1, int row2, int col2) {

int temp = board[row1][col1];

board[row1][col1] = board[row2][col2];

board[row2][col2] = temp;

}



int main() {

int board[4][4] = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12},

{13, 14, 15, 0}

};



displayBoard(board);



int row, col;

printf("Enter the row and column of the tile you want to move: ");

scanf("%d %d", &row, &col);



swapTiles(board, row, col, row, col+1);

displayBoard(board);



return 0;

}

In the updated code, we have added the swapTiles function that takes the game board and the positions of two tiles as input. It swaps the positions of the two tiles by using a temporary variable. We have also added user input using the scanf function to select a tile to move, and then called the swapTiles function to perform the swap operation.

Conclusion

By following the steps outlined in this article, you can create a basic implementation of the 15 puzzle game in C. You can further enhance the game by adding features like a random initial configuration, a win condition check, and a graphical user interface using libraries like SDL or OpenGL.

Leave a Comment