Created
February 27, 2018 11:15
-
-
Save Binary-Finery/2bbdf0e376db9f7d78b02357e7781ba9 to your computer and use it in GitHub Desktop.
Ultra minimal one player (human vs computer) game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.view.View; | |
import android.view.animation.AnimationUtils; | |
import android.widget.TextView; | |
import java.util.Locale; | |
import java.util.Random; | |
public class MainActivity extends AppCompatActivity { | |
private Random random; | |
private Play human; | |
private Play cpu; | |
private int win = 0; | |
private int draw = 0; | |
private int lose = 0; | |
private TextView tvHuman; | |
private TextView tvCpu; | |
private TextView tvStats; | |
private enum Play { | |
ROCK, | |
PAPER, | |
SCISSORS; | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
initiateViews(); | |
random = new Random(); | |
} | |
public void actionClick(View view) { | |
int id = view.getId(); | |
switch (id) { | |
case R.id.btn_rock: | |
human = Play.ROCK; | |
break; | |
case R.id.btn_paper: | |
human = Play.PAPER; | |
break; | |
case R.id.btn_scissors: | |
human = Play.SCISSORS; | |
break; | |
} | |
generateRandomCpuHand(); | |
} | |
private void generateRandomCpuHand() { | |
switch (random.nextInt(3)) { | |
case 0: | |
cpu = Play.ROCK; | |
break; | |
case 1: | |
cpu = Play.PAPER; | |
break; | |
case 2: | |
cpu = Play.SCISSORS; | |
break; | |
} | |
evaluate(); | |
} | |
private void evaluate() { | |
if (human == Play.ROCK && cpu == Play.ROCK || human == Play.PAPER && cpu == Play.PAPER || human == Play.SCISSORS && cpu == Play.SCISSORS) { | |
draw++; | |
} else if (human == Play.PAPER && cpu == Play.ROCK || human == Play.SCISSORS && cpu == Play.PAPER || human == Play.ROCK && cpu == Play.SCISSORS) { | |
win++; | |
} else { | |
lose++; | |
} | |
updateUI(); | |
} | |
private void initiateViews() { | |
tvHuman = findViewById(R.id.tv_human); | |
tvCpu = findViewById(R.id.tv_cpu); | |
tvStats = findViewById(R.id.tv_stats); | |
} | |
private void updateUI() { | |
tvHuman.setText(human.toString()); | |
tvCpu.setText(cpu.toString()); | |
tvHuman.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_right)); | |
tvCpu.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_left)); | |
tvStats.setText(String.format(Locale.getDefault(), "Win: %d, Lose: %d, Draw: %d", win, lose, draw)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment