您的位置:首页 > 其它

人机猜拳游戏

2013-05-12 21:16 211 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/wangjing1_12/article/details/8913780

activity_mian.xml中用到了RadioGroup

MainActivity.java中:

public class MainActivity extends Activity {

private RadioGroup radioGroup;
private String myChuQuan="剪刀";//将选择项默认为剪刀
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=(RadioGroup)this.findViewById(R.id.radioGroup1);
button=(Button)this.findViewById(R.id.ok);
//对RadioGroup 进行监听,并对myChuQuan进行赋值
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId)
{
case R.id.jianDao:
myChuQuan="剪刀";
break;
case R.id.shiTou:
myChuQuan="石头";
break;
case R.id.bu:
myChuQuan="布";
break;
}
}

});
//System.out.println(myChuQuan);

button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Intent intent=new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
Bundle bundle=new Bundle();
bundle.putString("myChuQuan", myChuQuan);

intent.putExtras(bundle);
startActivity(intent);

}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}
Second.java中随机产生电脑的选择,并与第一个页面传过来的信息进行比较:
public class SecondActivity extends Activity {

String myChuQuan;
String computerQuan;
String result;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
text=(TextView)this.findViewById(R.id.result);
Intent intent=getIntent();//利用得到Intent,并利用Bundle取得传递的值
Bundle bundle=intent.getExtras();
myChuQuan=bundle.getString("myChuQuan");
computerQ();//电脑随机产生选择
compareJieGuo();//比较猜拳
text.setText("您出的是"+myChuQuan+",电脑出的是"+computerQuan+"\n"+result);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
public void computerQ()
{
int suiJi=(int)((Math.random()*10)%3);//取得0   1   2
switch(suiJi)
{
case 0:
computerQuan="剪刀";
break;
case 1:
computerQuan="石头";
break;
case 2:
computerQuan="布";
break;

}

}
public void compareJieGuo()
{
int a,b;
//a用1 2 3 表示人的出拳
if(myChuQuan.equals("剪刀")) a=1;
else if(myChuQuan.equals("石头")) a=2;
else a=3;
//b表示电脑的出拳,为了之后的方便
if(computerQuan.equals("剪刀")) b=1;
else if(computerQuan.equals("石头")) b=2;
else b=3;
if((a==1&&b==3)||(a==2&&b==1)||(a==3&&b==2))
{
result="您赢了";
}
else if((b==1&&a==3)||(b==2&&a==1)||(b==3&&a==2))
{
result="电脑赢了";
}
else
{
result="平局";
}

}

}

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