Created
March 2, 2015 23:51
-
-
Save valdo404/ae1b9aa9cd4dae14b940 to your computer and use it in GitHub Desktop.
jeu set et match
This file contains hidden or 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
package tennis | |
class Player(val number: Int, private var value:Int = 0) { | |
def score(): Score = value match { | |
case 0 => Love | |
case 1 => Fifteen | |
case 2 => Thirty | |
case 3 => Forty | |
case _ => Win(number)} | |
def += (i: Int): Unit = { | |
value += i | |
} | |
def loveOn(other: Player) = value > 0 && other.value == 0 | |
def newScoreOn(other: Player) = value > other.value && other.value < 4 | |
def advantageOn(other: Player) = value > other.value && other.value >= 3 | |
def winOn(other: Player) = value >= 4 && other.value >= 0 && (value - other.value) >= 2 | |
def same(other: Player) = value == other.value | |
def deuce(other: Player) = same(other) && value >= 3 | |
def * (other: Player): Score = { | |
var result = this combine other | |
if(advantageOn(other)) | |
result = Advantage(this.number) | |
if(this.winOn(other)) | |
result = Win(this.number) | |
if(other.advantageOn(this)) | |
result = Advantage(other.number) | |
if(other.winOn(this)) | |
result = Win(other.number) | |
result | |
} | |
def combine (other: Player): Score = { | |
if (same(other)) | |
if (deuce(other)) Deuce else Combination(score(), All) | |
else if (loveOn(other) || newScoreOn(other)) | |
Combination(this.score(), other.score()) | |
else if (other.loveOn(this) || other.newScoreOn(this)) | |
Combination(this.score(), other.score()) | |
else | |
Combination(this.score(), other.score()) | |
} | |
} | |
class TennisGame2(val player1Name: String, val player2Name: String) extends TennisGame { | |
var p1 = new Player(1, 0) | |
var p2 = new Player(2, 0) | |
def calculateScore(): String = { | |
Score.format(p1 * p2) | |
} | |
def wonPoint(player: String) { | |
if (player == "player1") { | |
p1 += 1 | |
} | |
else { | |
p2 += 1 | |
} | |
} | |
} | |
class Score | |
case object Love extends Score | |
case object Fifteen extends Score | |
case object Thirty extends Score | |
case object Forty extends Score | |
case object All extends Score | |
case object Deuce extends Score | |
case class Combination(first: Score, second: Score) extends Score | |
case class Win(number: Int) extends Score | |
case class Advantage(number: Int) extends Score | |
object Score { | |
def format(score: Score): String = score match { | |
case Combination(Win(n), _) => "Win for player" + n | |
case Combination(_, Win(n)) => "Win for player" + n | |
case Combination(x, y) => x + "-" + y | |
case Advantage(n) => "Advantage player" + n | |
case Win(n) => "Win for player" + n | |
case Deuce => "Deuce" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment