solution v2
Transcription
solution v2
Double Dice Game (v2)
File:
DoubleDice.java
| Project:
DoubleDiceGame_v2
11TG
/**
* A double dice (Würfel) is composed of two standard dices each with a value of 1 ... 6
*
* @author
Gamboa Carlos (gamca174) / Olinger Alex (olial319)
* @version
25/05/2016 13:11:26
* classe:
11TG
*/
public class DoubleDice
{
private int dice1;
private int dice2;
public DoubleDice()
{
dice1 = (int)(Math.random()*6)+1;
dice2 = (int)(Math.random()*6)+1;
}
public int getDice1()
{
return dice1;
}
public int getDice2()
{
return dice2;
}
public boolean isIdentical()
{
return dice1 == dice2;
}
}
public int getTotal()
{
return dice1 + dice2;
}
Solution
1 / 3
Double Dice Game (v2)
File:
Game.java
| Project:
DoubleDiceGame_v2
11TG
/**
* Simulates a game of dices:
* Two players throw a double dice.
* Game rules:
* 1) Greatest sum of eyes wins
* 2) Exception: A double beats any sum
* 3) Exception of exception: A double with greater eyes beats another double.
* 4) No points when eyes are equal.
*
* @author
Gamboa Carlos (gamca174) / Olinger Alex (olial319)
* @version
25/05/2016 13:11:26
* classe:
11TG
*/
public class Game
{
private String namePlayer1;
private String namePlayer2;
private int scorePlayer1;
private int scorePlayer2;
public Game(String pNamePlayer1, String pNamePlayer2)
{
namePlayer1 = pNamePlayer1;
namePlayer2 = pNamePlayer2;
scorePlayer1 = 0;
scorePlayer2 = 0;
}
public void calcScores(DoubleDice pDoubleDice1, DoubleDice pDoubleDice2)
{
// VERISON 2: logique compacte sans duplication de code
int total1 = pDoubleDice1.getTotal();
int total2 = pDoubleDice2.getTotal();
}
}
// Note: le if suivant peut aussi s'écrire plus simplement:
//
if (pDoubleDice1.isIdentical() == pDoubleDice2.isIdentical())
//
mais c'est plus difficile à comprendre
if ((pDoubleDice1.isIdentical() && pDoubleDice2.isIdentical())
|| (!pDoubleDice1.isIdentical() && !pDoubleDice2.isIdentical()))
{
// les deux joueurs ont un double ou aucun n'a un double
if (total1 > total2)
{
scorePlayer1++;
}
else if (total1 < total2)
{
scorePlayer2++;
}
// else... rien à faire car égalité des totaux
}
else
{
// un seul joueur a un double
if (pDoubleDice1.isIdentical())
{
scorePlayer1++;
}
else
{
scorePlayer2++;
}
}
public void singleTurn()
{
DoubleDice d1 = new DoubleDice();
DoubleDice d2 = new DoubleDice();
calcScores(d1, d2);
System.out.println(namePlayer1 + " = " + d1.getDice1() + "+" + d1.getDice2() + " -> " + scorePlayer1);
System.out.println(namePlayer2 + " = " + d2.getDice1() + "+" + d2.getDice2() + " -> " + scorePlayer2);
}
Solution
2 / 3
Double Dice Game (v2)
File:
TestGame.java
| Project:
DoubleDiceGame_v2
11TG
/**
* Simulates a lot of turns.
*
* @author
Gamboa Carlos (gamca174) / Olinger Alex (olial319)
* @version
25/05/2016 13:11:26
* classe:
11TG
*/
public class TestGame
{
public static void main(String[] args)
{
Game g0 = new Game("Alex", "Carlos");
for (int i=1;i<=1000;i++)
{
System.out.println("Turn "+i);
g0.singleTurn();
}
}
}
Solution
3 / 3