Skip to content

Instantly share code, notes, and snippets.

@AmaxJ
Last active December 10, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmaxJ/e3d89757d9a79eb174ecf6c84321464c to your computer and use it in GitHub Desktop.
Save AmaxJ/e3d89757d9a79eb174ecf6c84321464c to your computer and use it in GitHub Desktop.
blackjack
object BlackJack {
def main(args: Array[String]) = {
val deck = new Deck()
val players = addPlayers(3)
println(deck.deal)
println(deck.cards)
}
def addPlayers(num: Int) = {
(1 to num) map { player => new Player(s"player $player") } toList
}
class Player(name:String) {
var hand = List()
def calculateScore() = {
hand.map({card:Card => card.value })
.reduce((acc, score) => acc + score)
}
override def toString: String = this.name
}
class Deck() {
var cards = for {
suit <- List("Spades", "Hearts", "Clubs", "Diamonds")
rank <- (2 to 10).toList ++ List("Jack", "Queen", "King", "Ace")
} yield rank match {
case "Ace" => Card("Ace", suit, 11)
case broadway: String => Card(broadway, suit, 10)
case num: Int => Card(num.toString, suit, num)
}
def deal():Card = {
val r = scala.util.Random
val randNum:Int = r.nextInt(52)
val card = this.cards(randNum)
this.cards = this.cards diff List(this.cards(randNum))
card
}
}
case class Card(rank:String, suit:String, value:Int) {
override def toString: String = s"$rank of $suit"
}
}
@jcourtois
Copy link

jcourtois commented Mar 3, 2017

scala is 0-indexed, so you want nextInt(52); with r.nextInt(51)+1, you get a range of 1-51 and you'll never pick the 2 of spades, which will be at cards(0).

@jcourtois
Copy link

import scala.collection.mutable
import scala.util.Random.shuffle

case class Card(suit: String, rank: Any) {
  def value: Int = {
    rank match {
      case "Ace"      11
      case n: Int     n
      case _: String  10
    }
  }

  override def toString: String = s"$rank of $suit"
}

case class Deck() {
  def deal(n: Int = 1): Seq[Card] = {
    (1 to n).flatMap(_ =>
      if (deck.isEmpty) None
      else Some(deck.pop)
    )
  }

  val deck: mutable.Stack[Card] = shuffle(
    for {
      suit  mutable.Stack("Spades", "Hearts", "Clubs", "Diamonds")
      rank  (2 to 10) ++ Seq("Jack", "Queen", "King", "Ace")
    } yield Card(suit, rank)
  )
}

case class Player(number: Int, hand: Seq[Card]) {
  var this.hand: Seq[Card] = hand

  def name: String = s"Player $number"
  def calculateScore: Int = hand.map(_.value).sum
  override def toString: String = s"\n\nPlayer $number\nScore: $calculateScore\nHand: $hand"
}

case class Game(size: Int) {
  val deck = Deck()
  val players: Seq[Player] = (1 to size).map(Player(_, this.deck.deal(2))).sortBy(-_.calculateScore)
}

object BlackJack {
  def main(args: Array[String]): Unit = {
    println(Game(6).players)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment