import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnScissors, btnRock, btnPaper;
private TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScissors = findViewById(R.id.btn_scissors);
btnRock = findViewById(R.id.btn_rock);
btnPaper = findViewById(R.id.btn_paper);
tvResult = findViewById(R.id.tv_result);
btnScissors.setOnClickListener(this);
btnRock.setOnClickListener(this);
btnPaper.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_scissors:
playGame(0);
break;
case R.id.btn_rock:
playGame(1);
break;
case R.id.btn_paper:
playGame(2);
break;
}
}
private void playGame(int userChoice) {
// 0 = 剪刀, 1 = 石头, 2 = 布
int computerChoice = (int) (Math.random() * 3);
if (userChoice == computerChoice) {
tvResult.setText("平局");
} else if ((userChoice == 0 && computerChoice == 2)
|| (userChoice == 1 && computerChoice == 0)
|| (userChoice == 2 && computerChoice == 1)) {
tvResult.setText("恭喜你,你赢了!");
} else {
tvResult.setText("很遗憾,你输了。");
}
}
}
03-02