raku

My Raku Scripts Collection
git clone https://fab.ddns.me.uk/stagit/raku
Log | Files | Refs | README

blackjack.raku (1766B)


      1 #!/usr/bin/env raku
      2 # 1. 山札(デッキ)の作成
      3 my @base = <1 2 3 4 5 6 7 8 9 10 J Q K A>;
      4 my @deck = (@base, @base, @base, @base).flat;
      5 
      6 # 2. 手札の合計を計算する関数
      7 sub count-score(@hand) {
      8     my $total = 0;
      9     my $aces = 0;
     10 
     11     for @hand -> $card {
     12         if $card ~~ Int { $total += $card }
     13         elsif $card eq 'A' { $aces += 1; $total += 11 }
     14         else { $total += 10 } # J, Q, K は 10
     15     }
     16 
     17     # Aの調整(21を超えたら11から1に変換)
     18     while $total > 21 && $aces > 0 {
     19         $total -= 10;
     20         $aces -= 1;
     21     }
     22     return $total;
     23 }
     24 
     25 # 3. ゲーム開始
     26 my @cards = @deck.pick(*); # 山札をシャッフル
     27 my @player = @cards.pop, @cards.pop;
     28 my @dealer = @cards.pop, @cards.pop;
     29 
     30 loop {
     31     my $p-score = count-score(@player);
     32     say "Your hand: {@player.join(', ')} (Score: $p-score)";
     33     
     34     if $p-score > 21 { say "Bust! You lose. 🇬🇧 Dreadful luck!"; exit; }
     35     if $p-score == 21 { say "Blackjack! 🇬🇧 Top-hole!"; last; }
     36 
     37     my $choice = prompt "Do you want to (H)it or (S)tand? ";
     38     if $choice.lc.starts-with('h') {
     39         @player.push: @cards.pop;
     40     } else {
     41         last;
     42     }
     43 }
     44 
     45 # 4. ディーラーのターン
     46 say "\nDealer's hand: {@dealer.join(', ')}";
     47 while count-score(@dealer) < 17 {
     48     @dealer.push: @cards.pop;
     49     say "Dealer hits: {@dealer.join(', ')}";
     50 }
     51 
     52 # 5. 結果判定
     53 my $p-total = count-score(@player);
     54 my $d-total = count-score(@dealer);
     55 
     56 say "\nFinal Scores - You: $p-total, Dealer: $d-total";
     57 
     58 if $d-total > 21 { say "Dealer busts! You win! 🇬🇧 Brilliant!"; }
     59 elsif $p-total > $d-total { say "You win! 🇬🇧 Jolly good!"; }
     60 elsif $p-total < $d-total { say "Dealer wins. 🇬🇧 Better luck next time!"; }
     61 else { say "It's a push (Tie)."; }