您的位置:首页 > 其它

OC小游戏-人机大战-猜拳

2015-05-19 17:40 295 查看
先声明3个类,分别是Person、Computer、Tocompare,制定游戏规则,让0~2中的数字依次代表石头、剪刀、布;在Person类中声明一个变量,接收键盘录入的数字,在Computer中声明一个返回随机数的方法,然后在Tocompare类中进行比较,思路很简单,直接上代码:

Person.h​
@interface Person : NSObject
@property(assign ,nonatomic)int num;//声明一个属性,接收输入的数字

@end
​由于没有在Person类中声明方法,所以Person.m文件为空;

Computer.h​
​@interface Computer : NSObject
-(int)play;//声明产生一个随机数的方法

@end
Computer.m​
@implementation Computer
-(int)play

{

return arc4random()%3;//返回一个0~2中的随机数
}
@end
​To compare.h
@interface To_compare : NSObject
-(void)compare;//声明一个比较的方法

@end​
​To compare.m
#import "To compare.h"
#import "Computer.h"

#import "Person.h"//导入头文件
@implementation To_compare
-(void)compare
{

intp,c;

intp_num=0,c_num=0,count=0;//统计次数

NSString*win;

NSString*p_string;

NSString*c_string;

NSLog(@"请输入0~2之间的一个数字,0代表石头,1代表剪刀,2代表布");

NSLog(@"Number\tPerson\t\tComputer\tWin");

while (p!=100){

scanf("%d",&p);//接收输入的数字

if(p==100) {

continue;

}//输入100即结束游戏

Person *per=[Personnew];

per.num=p;

Computer *com=[Computernew];

c=[complay];//接收Computer类中产生的随机数

if(p==0)

p_string=@"石头";

else if(p==1)

p_string=@"剪刀";

else if(p==2)

p_string=@"布";

else {

NSLog(@"输入错误!请重新输入:");

continue;

}

if(c==0)

c_string=@"石头";

else if(c==1)

c_string=@"剪刀";

else

c_string=@"布";//将结果用汉字输出

if((p==0&&c==1)||(p==1&&c==2)||(p==2&&c==0)) {

win=@"人类";

p_num++;

}

else if((c==0&&p==1)||(c==1&&p==2)||(c==2&&p==0)) {

win=@"电脑";

c_num++;

}

else

win=@"-";//设置游戏规则

count++;

NSLog(@"%d\t\t%@\t\t%@\t\t%@",count,p_string,c_string,win);
​}
NSLog(@"总共出拳%d次,人类获胜%d次,电脑获胜%d次,平局%d次.\nPS: -代表平局",count,p_num,c_num,count-p_num-c_num);

}
@end
输出如下:​
2015-05-20 09:10:10.624 The man-machine against[7750:1208272] 欢迎来到人机大战的猜拳世界,输入数字100结束游戏。

2015-05-20 09:10:10.625 The man-machine against[7750:1208272] 请输入0~2之间的一个数字,0代表石头,1代表剪刀,2代表布

2015-05-20 09:10:10.626 The man-machine against[7750:1208272] Number Person Computer Win

1

2015-05-20 09:10:13.654 The man-machine against[7750:1208272] 1 剪刀 石头 电脑

2

2015-05-20 09:10:14.113 The man-machine against[7750:1208272] 2 布 剪刀 电脑

3

2015-05-20 09:10:14.486 The man-machine against[7750:1208272] 输入错误!请重新输入:

4

2015-05-20 09:10:14.813 The man-machine against[7750:1208272] 输入错误!请重新输入:

6

2015-05-20 09:10:15.172 The man-machine against[7750:1208272] 输入错误!请重新输入:

1

2015-05-20 09:10:15.782 The man-machine against[7750:1208272] 3 剪刀 石头 电脑

2

2015-05-20 09:10:16.139 The man-machine against[7750:1208272] 4 布 布 -

0

2015-05-20 09:10:16.471 The man-machine against[7750:1208272] 5 石头 石头 -

1

2015-05-20 09:10:16.813 The man-machine against[7750:1208272] 6 剪刀 石头 电脑

2

2015-05-20 09:10:17.295 The man-machine against[7750:1208272] 7 布 剪刀 电脑

3100

2015-05-20 09:10:19.296 The man-machine against[7750:1208272] 输入错误!请重新输入:

100

2015-05-20 09:10:21.118 The man-machine against[7750:1208272] 总共出拳7次,人类获胜0次,电脑获胜5次,平局2次.

PS: - 代表平局
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: