Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private Button _blankButton;
- private Button[] _originalButtons = buttonPanel.Controls.OfType<Button>(); // Store an un-randomized list of them in order
- // For checking results later
- public void form_load() { // Or whatever it's called
- var numbers = Enumerable.Range(1, 8).OrderBy(x => Guid.NewGuid()).ToList(); // Create/Randomize the number list
- var buttons = _originalButtons.OrderBy(x => Guid.NewGuid()).ToList(); // Randomize the button list
- for (var i = 0; i < buttons.Count-1; i++)
- {
- var button = buttons[i];
- button.Text += numbers[i];
- button.Tag = i; // Tag each button to track what position it has in the array
- }
- _blankButton = buttons[buttons.Count-1]; // Save the blankButton for what it is
- _blankButton.Text = " "; // Give it a value so we can treat each of them as a char
- _blankButton.Tag = buttons.Count-1; // Though they all have to get tagged because it could have a number later
- }
- button_click(object sender, EventArgs e) // Assign this same event to all of the buttons in the Designer
- {
- Button clicked = sender as Button;
- if(!string.IsNullOrWhiteSpace(clicked.Text)) {
- // They clicked a button other than the blank one
- // See if the blank one is adjacent
- // It could be either at buttons[i-1], [i+1], [i-3] or [i+3]
- int startPosition = int.Parse(clicked.Tag); // Remember we stored its array position in Tag earlier
- int blankPosition = int.Parse(_blankButton.Tag);
- // Check our 4 possible positions
- if (blankPosition == startPosition - 1 || blankPosition == startPosition - 3 || blankPosition == startPosition + 1 || blankPosition == startPosition + 3) {
- // They have clicked a number that is adjacent to the blank tile
- // Swap the text from one they clicked with the blank tile.
- _blankButton.Text = clicked.Text;
- clicked.Text = " "; // Must have a space value so we can treat it as a char
- _blankButton = clicked;
- // And then check if they have won
- // Do they win only if the blank is in the top left, or can the blank be anywhere?
- // Assuming top left only
- // We actually don't have to cast them from strings, they will compare properly with their ascii char values
- // And null, space, etc are all sorted before the numbers in ASCII too
- int lastValue = 128;
- bool success = true;
- foreach(var button in _originalButtons) { // Iterate the buttons in their original order (reverse order)
- int value = (int)button.Text[0];
- if(value > lastValue)
- { // If any number on the buttons, in reverse, is higher than a previous one, it's not in order
- success = false;
- break;
- }
- else
- lastValue = value;
- // If all of them are lower than their previous ones, it's in order and success stays true
- }
- if (success) {
- // Do whatever you want to do when they win
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement