简单的IOS程序 21点 扑克牌游戏

来源:互联网 发布:苹果mac腾讯视频在哪里 编辑:程序博客网 时间:2024/05/17 08:39

    算是老师的一个作业,也是要给老师查阅的,所以开始了人生第一个关于IOS开发的博客

      还只是一个很弱智的练手小游戏 




      好吧让我们来看下 这个小游戏的界面

    

一个是主界面,负责游戏的运行,还有一个是记录界面,负责游戏的成绩记录 和一个成绩榜单

首先要看主界面 扑克牌的加载



我讲2组UIImageView 分别加入两组集合数组中,用control 相连时 要逐个 按数组顺序 相连 

@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *bankerPokers;@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *myPokers;

然后需要模拟摸牌 下面是从52张牌中随机出一张牌的 代码

</pre><p></p><pre name="code" class="objc">
-(void)setPokers{    int c  =arc4random_uniform(52);    int a = c/13;    int b = c %13;        switch (a) {        case 0:            _randomPoker =[NSString stringWithFormat:@"heart-%d",b+1];            break;        case 1:            _randomPoker =[NSString stringWithFormat:@"club-%d",b+1];            break;        case 2:            _randomPoker =[NSString stringWithFormat:@"diamond-%d",b+1];            break;        case 3:            _randomPoker =[NSString stringWithFormat:@"spade-%d",b+1];            break;        default:            break;    }        if (b >=9) {        b =9;    }    _score = b +1;}-(NSString *) getPokers{    [self setPokers];    return _randomPoker;}-(int)getScore{    [self setPokers];    return _score;}
再在 ViewController 调用Pokers 类中的方法 来得到随机到这个张牌的 NSString 名字 再到 图片中 中添加
     例如 我们初始化 需要 初始化 一张庄家牌,和两张 玩家牌,我们这样初始化
- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    _model =[[Model alloc]init];        Pokers *pokers =[[Pokers alloc]init];    UIImageView *bankerPokers1 =self.bankerPokers[0];    bankerPokers1.image= [UIImage imageNamed:pokers.getPokers];    _model.bankerScore = pokers.score+_model.bankerScore;    self.bankerlabel.text=[NSString stringWithFormat:@"%d",_model.bankerScore];    UIImageView *bankerPokers2 =self.bankerPokers[1];    bankerPokers2.image=[UIImage imageNamed:@"card-back"];        UIImageView *myPoker1 = self.myPokers[0];    myPoker1.image =[UIImage imageNamed:pokers.getPokers];    _model.myScore = pokers.score+_model.myScore;     self.mylabel.text=[NSString stringWithFormat:@"%d",_model.myScore];    UIImageView *myPoker2 = self.myPokers[1];    myPoker2.image =[UIImage imageNamed:pokers.getPokers];    _model.myScore = pokers.score+_model.myScore;     self.mylabel.text=[NSString stringWithFormat:@"%d",_model.myScore];    _model.Score =50;    self.scoreLabel.text =[NSString stringWithFormat:@"%d",_model.Score];}
        其中还有一些 model 类里面 有 玩家手牌点 myScore 以及 庄家手牌点数 bankerScore  还有 一盘游戏的得分(即胜利或者失败所得的分数)。
     
       初始化 结束后,玩家可根据手上已有的牌 来判断 是否要继续 发牌,来使自己更接近21点,每点一次会增加一张随机的牌到手中 代码如下
- (IBAction)fapai:(UIButton *)sender {    Pokers *pokers =[[Pokers alloc]init];        UIImageView *myPoker3 = self.myPokers[2];    UIImageView *myPoker4 = self.myPokers[3];    UIImageView *myPoker5 = self.myPokers[4];        if (myPoker3.image ==nil && myPoker4.image ==nil && myPoker5.image ==nil) {        myPoker3.image =[UIImage imageNamed:pokers.getPokers];        _model.myScore = pokers.score+_model.myScore;        self.mylabel.text=[NSString stringWithFormat:@"%d",_model.myScore];        }else if(myPoker3.image !=nil && myPoker4.image ==nil && myPoker5.image ==nil){        myPoker4.image =[UIImage imageNamed:pokers.getPokers];        _model.myScore = pokers.score+_model.myScore;        self.mylabel.text=[NSString stringWithFormat:@"%d",_model.myScore];           }else if(myPoker3.image !=nil && myPoker4.image !=nil && myPoker5.image ==nil){        myPoker5.image =[UIImage imageNamed:pokers.getPokers];        _model.myScore = pokers.score+_model.myScore;        self.mylabel.text=[NSString stringWithFormat:@"%d",_model.myScore];          }    NSLog(@"score= %d,my =%d ,banker =%d",pokers.score,_model.myScore,_model.bankerScore);}
   
  再 玩家觉得 已经足够 时 可以 点下 停牌 按钮 ,这样触发 程序 庄家开始根据程序设定来 增加牌 并按 Model 类里面的规则 判断是否胜利
- (IBAction)tingpai:(UIButton *)sender {    self.i  =1;            [self performSelector:@selector(zhuangjiafapai) withObject:nil afterDelay:1.0f];    sleep(0.5);    [self performSelector:@selector(zhuangjiafapai) withObject:nil afterDelay:1.0f];    sleep(0.5);    [self performSelector:@selector(zhuangjiafapai) withObject:nil afterDelay:1.0f];    sleep(0.5);    [self performSelector:@selector(zhuangjiafapai) withObject:nil afterDelay:1.0f];    sleep(0.5);    [self performSelector:@selector(rule) withObject:nil afterDelay:1.0f];    NSLog(@"Score %d",_model.Score);    [self performSelector:@selector(score) withObject:nil afterDelay:1.0f];}-(void)score{     self.scoreLabel.text =[NSString stringWithFormat:@"%d",_model.Score];}-(void)rule{     [_model gameRule:_model.myScore andwith:_model.bankerScore];}-(void)zhuangjiafapai{        if (_model.myScore >_model.bankerScore && _model.bankerScore <= 18 ) {                Pokers *pokers =[[Pokers alloc]init];        NSLog(@"i 2= %d",self.i);                UIImageView *bankerPoker = self.bankerPokers[self.i];        bankerPoker.image =[UIImage imageNamed:pokers.getPokers];                _model.bankerScore = pokers.score+_model.bankerScore;        self.bankerlabel.text=[NSString stringWithFormat:@"%d",_model.bankerScore];            }    self.i ++;    }

以上这个停牌程序 自己觉得并不是很理想,设想可以延迟一秒 来发这个牌,但是 自己总是不能实现,也存在着些许疑问‘


 下面是Model 类的代码
-(void)gameRule:(int)myScore andwith:(int)bankerScore{    if ( _myScore >21 ) {            UIAlertView *a =[[UIAlertView alloc]initWithTitle:@"战况" message:@"你输了" delegate:self cancelButtonTitle:@"继续" otherButtonTitles:nil];            [a show];        _Score = _Score -10;            }        if ( _myScore <= _bankerScore && _myScore <= 21 && _bankerScore <= 21) {        UIAlertView *a =[[UIAlertView alloc]initWithTitle:@"战况" message:@"你输了" delegate:self cancelButtonTitle:@"继续" otherButtonTitles:nil];        [a show];        _Score = _Score -10;    }        if (_myScore > _bankerScore && _myScore <= 21 && _bankerScore <= 21 ) {        UIAlertView *a =[[UIAlertView alloc]initWithTitle:@"战况" message:@"你赢了" delegate:self cancelButtonTitle:@"继续" otherButtonTitles:nil];        [a show];        _Score =_Score + 20;    }        if (_myScore <=21 && _bankerScore >21) {        UIAlertView *a =[[UIAlertView alloc]initWithTitle:@"战况" message:@"你赢了" delegate:self cancelButtonTitle:@"继续" otherButtonTitles:nil];        [a show];        _Score = _Score + 20;    }    NSLog(@"model 里面分数%d",_Score);}

主界面中 初始为50的 那个值 即为 Model 中的 Score ,玩家赢了+20,输了-10。然后将这个 值可以 传进 记录界面 里面的当前得分的  presentScore 

这里没用通知中心的方法,用了王达同学告知于我的一个方法
<span style="font-size:14px;">-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{    if ([segue.identifier isEqualToString:@"show"]) {        recordViewController *r1 = [[recordViewController alloc]init];        r1 = segue.destinationViewController;        r1.str = self.scoreLabel.text;        NSLog(@"%@",r1.str);    }   }</span>

其中两个视图相连的segue.identfier 要改下 如图


代码其中r1.str  str是 记录视图 recordViewController 的 一个属性 负责接收要传过去的数据

点击 记录  进入 记录界面后 在用户名一栏中输入自己姓名后,就会保存姓名以及当前分数到数据库中

比较失败的是,点击保存后没能立即刷新,日后有待完善。 上面问题 已得到解决  数据代码如下
- (IBAction)preserve:(UIButton *)sender {        [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.    AppDelegate *appDelegate =[UIApplication sharedApplication].delegate;    NSManagedObjectContext *context =[appDelegate managedObjectContext];        NSError *error;        NSManagedObject *user =[NSEntityDescription insertNewObjectForEntityForName:kUserEntityName inManagedObjectContext:context];    NSString *str =self.presentScore.text;    [user setValue:@([str intValue]) forKey:@"score"];    [user setValue:self.nameField.text forKey:@"name"];        BOOL success = [context save:&error];        if (!success) {        [NSException raise:@"访问数据库错误" format:@"%@",[error localizedDescription]];            }    [appDelegate saveContext];}

取出数据库中的数据放入数组中 再将数组中数据放入 表视图中

先是取出数据库在放入数组中的代码
       AppDelegate * appDelegate = [UIApplication sharedApplication].delegate;    NSManagedObjectContext * context = [appDelegate managedObjectContext];        NSError * error;        NSFetchRequest * request = [[NSFetchRequest alloc]init];        //设置要查询的实体    request.entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];    NSSortDescriptor *sort =[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];    request.sortDescriptors = [NSArray arrayWithObject:sort];        NSArray * objs =[context executeFetchRequest:request error:&error];    self.arr = [NSMutableArray array];    self.arr2 = [NSMutableArray array];    for (id temp in objs) {        [self.arr addObject:[temp valueForKey:@"name"]];        [self.arr2 addObject:[temp valueForKey:@"score"]];    }        if (objs == nil) {        NSLog(@"查询错误");    }

然后就是3个代理需要的方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    return 1;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    if (self.arr.count <=9) {        return self.arr.count;    }else {        return 9;    }}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{       NSString *SimleTableIdentifier =@"Cell";        UITableViewCell *cell =[tableView dequeueReusableHeaderFooterViewWithIdentifier:SimleTableIdentifier];    if (cell == nil) {        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimleTableIdentifier];            }    cell.textLabel.text= [NSString stringWithFormat:@"                %@      %@", self.arr[indexPath.row],self.arr2[indexPath.row]];      cell.backgroundColor =[UIColor darkGrayColor];    cell.textLabel.textColor =[UIColor orangeColor];    return cell;}

以上大致就是全部过程了 不尽完善,通过整理博客也重新思考整个过程, 程序 发现很多问题,希望可以改正。
   




0 0