Programing/IOS

숫자야구 게임으로 앱 흉내내기

프띠버리 2013. 8. 20. 17:30






NumberBaseball2.zip



소스 부분

ViewController.h

//

//  ViewController.h

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface ViewController : UIViewController


- (IBAction)playball;

- (IBAction)help;


@end


ViewController.m

//

//  ViewController.m

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "ViewController.h"

// 게임과 도움 헤더파일 포함

#import "playball.h"

#import "help.h"


@interface ViewController ()


@end


@implementation ViewController


// 게임 시작 화면으로 이동

- (IBAction)playball

{

    playball *view = [[playball alloc] initWithNibName:@"playball" bundle:nil];

    view.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    [self presentViewController:view animated:YES completion:nil];

}


// 도움말 화면으로 이동

- (IBAction)help

{

    help *view = [[help alloc] initWithNibName:@"help" bundle:nil];

    view.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    [self presentViewController:view animated:YES completion:nil];

}


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


help.h

//

//  help.h

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface help : UIViewController


- (IBAction)mainmenu;


@end


help.m

//

//  help.m

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "help.h"


@interface help ()


@end


@implementation help


// 메인화면으로 돌아가기

- (IBAction)mainmenu

{

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


playball.h

//

//  playball.h

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>

// 사운드를 위해  AVAFound 포함

#import <AVFoundation/AVFoundation.h>


@interface playball : UIViewController<AVAudioPlayerDelegate>

{

    AVAudioPlayer *theAudio;

}


@property (strong, nonatomic) IBOutlet UITextField *InputNum1;

@property (strong, nonatomic) IBOutlet UITextField *InputNum2;

@property (strong, nonatomic) IBOutlet UITextField *InputNum3;

@property (strong, nonatomic) IBOutlet UITextView *viewText;

- (IBAction)btnHit:(id)sender;


- (IBAction)mainmenu;


@end


playball.m

//

//  playball.m

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "playball.h"


@interface playball ()


@end


@implementation playball

@synthesize InputNum1;              // 텍스트필드 1 정의

@synthesize InputNum2;              // 텍스트필드 2 정의

@synthesize InputNum3;              // 텍스트필드 3 정의

@synthesize viewText;               // 텍스트뷰 정의

NSString *result;                   // 결과를 보여줄 문자열 전역으로 정의

NSNumber *nnum1;                    // 랜덤 생성할 1 숫자

NSNumber *nnum2;                    // 랜덤 생성할 2 숫자

NSNumber *nnum3;                    // 랜덤 생성할 3 숫자

int count = 0;                      // 카운트 표시


- (IBAction)btnHit:(id)sender {

    // 스트라이크와 볼을 구하기 위한 변수 선언

    int ball = 0, strick = 0;

    

    // 텍스트 필드로 입력 받은 넘기기

    NSNumber *num1 = [[NSNumber alloc] initWithInt:[InputNum1.text intValue]];

    NSNumber *num2 = [[NSNumber alloc] initWithInt:[InputNum2.text intValue]];

    NSNumber *num3 = [[NSNumber alloc] initWithInt:[InputNum3.text intValue]];

    

    // 배열에 텍스트 필드로 받은 넣기

    NSArray *intNum = [NSArray arrayWithObjects: num1, num2, num3, nil];

    

    // 랜덤 숫자 배열에 넣기

    NSArray *resNum = [NSArray arrayWithObjects: nnum1, nnum2, nnum3, nil];

    

    // 텍스트 필드가 공백일때

    if([InputNum1.text isEqualToString:@""] || [InputNum2.text isEqualToString:@""] || [InputNum3.text isEqualToString:@""])

    {

        viewText.text = @"공백은 입력할수 없습니다.";

        NSLog(@"빈칸이랑께");

    }

    // 텍스트 필드에 문자가 입력되었을때

//    else if(![InputNum1.text intValue] || ![InputNum2.text intValue] || ![InputNum3.text intValue])

//    {

//        viewText.text = @"문자는 입력할수 없습니다.";

//        NSLog(@"문자시져");

//    }

    // 텍스트 필드의 숫자가 두자리 이상일때

    else if([InputNum1.text intValue] > 9 || [InputNum2.text intValue] > 9 || [InputNum3.text intValue] > 9)

    {

        viewText.text = @"숫자는 한자리수만 가능합니다.";

        NSLog(@"숫자많앙");

    }

    // 텍스트 필드의 숫자가 중복되었을때

    else if([InputNum1.text intValue] == [InputNum2.text intValue] || [InputNum1.text intValue] == [InputNum3.text intValue] || [InputNum2.text intValue] == [InputNum3.text intValue])

    {

        viewText.text = @"중복된 숫자는 사용할수 없습니다.";

        NSLog(@"중복이양");

    }

    // 모든 예외체크를 통과 했다면

    else

    {

        count = count + 1;

        // 스트라이크와 볼을 구하는 부분

        for(int i=0;i<3;i++)

        {

            // 입력받은 수와 지정된 임의의 수를 비교하여 스트라이크 구하기

            if([intNum objectAtIndex:i] == [resNum objectAtIndex:i])

            {

                strick = strick + 1;                    // 자리와 숫자가 일치하면 스트라이크+1

                NSLog(@"%d 스트라이크", strick);

            }

            

            // 입력받은 수와 지정된 임의의 수를 비교하여 구하기

            if([intNum objectAtIndex:i] != [resNum objectAtIndex:i])

            {

                // 첫번째 숫자 부터 같은지 비교 시작

                for(int j=0;j<3;j++)

                {

                    // 만약 자리가 다르고 같은수가 있다면

                    if([intNum objectAtIndex:i] == [resNum objectAtIndex:j])

                    {

                        ball = ball + 1;                // +1

                        NSLog(@"%d ", ball);

                    }

                }

            }

        }

        

        // 텍스트 필드로 입력받은 숫자와 스트라이크 표시

        NSString *msg = [NSString stringWithFormat:@"%2d : %@ %@ %@ () %d %d 스트라이크 입니다.\n", count, [intNum objectAtIndex:0], [intNum objectAtIndex:1], [intNum objectAtIndex:2], ball, strick];

        

        // 앞의 진행상황을 계속해서 보여줌

        result = [NSString stringWithFormat:@"%@%@", result, msg];

        

        // 뷰텍스트에 표시

        viewText.text = result;

        

    }

    // 3스트라이크가 되었을때 승리창 띄우기

    if(strick == 3)

    {

        // 승리 사운드

        NSString *path = [[NSBundle mainBundle] pathForResource:@"woo" ofType:@"wav"];

        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

        theAudio.delegate = self;

        [theAudio play];

        

        // 경고창

        NSString *msg = [NSString stringWithFormat:@"축하합니다! 당신의 승리입니다."];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You WIN!!" message:msg delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기", nil];

        alert.tag = 11;

        [alert show];

    }

    // 10 동안안에 맞추면 패배창 띄우기

    if(strick !=3 && count == 10)

    {

        // 패배 사운드

        NSString *path2 = [[NSBundle mainBundle] pathForResource:@"boo" ofType:@"wav"];

        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL];

        theAudio.delegate = self;

        [theAudio play];

        

        // 경고창

        NSString *msg = [NSString stringWithFormat:@"당신은 패배하였습니다."];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You LOSE!!" message:msg delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기", nil];

        alert.tag = 12;

        [alert show];

    }

    

    // 텍스트 필드 초기화

    InputNum1.text = @"";

    InputNum2.text = @"";

    InputNum3.text = @"";

    

    // 텍스트 필드 리턴시 자판 내려가기

    [InputNum1 resignFirstResponder];

    [InputNum2 resignFirstResponder];

    [InputNum3 resignFirstResponder];

}


// UIALertView설정

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if(buttonIndex == alertView.firstOtherButtonIndex)

    {

        [self initPlayball];

    }else

    {

        [self mainmenu];

    }

}


// 메인 화면으로 돌아가기

- (IBAction)mainmenu

{

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

 

    [self initPlayball];

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


// 게임 초기화

- (void)initPlayball

{

    // 텍스트 필드에서 자판 번호모양으로 표시

    InputNum1.keyboardType=UIKeyboardTypeNumberPad;

    InputNum2.keyboardType=UIKeyboardTypeNumberPad;

    InputNum3.keyboardType=UIKeyboardTypeNumberPad;

    

    // 텍스트 필드 초기화

    [InputNum1 setText:@""];

    [InputNum2 setText:@""];

    [InputNum3 setText:@""];

    

    // nnum 초기화 시켜주기

    nnum1 = 0;

    nnum2 = 0;

    nnum3 = 0;

    count = 0;

    

    viewText.text = @"";

    

    // 랜덤 숫자 3 구하기

    while(nnum1 == nnum2 || nnum2 == nnum3 || nnum3 == nnum1)

    {

        nnum1 = [[NSNumber alloc] initWithInt:arc4random()%10];

        nnum2 = [[NSNumber alloc] initWithInt:arc4random()%10];

        nnum3 = [[NSNumber alloc] initWithInt:arc4random()%10];

    }

    

    NSLog(@"%@ %@ %@", nnum1, nnum2, nnum3);   // 개발자 CMD화면에 랜덤 찍어보기

    

    // 텍스트 결과창 초기화

    result = @"";


}

@end