猜拳游戏主要有两个界面:第一个界面的布局中用TextView、RadioGroup、Radiobutton、Button
第二个界面中含有一个TextView
MainActivity
package com.example.guess;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
public class MainActivity extends Activity {
private RadioGroup radioGroup;
private Button button;
private OnClickListener listener=new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
int id=radioGroup.getCheckedRadioButtonId();
int quan=0;
switch(id){
case R.id.r1:
quan=1;
break;
case R.id.r2:
quan=2;
break;
case R.id.r3:
quan=3;
break;
default:
break;
}
Intent intent=new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
intent.putExtra("quan",quan);
startActivity(intent);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化控件
radioGroup=(RadioGroup) findViewById(R.id.radioGroup1);
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(listener);
}
}
SecondActivity
package com.example.guess;
import java.util.Random;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
public class SecondActivity extends Activity {
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textview=(TextView) findViewById(R.id.result);
//得到人出的拳
Intent intent=getIntent();
Bundle bundle=intent.getExtras();
int ren=bundle.getInt("quan");
//得到电脑出的拳
Random random=new Random();
int chu=random.nextInt(3-1)+1;
//比较结果 得出胜负
String result=compare(ren ,chu);
textview.setText(result);
}
private String compare(int ren ,int chu){
StringBuffer sbf=new StringBuffer("猜拳结果:\n"+"人 "+convert(ren)+" VS "+" 电脑"+convert(chu)+" \n");
if(ren==chu){
sbf.append("平局哦,继续努力!");
}else if(ren==1&&chu==3){
sbf.append("电脑赢了哦,你要继续努力喽!");
}else if(ren==3&&chu==1){
sbf.append("你赢了哦,happy!");
}else if(ren<chu){
sbf.append("你赢了,电脑输了哦");
}else if(ren>chu){
sbf.append("电脑赢了,你要加油哦!!");
}
return sbf.toString();
}
private String convert(int id) {
// TODO Auto-generated method stub
switch(id){
case 1:
return "石头";
case 2:
return "剪刀";
case 3:
return "布";
default:
break;
}
return null;
}
}