Minesweeper Game for Mac OS written in Cocoa, Objective C

Minesweeper Game for Mac OS written in Cocoa, Objective C (Part 1)

Created By: Debasis Das (14-Oct-2014)

Minesweeper Definition (Source Wiki)

(Minesweeper is a single-player puzzle video game. The objective of the game is to clear a rectangular board containing hidden “mines” without detonating any of them, with help from clues about number of neighboring mines in each field. The game originates from the 1960s, and has been written for many computing platforms in use today. It has many variations and offshoots.)

 

In this sample application we will create a Minesweeper application in Cocoa, Objective C.

  1. Player can choose the grid size (currently is square n*n) – Default is set to 10* 10 which player can change and start a new game.
  2. Check All – Chit Code to show all the mines
  3. As this is a sample code, the game does not stop when player hits a mine.
  4. Flood Field has not been implemented (Will be implemented in Part 2)
  5. Score count will be done in Part 2
  6. Time tracking will be done in Part 2

Note: This application including the logic, Code and UI was developed under 2 hrs so definitely there would scope of improvement.

Final Output of the Code

MineSweeper1010

Minesweeper – 10* 10 Grid

MineSweeper2020

Minesweeper – 20 * 20 Grid

//
//  AppDelegate.h
//  DDMinesweeper
//
//  Created by Debasis Das on 10/14/14.
//  Copyright (c) 2014 Knowstack. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject 

@property (nonatomic, assign) IBOutlet NSView *placeholderView;
@property (nonatomic, assign) IBOutlet NSTextField *gridSizeTextField;
@property (nonatomic, retain) NSMutableArray *mainDataArray;

@end

 

 

//
//  AppDelegate.m
//  DDMinesweeper
//
//  Created by Debasis Das on 10/14/14.
//  Copyright (c) 2014 Knowstack. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@property (weak) IBOutlet NSWindow *window;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self.gridSizeTextField setIntValue:10];
    [self createNewGame];
}

-(IBAction)newGame:(id)sender
{
    while([[self.placeholderView subviews] count] > 0) {
        [[[self.placeholderView subviews] objectAtIndex:0] removeFromSuperview];
    }
    [self createNewGame];
}

-(IBAction)testGame:(id)sender
{
    for (NSButton *but in self.placeholderView.subviews)
    {
        int index = [[but identifier] intValue];
        NSDictionary *dict = [self.mainDataArray objectAtIndex:index];
        if ([[dict objectForKey:@"hasBomb"] intValue] == 1)
        {
            [[but cell] setImageScaling:NSImageScaleProportionallyUpOrDown];
            [but setImage:[NSImage imageNamed:@"gnome-mines"]];
        }
        else
        {
            [but setTitle:[dict objectForKey:@"neighborBombScore"]];
        }
    }
}
-(void)createNewGame
{
    NSMutableArray *dataArray = [NSMutableArray new];
    int gridNos = [self.gridSizeTextField intValue];
    int horizonalGrids = gridNos;
    int verticalGrids = horizonalGrids;
    int totalGridNumber = horizonalGrids * verticalGrids;
    
    for (int i = 0; i < totalGridNumber ; i++ )
    {
        NSMutableDictionary * mDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       [NSNumber numberWithInt:i],@"index",
                                       [NSNumber numberWithBool:NO],@"hasBomb",
                                       [NSNumber numberWithInt:0],@"neighborBombScore"
                                       , nil];
        [dataArray addObject:mDict];
    }
    
    NSMutableArray *randomNumberArray = [NSMutableArray new];
    while(randomNumberArray.count != gridNos * 4)
    {
        NSNumber *randomNumber = [NSNumber numberWithInt:arc4random()% totalGridNumber];
        if (![randomNumberArray containsObject:randomNumber])
        {
            [randomNumberArray addObject:randomNumber];
        }
    }
    for (NSNumber *num in randomNumberArray)
    {
        for (NSDictionary *dict in dataArray)
        {
            if ([[dict objectForKey:@"index"] intValue] == [num intValue])
            {
                [dict setValue:[NSNumber numberWithBool:YES] forKey:@"hasBomb"];
            }
        }
    }
    //items to evaluate
    //if Grid is 10 * 10
    /*
     (index - verticalGrids - 1),
     (index - verticalGrids),
     (index - verticalGrids + 1),
     (index - 1),
     (index + 1),
     (index + verticalGrids - 1),
     (index + verticalGrids),
     (index + verticalGrids + 1),
     */
    
    for (NSDictionary *dict in dataArray)
    {
            
            int score = 0;
            int index = [[dict objectForKey:@"index"] intValue];
            
            int index1 = (index - verticalGrids - 1) ;
            int index2 = (index - verticalGrids) ;
            int index3 = (index - verticalGrids + 1)  ;
            int index4 = (index - 1)  ;
            int index5 = (index + 1) ;
            int index6 = (index + verticalGrids - 1) ;
            int index7 = (index + verticalGrids) ;
            int index8 = (index + verticalGrids + 1) ;

            //Four Corners
            if (index == 0)
            {
                score =
                [[[dataArray objectAtIndex:index5] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index7] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index8] objectForKey:@"hasBomb"] intValue];
            }
            else if (index == gridNos - 1)
            {
                score =
                [[[dataArray objectAtIndex:index4] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index6] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index7] objectForKey:@"hasBomb"] intValue];
            }
            else if   (index == gridNos * (gridNos - 1))
            {
                score =
                [[[dataArray objectAtIndex:index2] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index3] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index5] objectForKey:@"hasBomb"] intValue];
            }
            else if  (index == (gridNos * gridNos) - 1)
            {
                score =
                [[[dataArray objectAtIndex:index1] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index2] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index4] objectForKey:@"hasBomb"] intValue];
            }
            else if ((index > 0) && (index < (gridNos - 1)))
            {
                //Row 0
                score =
                [[[dataArray objectAtIndex:index4] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index5] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index6] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index7] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index8] objectForKey:@"hasBomb"] intValue];
            }
            else if ((index > gridNos * (gridNos - 1)) && (index < (gridNos * gridNos) - 1))
            {
                //Row n
                score =
                [[[dataArray objectAtIndex:index1] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index2] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index3] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index4] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index5] objectForKey:@"hasBomb"] intValue];
            }
            else if ((index != 0) &&
                     (index % gridNos == 0) &&
                     (index != (gridNos * (gridNos - 1)))
                     )
            {
                score =
                [[[dataArray objectAtIndex:index2] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index3] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index5] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index7] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index8] objectForKey:@"hasBomb"] intValue];
            }
            else if ((index != gridNos - 1) &&
                     (index % gridNos == gridNos - 1 ) &&
                     (index != (gridNos * gridNos - 1))
                     )
            {
                //Column n
                score =
                [[[dataArray objectAtIndex:index1] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index2] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index4] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index6] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index7] objectForKey:@"hasBomb"] intValue];
                
            }
            else
            {
                score = [[[dataArray objectAtIndex:index1] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index2] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index3] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index4] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index5] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index6] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index7] objectForKey:@"hasBomb"] intValue] +
                [[[dataArray objectAtIndex:index8] objectForKey:@"hasBomb"] intValue];
            }
            [dict setValue:[NSNumber numberWithInt:score] forKey:@"neighborBombScore"];
       
    }
    
    float width = self.placeholderView.frame.size.width / horizonalGrids;
    float height = self.placeholderView.frame.size.height / horizonalGrids;
    int gridCount = 0;
    for (int i =0 ; i < verticalGrids; i++)
    {
        for (int j =0 ; j < horizonalGrids; j++)
        {
            NSButton *but = [[NSButton alloc] initWithFrame:NSMakeRect(j*width, self.placeholderView.frame.size.height-height - (i*height), width, height)];
            [but setFont:[NSFont fontWithName:@"Helvetica" size:22.0]];
            [but setAction:@selector(showDetails:)];
            [but setIdentifier:[NSString stringWithFormat:@"%d",gridCount]];
            [but setTitle:@""];
            [self.placeholderView addSubview:but];
            gridCount ++;
        }
    }
    [self setMainDataArray:dataArray];
}
-(IBAction)showDetails:(id)sender
{
    NSLog(@"sender identifier %@",[sender identifier]);
    NSDictionary *dict = [self.mainDataArray objectAtIndex:[[sender identifier] intValue]];
    
    if ([[dict objectForKey:@"hasBomb"] intValue] == 1)
    {
        [[(NSButton *)sender cell] setImageScaling:NSImageScaleProportionallyUpOrDown];
        [(NSButton *)sender setImage:[NSImage imageNamed:@"gnome-mines"]];
    }
    else
    {
        [(NSButton *)sender setTitle:[dict objectForKey:@"neighborBombScore"]];
    }
    //[(NSButton *)sender setButtonType:NSMomentaryPushInButton];
    
}
@end

 

Posted in algorithms, Cocoa, Objective C Tagged with: , , , ,
0 comments on “Minesweeper Game for Mac OS written in Cocoa, Objective C
1 Pings/Trackbacks for "Minesweeper Game for Mac OS written in Cocoa, Objective C"

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news