Advertisement
Guest User

puzzle tile picture game

a guest
Jul 23rd, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.62 KB | None | 0 0
  1. using System;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. using System.Threading;
  5. using System.IO;
  6. namespace puzzle_game
  7. {
  8.     public partial class Form1 : Form
  9.     {
  10.         Button[,] btns;
  11.         int[] blank = new int[2];
  12.         Image[] cropped = new Image[9];
  13.         Point[] btnlocation;//pre determined locations for buttons, for resetting
  14.         Boolean isPlaying = false;
  15.         Image splitdimg;
  16.         String splitdImgfilename = "";
  17.         Bitmap btndefault = new Bitmap("res/button.png");
  18.         Bitmap blankbtn = new Bitmap("res/blank.png");
  19.         public Form1()// initialises the btns, bntlocation and calls movetiles()
  20.         {
  21.             InitializeComponent();
  22.             btns = new Button[3, 3] { { btn1, btn2, btn3 }, { btn4, btn5, btn6 }, { btn7, btn8, btn9 } };
  23.             btnlocation = new Point[9]{btn1.Location,btn2.Location,btn3.Location,btn4.Location,btn5.Location,btn6.Location,btn7.Location,btn8.Location,btn9.Location};
  24.             movetiles();
  25.         }
  26.         private void movetiles()//randomly moves tiles to simulate 500 mouse clicks on random adjacent(to the blank) tiles, ensures winnability
  27.         {   Random rdm = new Random();
  28.             int tmp=0;
  29.             isPlaying = false;
  30.             if (splitdimg != null)
  31.             {LoadImage(splitdimg);}
  32.             reset();
  33.             for (int l = 0; l < 500; l++)//simulating the 500 clicks
  34.             {   tmp = rdm.Next(0, 5);
  35.                 try
  36.                 {
  37.                     switch (tmp)//moving the blank
  38.                     {
  39.                         case 1:
  40.                             check(blank[0] + 1, blank[1]);
  41.                             break;
  42.                         case 2:
  43.                             check(blank[0] - 1, blank[1]);
  44.                             break;
  45.                         case 3:
  46.                             check(blank[0], blank[1]-1);
  47.                             break;
  48.                         case 4:
  49.                             check(blank[0], blank[1]+1);
  50.                             break;
  51.                     }
  52.                 }catch (Exception){}
  53.             }
  54.             lblwin.Text = "";
  55.             isPlaying = true;
  56.         }
  57.         private void swap(int chk1, int chk2)//simply changes the text value of one button to another, specifically the button pressed to the blank and vice versa
  58.         {   btns[blank[0], blank[1]].Text = btns[chk1, chk2].Text;//changes blank to the button pressed
  59.             btns[blank[0], blank[1]].Tag = btns[chk1, chk2].Tag;
  60.             if (splitdimg == null){//swapping background image/setting to blank
  61.                 btns[blank[0], blank[1]].BackgroundImage = btndefault;
  62.             }else{
  63.                 btns[blank[0], blank[1]].BackgroundImage = btns[chk1, chk2].BackgroundImage;
  64.             }
  65.  
  66.             btns[chk1, chk2].BackgroundImage = blankbtn;
  67.             blank[0] = chk1;//changes button pressed to the blank  
  68.             blank[1] = chk2;
  69.             btns[chk1, chk2].Text = "";//the button pressed becomes the blank
  70.             btns[chk1, chk2].Tag = "";
  71.         }
  72.         private bool wincheck()//checks if the game is won
  73.         {
  74.             bool iswin = false;
  75.             int winincr = 1;
  76.             for (int i = 0; i <= 2; i++)//the first dim of the array
  77.             {
  78.                 for (int n = 0; n <= 2; n++)//second dim
  79.                 {
  80.                     if (!(winincr >= 9))//check for last button, basically if it gets to the 9th one it should be blank, and you should win.
  81.                     {
  82.                         if (btns[i, n].Tag != winincr.ToString())//because the win is 1,2,3,4 etc the next button should correspond to a incrament of 1 each time,
  83.                         { //so if it is not then you loose and the loop breaks
  84.                             iswin = false;
  85.                             i = 10;
  86.                             break;
  87.                         }else{iswin = true;}//if they are the same each time then the method will return true, meaning a win
  88.                     }
  89.                     winincr++;
  90.                 }
  91.             }
  92.             return iswin;
  93.         }
  94.         private void check(int chk1,int chk2)//checks to see if the blank space is next to the button press and also calls wincheck
  95.         {//since the parameters are the buttons array coords:
  96.             if (((blank[0] + 1) == chk1) && (blank[1] == chk2)){//checks to see if the blank is to the direct bottom of the button pressed
  97.                 swap(chk1, chk2); }
  98.             else if (((blank[0] - 1) == chk1) && (blank[1] == chk2)){//to the top
  99.                 swap(chk1, chk2); }
  100.             else if ((blank[0] == chk1) && ((blank[1] + 1) == chk2)){//to the right
  101.                 swap(chk1, chk2);}
  102.             else if ((blank[0] == chk1) && ((blank[1] - 1) == chk2)) {//and to the left of the blank
  103.                 swap(chk1, chk2); }//if the button pressed is next to the blank then they are swapped
  104.             if (wincheck() && isPlaying){//checks win each button press because when else would you do it
  105.                 onWin();
  106.             }else{
  107.                 lblwin.Text = "";}
  108.         }
  109.         private void onWin()//what happens when the game is won
  110.         {
  111.             lblwin.Text = "YOU ARE WINNER, HAHAHA";
  112.             for (int i = 0; i <= 2; i++)
  113.             {
  114.                 for (int l = 0; l <= 2; l++)//disables all the tiles cause the game is won
  115.                 {btns[i, l].Enabled = false;}
  116.             }
  117.             if (splitdimg != null)
  118.                 btns[2, 2].BackgroundImage = cropped[8];//makes it so full image appears on win, if image is loaded
  119.         }
  120.         private void btn1_Click(object sender, EventArgs e){ check(0, 0); }//buttons simply send their array coordinates to the check function
  121.         private void btn2_Click(object sender, EventArgs e){ check(0, 1); }
  122.         private void btn3_Click(object sender, EventArgs e){ check(0, 2); }
  123.         private void btn4_Click(object sender, EventArgs e){ check(1, 0); }
  124.         private void btn5_Click(object sender, EventArgs e){ check(1, 1); }
  125.         private void btn6_Click(object sender, EventArgs e){ check(1, 2); }
  126.         private void btn7_Click(object sender, EventArgs e){ check(2, 0); }
  127.         private void btn8_Click(object sender, EventArgs e){ check(2, 1); }
  128.         private void btn9_Click(object sender, EventArgs e){ check(2, 2); }
  129.         private void btnshuffle_Click(object sender, EventArgs e){ movetiles(); }//allows player to reset/change game if they're a casual
  130.         private void reset()//resets buttons to a win or default position
  131.         {   int iter=1;
  132.             for (int i = 0; i <= 2; i++)//sets the buttons to default for simulating, especially for shuffle button(sets buttons 1-8 then blank)
  133.             {
  134.                 for (int n = 0; n <= 2; n++)
  135.                 {
  136.                     btns[i, n].Enabled = true;
  137.                     if (iter == 9)
  138.                     {
  139.                         btns[i, n].Text = "";
  140.                         btns[i, n].Tag = "";
  141.                         blank[0] = i;
  142.                         blank[1] = n;
  143.                     }else{
  144.                         if (splitdimg == null)
  145.                         {
  146.                             btns[i, n].Text = iter.ToString();
  147.                         }
  148.                         else
  149.                         {
  150.                             btns[i, n].Text = "";
  151.                         }
  152.                         btns[i, n].Tag = iter.ToString();
  153.                         iter++;
  154.                     }
  155.                 }
  156.             }
  157.         }
  158.         private void saveGame()// Saves the game to a binary file
  159.         {
  160.             SaveFileDialog savedialg = new SaveFileDialog();// created dialog for users to create a specific file
  161.             savedialg.Filter = "Binary Files (*.bin)|*.bin"; // setting filters/ asthetics
  162.             savedialg.Title = "Create/select file to save to";
  163.             savedialg.CreatePrompt = true;
  164.             savedialg.ShowDialog();
  165.             Stream save = savedialg.OpenFile();
  166.             BinaryWriter writr = new BinaryWriter(save);// opens a new binarywriter using the newly created file
  167.             if (splitdimg != null)//if there is a picture loaded then the filename is saved too
  168.             {
  169.                 writr.Write(splitdImgfilename);
  170.             }
  171.             else
  172.             {
  173.                 writr.Write("none");
  174.             }
  175.             for (int i = 0; i <= 2; i++)
  176.             {
  177.                 for (int l = 0; l <= 2; l++)
  178.                 {
  179.                     if (btns[i, l].Text == "")// writing the buttons in order
  180.                     {
  181.                         writr.Write(9);
  182.                     }
  183.                     else
  184.                     {
  185.                         writr.Write(Int32.Parse(btns[i, l].Text));
  186.                     }
  187.                 }
  188.             }
  189.             savedialg.Dispose();
  190.             save.Close();
  191.             writr.Close();
  192.         }
  193.         private void loadGame()// loads the game from a binary file
  194.         {
  195.            OpenFileDialog dialg = new OpenFileDialog();
  196.            dialg.Filter = "Binary Files(*.bin)|*.bin";
  197.            dialg.ShowDialog();
  198.            if (dialg.FileName == null || dialg.FileName == "")
  199.            {
  200.                return;
  201.            }
  202.            Stream load = dialg.OpenFile();
  203.            BinaryReader bReadr = new BinaryReader(load);//creates a new binaryreader using the user specified file
  204.            Int32 tmpint = 0;
  205.            try
  206.            {
  207.                splitdImgfilename = bReadr.ReadString();
  208.                if (splitdImgfilename != "none")
  209.                {
  210.                    splitdimg = new Bitmap(splitdImgfilename);// tries to load a saved image
  211.                }
  212.                Loadcrops(splitdimg);
  213.            }
  214.            catch (Exception)
  215.            {
  216.                
  217.            }
  218.            for (int i = 0; i <= 2; i++)
  219.            {
  220.                for (int l = 0; l <= 2; l++)
  221.                {
  222.                    tmpint = bReadr.ReadInt32();//loads the next value into a temp
  223.                    if (tmpint == 9)// sets the buttons to the loaded order
  224.                    {
  225.                        blank[0] = i;
  226.                        blank[1] = l;
  227.                        btns[i, l].BackgroundImage = blankbtn;
  228.                        btns[i, l].Text = "";
  229.                    }
  230.                    else
  231.                    {
  232.                        if (splitdimg != null)
  233.                        {
  234.                            btns[i, l].BackgroundImage = cropped[tmpint - 1];
  235.                            btns[i, l].Text = "";
  236.                        }
  237.                        else
  238.                        {
  239.                            btns[i, l].BackgroundImage = btndefault;
  240.                            btns[i, l].Text = tmpint.ToString();
  241.                        }
  242.                    }
  243.                }
  244.            }
  245.            load.Close();
  246.            bReadr.Close();
  247.         }
  248.         private static Image cropImage(Image img, Rectangle cropArea)//crops specified image using specified rect, returns cropped image
  249.         {   Bitmap bmpCrop =null;
  250.             try
  251.             {   Bitmap bmpImage = new Bitmap(img);
  252.                 bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);//creates a clone of the area essentially cropping it
  253.             }
  254.             catch (Exception ex)
  255.             {MessageBox.Show(ex.Message + " rect h" + cropArea.Height + " w" + cropArea.Width + " x" +cropArea.X + " y" + cropArea.Y ); }
  256.             GC.Collect();
  257.             return (Image)(bmpCrop);
  258.         }
  259.         private void Loadcrops(Image img)//crops a picture using the cropimage function and puts them into an array
  260.         {
  261.             int hres = img.Width / 3, vres = img.Height / 3;
  262.             int iter = 0;
  263.                 for (int i = 0; i <= 2; i++)
  264.                 {
  265.                     for (int l = 0;l <= 2; l++)
  266.                     {
  267.                         Rectangle rec = new Rectangle(hres * l, vres * i, hres, vres);
  268.                         cropped[iter] = cropImage(img, rec);
  269.                         iter++;
  270.                         btns[i, l].Top = (124 * i) + 100;
  271.                         btns[i, l].Left = (124 * l) + 100;
  272.                         btns[i, l].Size = new Size(124, 124);
  273.                     }
  274.                 }
  275.         }
  276.         private void LoadImage(Image img)//Loads the cropped array into the buttons
  277.         {  
  278.             splitdimg = img;
  279.             int iter=0;
  280.             Loadcrops(splitdimg);
  281.                 for (int i = 0; i <= 2; i++)
  282.                 {
  283.                     for (int l = 0; l <= 2; l++)
  284.                     {
  285.                         if (!(i == 2 && l == 2))
  286.                         {
  287.                             btns[i, l].BackgroundImage = cropped[iter];
  288.                         }
  289.                         iter++;
  290.                         btns[i, l].Top = (124* i) + 100;
  291.                         btns[i, l].Left = (124  * l) + 100;
  292.                         btns[i, l].Size = new Size(124, 124);
  293.                     }
  294.             }
  295.         }
  296.         private void btnload_Click(object sender, EventArgs e)//creates a dialog for a user to load an image, then loads/shuffles tiles
  297.         {   OpenFileDialog dialg = new OpenFileDialog();
  298.             dialg.Title="Open Image";
  299.             dialg.Filter = "Image Files (*.bmp*.jpg; *.jpeg; *.bmp; *.png)|*.jpg; *.jpeg; *.bmp; *.png";
  300.             dialg.ShowDialog();
  301.             if (dialg.FileName != ""){
  302.                 splitdimg = new Bitmap(dialg.FileName);
  303.                 splitdImgfilename = dialg.FileName;
  304.                 for (int i = 0; i <= 2; i++)
  305.                 {
  306.                     for (int n = 0; n <= 2; n++)
  307.                     {
  308.                         btns[i, n].Text = "";
  309.                     }
  310.                 }
  311.                 movetiles();}//load/shuffle
  312.         }
  313.         private void btnreset_Click(object sender, EventArgs e)//resets the game back to default, and shuffles
  314.         {   int iter=0;
  315.             splitdimg = null;
  316.             for (int i = 0; i <= 2; i++)
  317.             {
  318.                 for (int l = 0; l <= 2; l++)//reseting the game
  319.                 {
  320.                     btns[i,l].Location = btnlocation[iter];//pre-determined locations being loaded
  321.                     btns[i, l].Size = new Size(96, 96);
  322.                     btns[i, l].BackgroundImage = btndefault;
  323.                     iter++;
  324.                 }  
  325.             }
  326.             movetiles();
  327.         }
  328.         private void btnsave_Click(object sender, EventArgs e){saveGame();}
  329.         private void btnloadgame_Click(object sender, EventArgs e){ loadGame(); }
  330.     }
  331. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement