Number Puzzle Game (C# Program)
Number Puzzle Game (C# Program)
(C# program)
Step 1 :
Step3 : Delete all the code on Form1.cs and Copy Paste the following code into Form1.cs
Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Number_Puzzle_Game
{
public partial class Form1 : Form
{
private Button[,] buttons;
private int emptyRow, emptyCol;
private int moves;
public Form1()
{
InitializeComponent();
InitializePuzzle();
this.Width = 700;
this.Height = 500;
this.CenterToScreen();
}
if (i == 3 && j == 3)
{
buttons[i, j].Text = "";
emptyRow = i;
emptyCol = j;
}
else
{
buttons[i, j].Text = (i * 4 + j + 1).ToString();
}
Controls.Add(buttons[i, j]);
buttons[i, j].Location = new System.Drawing.Point(j * buttonSize, i * buttonSize);
}
}
if (IsAdjacentToEmpty(clickedPosition))
{
SwapButtons(emptyRow, emptyCol, clickedPosition.Item1, clickedPosition.Item2);
emptyRow = clickedPosition.Item1;
emptyCol = clickedPosition.Item2;
moves++;
UpdateMovesCounter(); // Update moves counter after each move
CheckForWin();
}
}
private void SwapButtons(int row1, int col1, int row2, int col2)
{
string tempText = buttons[row1, col1].Text;
buttons[row1, col1].Text = buttons[row2, col2].Text;
buttons[row2, col2].Text = tempText;
}
return (Math.Abs(row - emptyRow) == 1 && col == emptyCol) || (Math.Abs(col - emptyCol) == 1 && row ==
emptyRow);
}
return validMoves;
}
if (win)
{
MessageBox.Show($"Congratulations! You solved the puzzle in {moves} moves!");
}
}
}
}
Thank you...
David vara