Pig the dice game: Difference between revisions

m
m (Better explanations)
 
(90 intermediate revisions by 43 users not shown)
Line 1:
{{task}}
 
The   [[wp:Pig (dice)|game of Pig]]   is a multiplayer game played with a single six-sided die.   The
object of the game is to reach   '''100'''   points or more.  
Play is taken in turns.   On each person's turn that person has the option of either:
 
:# '''Rolling the dice''':   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   '''1'''   loses the player's total points   ''for that turn''   and their turn finishes with play passing to the next player.
:# '''Holding''': The  the player's score for that round is added to their total and becomes safe from the effects of throwing a   '''1'''   (one).   The player's turn finishes with play passing to the next player.
 
;Task goal:
The goal of this task is to create a program to score for, and simulate dice throws for, a two-person game.
 
;CfTask:
Create a program to score for, and simulate dice throws for, a two-person game.
* [[Pig the dice game/Player]]
 
 
;Related task:
*   [[Pig the dice game/Player]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V playercount = 2
V maxscore = 100
V safescore = [0] * playercount
V player = 0
V score = 0
 
L max(safescore) < maxscore
V rolling = input(‘Player #.: (#., #.) Rolling? (Y) ’.format(
player, safescore[player], score)).trim(‘ ’).lowercase() C Set([‘yes’, ‘y’, ‘’])
I rolling
V rolled = random:(1 .. 6)
print(‘ Rolled #.’.format(rolled))
I rolled == 1
print(‘ Bust! you lose #. but still keep your previous #.’.format(score, safescore[player]))
(score, player) = (0, (player + 1) % playercount)
E
score += rolled
E
safescore[player] += score
I safescore[player] >= maxscore
L.break
print(‘ Sticking with #.’.format(safescore[player]))
(score, player) = (0, (player + 1) % playercount)
 
print("\nPlayer #. wins with a score of #.".format(player, safescore[player]))</syntaxhighlight>
 
{{out}}
The same as in Python solution.
 
=={{header|ActionScript}}==
<syntaxhighlight lang="actionscript">
<lang ActionScript>
package {
Line 442 ⟶ 477:
}
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Line 456 ⟶ 491:
Also, there is a procedure Play to play the game, following whatever the actors do.
 
<langsyntaxhighlight Adalang="ada">package Pig is
type Dice_Score is range 1 .. 6;
Line 478 ⟶ 513:
end record;
 
end Pig;</langsyntaxhighlight>
 
The implementation of Pig is as follows:
 
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
package body Pig is
Line 532 ⟶ 567:
begin
RND.Reset(Gen);
end Pig;</langsyntaxhighlight>
 
===Solving the Task===
Line 539 ⟶ 574:
class Hand from the class Actor to implement manually playing the game.
 
<langsyntaxhighlight Adalang="ada">with Pig, Ada.Text_IO;
 
procedure Play_Pig is
Line 570 ⟶ 605:
Play(A1, A2, Alice);
Ada.Text_IO.Put_Line("Winner = " & (if Alice then "Alice!" else "Bob!"));
end Play_Pig;</langsyntaxhighlight>
 
{{out}}
Line 598 ⟶ 633:
Alice you: 89 (opponent: 66) this round: 11 this roll: 5; add to score(+)?+
Winner = Alice!</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Gui, Font, s12, Verdana
Gui, Add, Text, vPlayer0, Player 0
Gui, Add, Text, vSum0, 000
Gui, Add, Button, Default, Roll
Gui, Add, Text, ys vLastRoll, Roll 0
Gui, Add, Text, vTurnSum, Sum 000
Gui, Add, Button, , Hold
Gui, Add, Text, ys vPlayer1, Player 1
Gui, Add, Text, vSum1, 000
Gui, Add, Button, , Reload
Gui, Show
GuiControl, Disable, Player1
 
CurrentPlayer := 0
ButtonRoll:
Loop 10
{
Random, LastRoll, 1, 6
GuiControl, , LastRoll, Roll %LastRoll%
Sleep 50
}
If LastRoll != 1
{
TurnSum += LastRoll
GuiControl, , TurnSum, Sum %TurnSum%
Return
}
TurnSum := 0
ButtonHold:
Sum%CurrentPlayer% += TurnSum
TurnSum := 0
GuiControl, , LastRoll, Roll
GuiControl, , TurnSum, Sum %TurnSum%
GuiControl, , Sum%CurrentPlayer%, % Sum%CurrentPlayer%
If Sum%CurrentPlayer% >= 100
{
MsgBox Player %CurrentPlayer% Won!
GuiClose:
ExitApp
}
GuiControl, Disable, Player%CurrentPlayer%
CurrentPlayer := !CurrentPlayer
GuiControl, Enable, Player%CurrentPlayer%
Return
 
ButtonReload:
Reload</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f PIG_THE_DICE_GAME.AWK
# converted from LUA
BEGIN {
players = 2
p = 1 # start with first player
srand()
printf("Enter: Hold or Roll?\n\n")
while (1) {
printf("Player %d, your score is %d, with %d temporary points\n",p,scores[p],points)
getline reply
reply = toupper(substr(reply,1,1))
if (reply == "R") {
roll = int(rand() * 6) + 1 # roll die
printf("You rolled a %d\n",roll)
if (roll == 1) {
printf("Too bad. You lost %d temporary points\n\n",points)
points = 0
p = (p % players) + 1
}
else {
points += roll
}
}
else if (reply == "H") {
scores[p] += points
points = 0
if (scores[p] >= 100) {
printf("Player %d wins with a score of %d\n",p,scores[p])
break
}
printf("Player %d, your new score is %d\n\n",p,scores[p])
p = (p % players) + 1
}
else if (reply == "Q") { # abandon game
break
}
}
exit(0)
}
</syntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">100 NJ = 2
110 MP = 100
120 DIM APT(3)
130 APT(1) = 1
140 APT(2) = 1
150 HOME
160 PRINT "The game of PIG"
170 PRINT "===============";CHR$(13);CHR$(10)
180 PRINT "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
190 PRINT "Si jugador saca 2-6, se agrega al total del turno y su turno continua."
200 PRINT "Si jugador elige 'mantener', su total de puntos se anade a su puntuacion,";
210 PRINT " y se convierte en el turno del siguiente jugador.";CHR$(10)
220 PRINT "El primer jugador en anotar 100 o mas puntos gana.";CHR$(13);CHR$(10)
230 FOR J = 1 TO 2
250 PT = 0
260 IF APT(J) > MP THEN GOTO 370
270 PRINT
280 PRINT "j";J;": (";APT(J);",";PT;")";
290 INPUT " Tirada? (Sn) ";NT$
300 IF NT$ = "S" OR NT$ = "s" THEN GOTO 400
310 REM opcion N
320 APT(J) = APT(J)+PT
330 PRINT " Te quedas con: ";APT(J)
340 IF APT(J) >= MP THEN PRINT CHR$(10);"Gana el j";J;" con ";APT(J);" puntos." : END
350 GOTO 370
360 GOTO 260
370 NEXT J
380 GOTO 230
390 END
400 REM opcion S
410 TIRA = INT(RND(1)*5)+1
420 PRINT " tirada:";TIRA
430 IF TIRA = 1 THEN PRINT CHR$(10);"!Pierdes tu turno! j";J;" pero mantienes tu puntuacion anterior de ";APT(J) : GOTO 370
440 PT = PT+TIRA
450 GOTO 360</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Pig.bas"
110 RANDOMIZE
120 STRING PLAYER$(1 TO 2)*28
130 NUMERIC POINTS(1 TO 2),VICTORY(1 TO 2)
140 LET WINNINGSCORE=100
150 TEXT 40:PRINT "Let's play Pig!";CHR$(241):PRINT
160 FOR I=1 TO 2
170 PRINT "Player";I
180 INPUT PROMPT "Whats your name? ":PLAYER$(I)
190 LET POINTS(I)=0:LET VICTORY(I)=0:PRINT
200 NEXT
210 DO
220 CALL TAKETURN(1)
230 IF NOT VICTORY(1) THEN CALL TAKETURN(2)
240 LOOP UNTIL VICTORY(1) OR VICTORY(2)
250 IF VICTORY(1) THEN
260 CALL CONGRAT(1)
270 ELSE
280 CALL CONGRAT(2)
290 END IF
300 DEF TAKETURN(P)
310 LET NEWPOINTS=0
320 SET #102:INK 3:PRINT :PRINT "It's your turn, " PLAYER$(P);"!":PRINT "So far, you have";POINTS(P);"points in all."
330 SET #102:INK 1:PRINT "Do you want to roll the die? (y/n)"
340 LET KEY$=ANSWER$
350 DO WHILE KEY$="y"
360 LET ROLL=RND(6)+1
370 IF ROLL=1 THEN
380 LET NEWPOINTS=0:LET KEY$="n"
390 PRINT "Oh no! You rolled a 1! No new points after all."
400 ELSE
410 LET NEWPOINTS=NEWPOINTS+ROLL
420 PRINT "You rolled a";ROLL:PRINT "That makes";NEWPOINTS;"new points so far."
430 PRINT "Roll again? (y/n)"
440 LET KEY$=ANSWER$
450 END IF
460 LOOP
470 IF NEWPOINTS=0 THEN
480 PRINT PLAYER$(P);" still has";POINTS(P);"points."
490 ELSE
500 LET POINTS(P)=POINTS(P)+NEWPOINTS:LET VICTORY(P)=POINTS(P)>=WINNINGSCORE
510 END IF
520 END DEF
530 DEF CONGRAT(P)
540 SET #102:INK 3:PRINT :PRINT "Congratulations ";PLAYER$(P);"!"
550 PRINT "You won with";POINTS(P);"points.":SET #102:INK 1
560 END DEF
570 DEF ANSWER$
580 LET K$=""
590 DO
600 LET K$=LCASE$(INKEY$)
610 LOOP UNTIL K$="y" OR K$="n"
620 LET ANSWER$=K$
630 END DEF</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{works with|GW-BASIC}}
<syntaxhighlight lang="qbasic">100 NJ = 2
110 MP = 100
120 DIM APT(3)
130 APT(1) = 1
140 APT(2) = 1
150 CLS
160 PRINT "The game of PIG"
170 PRINT "===============";CHR$(13);CHR$(10)
180 PRINT "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
190 PRINT "Si jugador saca 2-6, se agrega al total del turno y su turno continua."
200 PRINT "Si jugador elige 'mantener', su total de puntos se anade a su puntuacion,";
210 PRINT " y se convierte en el turno del siguiente jugador.";CHR$(10)
220 PRINT "El primer jugador en anotar 100 o mas puntos gana.";CHR$(13);CHR$(10)
230 'while
240 FOR J = 1 TO 2 'nj
250 PT = 0
260 IF APT(J) > MP THEN GOTO 370
270 PRINT
280 PRINT "j";J;": (";APT(J);",";PT;")";
290 INPUT " Tirada? (Sn) ";NT$
300 IF NT$ = "S" OR NT$ = "s" THEN GOTO 400
310 REM opcion N
320 APT(J) = APT(J)+PT
330 PRINT " Te quedas con: ";APT(J)
340 IF APT(J) >= MP THEN PRINT CHR$(10);"Gana el j";J;"con";APT(J);"puntos." : END
350 GOTO 370 'exit while
360 GOTO 260
370 NEXT J
380 GOTO 230
390 END
400 REM opcion S
410 TIRA = INT(RND(1)*5)+1
420 PRINT " tirada:";TIRA
430 IF TIRA = 1 THEN PRINT CHR$(10);"!Pierdes tu turno! j";J;"pero mantienes tu puntuacion anterior de";APT(J) : GOTO 370 'exit while
440 PT = PT+TIRA
450 GOTO 360</syntaxhighlight>
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">numjugadores = 2
maxpuntos = 100
Dim almacenpuntos(3)
almacenpuntos[1] = 1
almacenpuntos[2] = 1
 
Cls: Print "The game of PIG"
Print "===============" + Chr(13) + Chr(10)
Print "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
Print "Si jugador saca 2-6, se agrega al total del turno y su turno continúa."
Print "Si jugador elige 'mantener', su total de puntos se añade a su puntuación, "
Print " y se convierte en el turno del siguiente jugador." + Chr(10)
Print "El primer jugador en anotar 100 o más puntos gana."&Chr(13)&Chr(10)
 
Do
For jugador = 1 To 2 #numjugadores
puntos = 0
 
While almacenpuntos[jugador] <= maxpuntos
Print
Print "Jugador "; jugador; ": (";almacenpuntos[jugador];",";puntos;")";
Input " ¿Tirada? (Sn) ", nuevotiro
If Upper(nuevotiro) = "S" Then
tirada = Int(Rand* 5) + 1
Print " Tirada:"; tirada
If tirada = 1 Then
Print Chr(10) + "¡Pierdes tu turno! jugador "; jugador;
Print " pero mantienes tu puntuación anterior de "; almacenpuntos[jugador]
Exit While
End If
puntos = puntos + tirada
Else
almacenpuntos[jugador] = almacenpuntos[jugador] + puntos
Print " Te quedas con: "; almacenpuntos[jugador]
If almacenpuntos[jugador] >= maxpuntos Then
Print Chr(10) + "Gana el Jugador "; jugador; " con "; almacenpuntos[jugador]; " puntos."
End
End If
Exit While
End If
End While
Next jugador
Until false</syntaxhighlight>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
 
const int NUM_PLAYERS = 2;
const int MAX_POINTS = 100;
 
 
//General functions
int randrange(int min, int max){
return (rand() % (max - min + 1)) + min;
}
 
 
//Game functions
void ResetScores(int *scores){
for(int i = 0; i < NUM_PLAYERS; i++){
scores[i] = 0;
}
}
 
 
void Play(int *scores){
int scoredPoints = 0;
int diceResult;
int choice;
 
for(int i = 0; i < NUM_PLAYERS; i++){
while(1){
printf("Player %d - You have %d total points and %d points this turn \nWhat do you want to do (1)roll or (2)hold: ", i + 1, scores[i], scoredPoints);
scanf("%d", &choice);
 
if(choice == 1){
diceResult = randrange(1, 6);
printf("\nYou rolled a %d\n", diceResult);
 
if(diceResult != 1){
scoredPoints += diceResult;
}
else{
printf("You loose all your points from this turn\n\n");
scoredPoints = 0;
break;
}
}
else if(choice == 2){
scores[i] += scoredPoints;
printf("\nYou holded, you have %d points\n\n", scores[i]);
 
break;
}
}
 
scoredPoints = 0;
CheckForWin(scores[i], i + 1);
 
}
}
 
 
void CheckForWin(int playerScore, int playerNum){
if(playerScore >= MAX_POINTS){
printf("\n\nCONGRATULATIONS PLAYER %d, YOU WIN\n\n!", playerNum);
 
exit(EXIT_SUCCESS);
}
}
 
 
int main()
{
srand(time(0));
 
int scores[NUM_PLAYERS];
ResetScores(scores);
 
while(1){
Play(scores);
}
 
return 0;
}</syntaxhighlight>
{{Out}}
<pre>Player 1 - You have 0 total points and 0 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 2
Player 1 - You have 0 total points and 2 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 2
Player 1 - You have 0 total points and 4 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 4
Player 1 - You have 0 total points and 8 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 5
Player 1 - You have 0 total points and 13 points this turn
What do you want to do (1)roll or (2)hold: 2
 
You holded, you have 13 points
 
Player 2 - You have 0 total points and 0 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 5
Player 2 - You have 0 total points and 5 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 6
Player 2 - You have 0 total points and 11 points this turn
What do you want to do (1)roll or (2)hold: 1
 
You rolled a 3
Player 2 - You have 0 total points and 14 points this turn
What do you want to do (1)roll or (2)hold:</pre>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">using System;
using System.IO;
 
namespace Pig {
 
class Roll {
public int TotalScore{get;set;}
public int RollScore{get;set;}
public bool Continue{get;set;}
}
 
class Player {
public String Name{get;set;}
public int Score {get;set;}
Random rand;
 
public Player() {
Score = 0;
rand = new Random();
}
 
public Roll Roll(int LastScore){
Roll roll = new Roll();
roll.RollScore = rand.Next(6) + 1;
 
if(roll.RollScore == 1){
roll.TotalScore = 0;
roll.Continue = false;
return roll;
}
 
roll.TotalScore = LastScore + roll.RollScore;
roll.Continue = true;
return roll;
}
 
public void FinalizeTurn(Roll roll){
Score = Score + roll.TotalScore;
}
}
 
public class Game {
public static void Main(String[] argv){
String input = null;
Player[] players = new Player[2];
 
// Game loop
while(true){
Console.Write("Greetings! Would you like to play a game (y/n)?");
while(input == null){
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
players[0] = new Player();
players[1] = new Player();
Console.Write("Player One, what's your name?");
input = Console.ReadLine();
players[0].Name = input;
Console.Write("Player Two, what's your name?");
input = Console.ReadLine();
players[1].Name = input;
Console.WriteLine(players[0].Name + " and " + players[1].Name + ", prepare to do battle!");
} else if (input.ToLowerInvariant() == "n"){
goto Goodbye; /* Not considered harmful */
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
 
// Play the game
int currentPlayer = 0;
Roll roll = null;
bool runTurn = true;
while(runTurn){
Player p = players[currentPlayer];
roll = p.Roll( (roll !=null) ? roll.TotalScore : 0 );
if(roll.Continue){
if(roll.TotalScore + p.Score > 99){
Console.WriteLine("Congratulations, " + p.Name + "! You rolled a " + roll.RollScore + " for a final score of " + (roll.TotalScore + p.Score) + "!");
runTurn = false;
} else {
Console.Write(p.Name + ": Roll " + roll.RollScore + "/Turn " + roll.TotalScore + "/Total " + (roll.TotalScore + p.Score) + ". Roll again (y/n)?");
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
// Do nothing
} else if (input.ToLowerInvariant() == "n"){
p.FinalizeTurn(roll);
currentPlayer = Math.Abs(currentPlayer - 1);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
Console.WriteLine(players[currentPlayer].Name + ", your turn begins.");
roll = null;
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
} else {
Console.WriteLine(p.Name + @", you rolled a 1 and lost your points for this turn.
Your current score: " + p.Score);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
currentPlayer = Math.Abs(currentPlayer - 1);
}
}
 
 
input = null;
}
Goodbye:
Console.WriteLine("Thanks for playing, and remember: the house ALWAYS wins!");
System.Environment.Exit(0);
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 736 ⟶ 1,286:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
Output:
<pre>
Line 755 ⟶ 1,305:
</pre>
 
=={{header|CChipmunk SharpBasic}}==
{{works with|Chipmunk Basic|3.6.4}}
<lang C Sharp>
<syntaxhighlight lang="vbnet">100 numjugadores = 2
using System;
110 maxpuntos = 100
using System.IO;
120 dim almacenpuntos(3)
130 almacenpuntos(1) = 1
140 almacenpuntos(2) = 1
150 cls
160 print "The game of PIG"
170 print "===============";chr$(13);chr$(10)
180 print "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
190 print "Si jugador saca 2-6, se agrega al total del turno y su turno continúa."
200 print "Si jugador elige 'mantener', su total de puntos se añade a su puntuación,";
210 print " y se convierte en el turno del siguiente jugador.";chr$(10)
220 print "El primer jugador en anotar 100 o más puntos gana.";chr$(13);chr$(10)
230 while
240 for jugador = 1 to 2 'numjugadores
250 puntos = 0
260 while almacenpuntos(jugador) <= maxpuntos
270 print
280 print "Jugador ";jugador;": (";almacenpuntos(jugador);",";puntos;")";
290 input " ¿Tirada? (Sn) ",nuevotiro$
300 if ucase$(nuevotiro$) = "S" then
310 tirada = int(rnd(1)*5)+1
320 print " Tirada:";tirada
330 if tirada = 1 then
340 print chr$(10);"¡Pierdes tu turno! jugador ";jugador;
350 print " pero mantienes tu puntuación anterior de ";almacenpuntos(jugador)
360 exit while
370 endif
380 puntos = puntos+tirada
390 else
400 almacenpuntos(jugador) = almacenpuntos(jugador)+puntos
410 print " Te quedas con: ";almacenpuntos(jugador)
420 if almacenpuntos(jugador) >= maxpuntos then
430 print chr$(10);"Gana el Jugador ";jugador;" con ";almacenpuntos(jugador);" puntos."
440 end
450 endif
460 exit while
470 endif
480 wend
490 next jugador
500 wend false
510 end</syntaxhighlight>
 
=={{header|Clojure}}==
namespace Pig {
<syntaxhighlight lang="clojure">(def max 100)
 
(defn roll-dice []
class Roll {
(let [roll (inc (rand-int 6))]
public int TotalScore{get;set;}
(println "Rolled:" roll) roll))
public int RollScore{get;set;}
public bool Continue{get;set;}
}
 
(defn switch [player]
class Player {
(if (= player :player1) :player2 :player1))
public String Name{get;set;}
public int Score {get;set;}
Random rand;
 
(defn find-winner [game]
public Player() {
(cond
Score = 0;
(>= (:player1 game) max) :player1
rand = new Random();
(>= (:player2 game) max) :player2
}
:else nil))
 
(defn bust []
public Roll Roll(int LastScore){
(println "Busted!") 0)
Roll roll = new Roll();
roll.RollScore = rand.Next(6) + 1;
 
(defn hold [points]
if(roll.RollScore == 1){
(println "Sticking with" points) points)
roll.TotalScore = 0;
roll.Continue = false;
return roll;
}
 
(defn play-round [game player temp-points]
roll.TotalScore = LastScore + roll.RollScore;
(println (format "%s: (%s, %s). Want to Roll? (y/n) " (name player) (player game) temp-points))
roll.Continue = true;
(let [input (clojure.string/upper-case (read-line))]
return roll;
(if (.equals input "Y")
}
(let [roll (roll-dice)]
(if (= 1 roll)
(bust)
(play-round game player (+ roll temp-points))))
(hold temp-points))))
 
(defn play-game [game player]
public void FinalizeTurn(Roll roll){
(let [winner (find-winner game)]
Score = Score + roll.TotalScore;
(if (nil? winner)
}
(let [points (play-round game player 0)]
}
(recur (assoc game player (+ points (player game))) (switch player)))
(println (name winner) "wins!"))))
 
(defn -main [& args]
public class Game {
(println "Pig the Dice Game.")
public static void Main(String[] argv){
(play-game {:player1 0, :player2 0} :player1))</syntaxhighlight>
String input = null;
Player[] players = new Player[2];
 
=={{header|CLU}}==
// Game loop
<syntaxhighlight lang="clu">% This program uses the RNG included in PCLU's "misc.lib".
while(true){
Console.Write("Greetings! Would you like to play a game (y/n)?");
while(input == null){
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
players[0] = new Player();
players[1] = new Player();
Console.Write("Player One, what's your name?");
input = Console.ReadLine();
players[0].Name = input;
Console.Write("Player Two, what's your name?");
input = Console.ReadLine();
players[1].Name = input;
Console.WriteLine(players[0].Name + " and " + players[1].Name + ", prepare to do battle!");
} else if (input.ToLowerInvariant() == "n"){
goto Goodbye; /* Not considered harmful */
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
 
pig = cluster is play
// Play the game
rep = null
int currentPlayer = 0;
own pi: stream := stream$primary_input()
Roll roll = null;
own po: stream := stream$primary_output()
bool runTurn = true;
while(runTurn){
own scores: array[int] := array[int]$[0,0]
Player p = players[currentPlayer];
roll = p.Roll( (roll !=null) ? roll.TotalScore : 0 );
if(roll.Continue){
if(roll.TotalScore + p.Score > 99){
Console.WriteLine("Congratulations, " + p.Name + "! You rolled a " + roll.RollScore + " for a final score of " + (roll.TotalScore + p.Score) + "!");
runTurn = false;
} else {
Console.Write(p.Name + ": Roll " + roll.RollScore + "/Turn " + roll.TotalScore + "/Total " + (roll.TotalScore + p.Score) + ". Roll again (y/n)?");
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
// Do nothing
} else if (input.ToLowerInvariant() == "n"){
p.FinalizeTurn(roll);
currentPlayer = Math.Abs(currentPlayer - 1);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
Console.WriteLine(players[currentPlayer].Name + ", your turn begins.");
roll = null;
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
} else {
Console.WriteLine(p.Name + @", you rolled a 1 and lost your points for this turn.
Your current score: " + p.Score);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
currentPlayer = Math.Abs(currentPlayer - 1);
}
}
 
% Seed the RNG with the current time
init_rng = proc ()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
end init_rng
% Roll die
roll = proc () returns (int)
return(random$next(6) + 1)
end roll
% Read keypresses until one of the keys in 's' is pressed
accept = proc (s: string) returns (char)
own beep: string := string$ac2s(array[char]$[char$i2c(7), char$i2c(8)])
while true do
c: char := stream$getc(pi)
if string$indexc(c,s) ~= 0 then
stream$putl(po, "")
return(c)
end
stream$puts(po, beep)
end
end accept
% Print the current scores
print_scores = proc ()
stream$puts(po, "\nCurrent scores: ")
for p: int in array[int]$indexes(scores) do
stream$puts(po, "Player " || int$unparse(p)
|| " = " || int$unparse(scores[p]) || "\t")
end
stream$putl(po, "")
end print_scores
% Player P's turn
turn = proc (p: int)
stream$putl(po, "\nPlayer " || int$unparse(p) || "'s turn.")
t: int := 0
while true do
r: int := roll()
stream$puts(po, "Score: " || int$unparse(scores[p]))
stream$puts(po, " Turn: " || int$unparse(t))
stream$puts(po, " Roll: " || int$unparse(r))
if r=1 then
% Rolled a 1, turn is over, no points.
stream$putl(po, " - Too bad!")
break
end
% Add this roll to the score for this turn
t := t + r
stream$puts(po, "\tR)oll again, or H)old? ")
if accept("rh") = 'h' then
% The player stops, and receives the points for this turn.
scores[p] := scores[p] + t
break
end
end
stream$putl(po, "Player " || int$unparse(p) || "'s turn ends.")
end turn
% Play the game
play = proc ()
stream$putl(po, "Game of Pig\n---- -- ----")
init_rng()
scores[1] := 0 % Both players start out with 0 points
scores[2] := 0
% Players take turns until one of them has a score >= 100
p: int := 1
while scores[1] < 100 & scores[2] < 100 do
print_scores()
turn(p) p := 3-p
end
print_scores()
for i: int in array[int]$indexes(scores) do
if scores[i] >= 100 then
stream$putl(po, "Player " || int$unparse(i) || " wins!")
break
end
end
end play
end pig
 
start_up = proc()
input = null;
pig$play()
}
end start_up</syntaxhighlight>
Goodbye:
{{out}}
Console.WriteLine("Thanks for playing, and remember: the house ALWAYS wins!");
<pre style='height:50ex'>Game of Pig
System.Environment.Exit(0);
---- -- ----
}
 
}
Current scores: Player 1 = 0 Player 2 = 0
}
 
</lang>
Player 1's turn.
Score: 0 Turn: 0 Roll: 6 R)oll again, or H)old? r
Score: 0 Turn: 6 Roll: 6 R)oll again, or H)old? h
Player 1's turn ends.
 
Current scores: Player 1 = 12 Player 2 = 0
 
Player 2's turn.
Score: 0 Turn: 0 Roll: 4 R)oll again, or H)old? r
Score: 0 Turn: 4 Roll: 4 R)oll again, or H)old? r
Score: 0 Turn: 8 Roll: 2 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 12 Player 2 = 10
 
Player 1's turn.
Score: 12 Turn: 0 Roll: 2 R)oll again, or H)old? r
Score: 12 Turn: 2 Roll: 5 R)oll again, or H)old? r
Score: 12 Turn: 7 Roll: 1 - Too bad!
Player 1's turn ends.
 
Current scores: Player 1 = 12 Player 2 = 10
 
Player 2's turn.
Score: 10 Turn: 0 Roll: 5 R)oll again, or H)old? r
Score: 10 Turn: 5 Roll: 5 R)oll again, or H)old? r
Score: 10 Turn: 10 Roll: 4 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 12 Player 2 = 24
 
Player 1's turn.
Score: 12 Turn: 0 Roll: 2 R)oll again, or H)old? r
Score: 12 Turn: 2 Roll: 1 - Too bad!
Player 1's turn ends.
 
Current scores: Player 1 = 12 Player 2 = 24
 
Player 2's turn.
Score: 24 Turn: 0 Roll: 5 R)oll again, or H)old? r
Score: 24 Turn: 5 Roll: 5 R)oll again, or H)old? r
Score: 24 Turn: 10 Roll: 5 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 12 Player 2 = 39
 
Player 1's turn.
Score: 12 Turn: 0 Roll: 3 R)oll again, or H)old? r
Score: 12 Turn: 3 Roll: 3 R)oll again, or H)old? r
Score: 12 Turn: 6 Roll: 3 R)oll again, or H)old? r
Score: 12 Turn: 9 Roll: 6 R)oll again, or H)old? h
Player 1's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 39
 
Player 2's turn.
Score: 39 Turn: 0 Roll: 1 - Too bad!
Player 2's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 39
 
Player 1's turn.
Score: 27 Turn: 0 Roll: 3 R)oll again, or H)old? r
Score: 27 Turn: 3 Roll: 1 - Too bad!
Player 1's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 39
 
Player 2's turn.
Score: 39 Turn: 0 Roll: 1 - Too bad!
Player 2's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 39
 
Player 1's turn.
Score: 27 Turn: 0 Roll: 1 - Too bad!
Player 1's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 39
 
Player 2's turn.
Score: 39 Turn: 0 Roll: 4 R)oll again, or H)old? r
Score: 39 Turn: 4 Roll: 5 R)oll again, or H)old? r
Score: 39 Turn: 9 Roll: 3 R)oll again, or H)old? r
Score: 39 Turn: 12 Roll: 5 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 56
 
Player 1's turn.
Score: 27 Turn: 0 Roll: 5 R)oll again, or H)old? r
Score: 27 Turn: 5 Roll: 5 R)oll again, or H)old? r
Score: 27 Turn: 10 Roll: 1 - Too bad!
Player 1's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 56
 
Player 2's turn.
Score: 56 Turn: 0 Roll: 6 R)oll again, or H)old? r
Score: 56 Turn: 6 Roll: 5 R)oll again, or H)old? r
Score: 56 Turn: 11 Roll: 5 R)oll again, or H)old? r
Score: 56 Turn: 16 Roll: 4 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 27 Player 2 = 76
 
Player 1's turn.
Score: 27 Turn: 0 Roll: 2 R)oll again, or H)old? r
Score: 27 Turn: 2 Roll: 6 R)oll again, or H)old? r
Score: 27 Turn: 8 Roll: 3 R)oll again, or H)old? r
Score: 27 Turn: 11 Roll: 6 R)oll again, or H)old? h
Player 1's turn ends.
 
Current scores: Player 1 = 44 Player 2 = 76
 
Player 2's turn.
Score: 76 Turn: 0 Roll: 6 R)oll again, or H)old? r
Score: 76 Turn: 6 Roll: 2 R)oll again, or H)old? r
Score: 76 Turn: 8 Roll: 3 R)oll again, or H)old? r
Score: 76 Turn: 11 Roll: 2 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 44 Player 2 = 89
 
Player 1's turn.
Score: 44 Turn: 0 Roll: 4 R)oll again, or H)old? r
Score: 44 Turn: 4 Roll: 2 R)oll again, or H)old? r
Score: 44 Turn: 6 Roll: 5 R)oll again, or H)old? r
Score: 44 Turn: 11 Roll: 1 - Too bad!
Player 1's turn ends.
 
Current scores: Player 1 = 44 Player 2 = 89
 
Player 2's turn.
Score: 89 Turn: 0 Roll: 5 R)oll again, or H)old? r
Score: 89 Turn: 5 Roll: 2 R)oll again, or H)old? r
Score: 89 Turn: 7 Roll: 3 R)oll again, or H)old? r
Score: 89 Turn: 10 Roll: 5 R)oll again, or H)old? h
Player 2's turn ends.
 
Current scores: Player 1 = 44 Player 2 = 104
Player 2 wins!</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defconstant +max-score+ 100)
(defconstant +n-of-players+ 2)
 
Line 906 ⟶ 1,675:
(setf current-player (mod (1+ current-player) +n-of-players+)))))
(format t "~%Player ~d wins with a score of ~d~%" current-player
(nth current-player scores)))</langsyntaxhighlight>
{{out}}
<pre>Player 0: (0, 0). Rolling? (Y)
Line 941 ⟶ 1,710:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.algorithm, std.random;
enum maxScore = 100;
Line 977 ⟶ 1,746:
writefln("\n\nPlayer %d wins with a score of %d",
player, safeScore[player]);
}</langsyntaxhighlight>
{{out}}
<pre> Player 0: (0, 0). Rolling? (y/n)
Line 1,007 ⟶ 1,776:
 
Player 0 wins with a score of 101</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Console}}
{{Trans|Go}}
Thanks JensBorrisholt for library [https://github.com/JensBorrisholt/DelphiConsole System.Console].
<syntaxhighlight lang="delphi">program Pig_the_dice_game;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Console;
 
var
playerScores: TArray<Integer> = [0, 0];
turn: Integer = 0;
currentScore: Integer = 0;
player: Integer;
 
begin
Randomize;
 
turn := Random(length(playerScores));
writeln('Player ', turn, ' start:');
 
while True do
begin
Console.Clear;
 
for var i := 0 to High(playerScores) do
begin
Console.ForegroundColor := TConsoleColor(i mod 15 + 1);
Writeln(format('Player %2d has: %3d points', [i, playerScores[i]]));
end;
Writeln(#10);
 
player := turn mod length(playerScores);
Console.ForegroundColor := TConsoleColor(player mod 15 + 1);
 
writeln(format('Player %d [%d, %d], (H)old, (R)oll or (Q)uit: ', [player,
playerScores[player], currentScore]));
var answer := Console.ReadKey.KeyChar;
 
case UpCase(answer) of
'H':
begin
playerScores[player] := playerScores[player] + currentScore;
writeln(format(' Player %d now has a score of %d.'#10, [player,
playerScores[player]]));
if playerScores[player] >= 100 then
begin
writeln(' Player ', player, ' wins!!!');
readln;
halt;
end;
 
currentScore := 0;
inc(turn);
end;
 
'R':
begin
var roll := Random(6) + 1;
if roll = 1 then
begin
writeln(' Rolled a 1. Bust!'#10);
currentScore := 0;
inc(turn);
 
writeln('Press any key to pass turn');
Console.ReadKey;
end
else
begin
writeln(' Rolled a ', roll, '.');
inc(currentScore, roll);
end;
end;
'Q':
halt;
else
writeln(' Please enter one of the given inputs.');
end;
end;
writeln(format('Player %d wins!!!', [(turn - 1) mod Length(playerScores)]));
Readln;
end.</syntaxhighlight>
{{out}}
<pre>Player 0 has: 96 points
Player 1 has: 92 points
 
 
Player 1 [92, 8], (H)old, (R)oll or (Q)uit:
Player 1 now has a score of 100.
 
Player 1 wins!!!</pre>
 
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=lVVNj5swEL3zK16zVS+rIBO+kmrZSy89Vm0v1SqqWHAWawGvwFmS/vrKGBubZFctiiJmPB9v3syYgtcPe2R4wG6XYpem2Hv98bEDa5l4zbveA9AfG2Qg46vIhXk/NpMvAcFeql7q/Ew7ZAg833vpeIFH0eKEM8RJfIQPX1oVvOYdkiSRQs1aOrBSVAi2Um74K5Ue+gwn3CKIlWI6XCPCGWuEczRCRkyCnkTP/lAERhxTazh9xQcN4zEvnp86fmxLGeNBYR/LKGqadybfFun2nxKtvo0h1it8mphwLLdWRFW78vrJRV5/hvSSlFo4jGsspRvI/woZQqytBAqXLKHamxRJjGSkp6OFQEgQ7OazLdLoakVOCZUDIbLdk/RN+AqDwiqbvyHyt/rO63qldanSfeV1udKdaU9imp6pPRYXuM2kKLXsMI7jvRpBdzilVPFBvvoGbUCw2ziVpBelq6Am232GgOiIqshf/IiBt/iw0onUIowU07qnjvWPgYmi0tvg+772MvvhdnCOtzHgBWtoh43ne7xVgkaqLIPJ8QYdr+tJYAeIpmiFxYjmIYoQprNuHhpr3tRjJsYKwQ4oWUFxb/LO7N9m45mrt+4J9VgkXWucLttGR4h1OjI7DYGLKVtgMpN0GdoFobLEcbygahMhjBZ8BCGC8F2AyjV1WJ7wdXlbslYgWZTj0qY6t3bKud5QMx7Ej99hWNsEl0T4am7ncdq4c7jcJ9tU0zAWTIzpWxOl6CMEoWs5k6f3NHR37kvNimcceIeWDnjKG7pYvkgty3SByDUwd4e1I5q/4Oq9rShSW9bwY09/l3xo3VXTsNhhMjnJPSDI29Io7hDFluK8tDjjbq5PsjIv7cjtHDhZBt79V+Dl9F90Wk+2/YV3bk7fM0ej8i8= Run it]
 
<syntaxhighlight>
col[] = [ 997 977 ]
subr initvars
sum = 0
stat = 0
sum[] = [ 0 0 ]
player = 1
.
proc btn x y txt$ . .
color 666
linewidth 18
move x y
line x + 15 y
move x - 4 y - 3
color 000
textsize 10
text txt$
.
proc show . .
background col[player]
clear
move 8 78
color 000
textsize 10
text "Player-" & player
textsize 8
move 8 66
text "Total: " & sum[player]
textsize 5
#
h = 3 - player
color col[h]
move 65 63
rect 30 19
move 68 74
color 000
text "Player-" & h
textsize 4
move 68 67
text "Total: " & sum[h]
#
btn 20 20 "Roll"
btn 70 20 "Hold"
.
proc nxtplayer . .
sum[player] += sum
if sum > 0
sum = 0
show
.
move 10 92
textsize 7
color 000
if sum[player] >= 100
text "You won !"
stat = 3
else
text "Switch player ..."
player = 3 - player
stat = 2
.
timer 2
.
on timer
if stat = 1
# roll
if tmcnt = 0
move 44 37
color col[player]
rect 30 10
if dice > 1
sum += dice
stat = 0
else
sum = 0
.
color 000
text sum
if dice = 1
nxtplayer
.
else
color 555
move 24 34
rect 13 13
color 000
move 27 37
dice = randint 6
text dice
tmcnt -= 1
if tmcnt = 0
timer 0.5
else
timer 0.1
.
.
elif stat = 2
stat = 0
show
elif stat = 3
move 0 0
color col[player]
rect 100 30
color 000
move 10 30
text "Click for new game"
stat = 4
.
.
proc roll . .
stat = 1
tmcnt = 10
textsize 10
timer 0
.
on mouse_down
if stat = 0
if mouse_x > 10 and mouse_x < 45 and mouse_y > 10 and mouse_y < 30
roll
elif mouse_x > 60 and mouse_x < 95 and mouse_y > 10 and mouse_y < 30
nxtplayer
.
elif stat = 4
initvars
show
.
.
initvars
show
</syntaxhighlight>
 
=={{header|Eiffel}}==
 
<syntaxhighlight lang="eiffel">
class
PLAYER
create
set_name
feature
set_name(n:STRING)
do
name := n.twin
set_points(0)
end
 
strategy(cur_points:INTEGER)
local
current_points, thrown:INTEGER
do
io.put_string ("You currently have " +points.out+". %NDo you want to save your points? Press y or n.%N")
io.read_line
if io.last_string.same_string ("y") then
set_points(cur_points)
else
io.put_string ("Then throw again.%N")
thrown:=throw_dice
if thrown= 1 then
io.put_string("You loose your points%N")
else
strategy(cur_points+thrown)
end
end
 
end
set_points (value:INTEGER)
require
value_not_neg: value >= 0
do
points := points + value
end
 
random: V_RANDOM
-- Random sequence.
once
create Result
end
throw_dice: INTEGER
do
random.forth
Result := random.bounded_item (1, 6)
end
 
name: STRING
points: INTEGER
end
</syntaxhighlight>
<syntaxhighlight lang="eiffel">
class
PIG_THE_DICE
 
feature
play
local
points, i: INTEGER
do
io.put_string("Welcome to the game.%N")
initiate_players
from
 
until
winner/=void
loop
across player as p loop
points:=p.item.throw_dice
io.put_string ("%N" + p.item.name +" you throwed " + points.out + ".%N")
if points =1 then
io.put_string ("You loose your points.%N")
else
p.item.strategy(points)
end
if p.item.points >=100 then
winner := p.item
io.put_string ("%NThe winner is " + winner.name.out + ".%N")
end
end
end
end
 
initiate_players
local
p1,p2: PLAYER
do
create player.make (1, 2)
create p1.set_name ("Player1")
player.put (p1, 1)
create p2.set_name ("Player2")
player.put (p2, 2)
end
 
player: V_ARRAY[PLAYER]
winner: PLAYER
end
</syntaxhighlight>
Test:
<syntaxhighlight lang="eiffel">
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
local
do
create pig
pig.initiate_players
pig.play
end
pig: PIG_THE_DICE
end
</syntaxhighlight>
{{out}}
<pre>
Welcome to the game.
 
Player1 you throwed 4.
You currently have 0.
Do you want to save your points? Press y or no.
y
 
Player2 you throwed 3.
You currently have 0.
Do you want to save your points? Press y or no.
n
Then throw again.
...
Player2 you throwed 6.
You currently have 98.
Do you want to save your points? Press y or n.
y
 
The winner is Player2.
</pre>
 
=={{header|Erlang}}==
Some of the code (ex: quit/2) is only there to make play during development easier. Some (ex: player_name/1) is only there to make [[Pig_the_dice_game/Player]] easier.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( pig_dice ).
 
Line 1,107 ⟶ 2,251:
[io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest];
task_display( Result ) -> io:fwrite( "Result: ~p~n", [Result] ).
</syntaxhighlight>
</lang>
{{out}}
Start of game:
Line 1,162 ⟶ 2,306:
Roll again (y/n/q):
</pre>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 T "GAME OF PIG"!
01.20 S S(1)=0;S S(2)=0;S P=1
01.30 T !"PLAYER",%1,P," TURN BEGINS"!
01.40 D 3;I (99-S(P))1.7
01.50 S P=3-P
01.60 G 1.3
01.70 T !"THE WINNER IS PLAYER",%1,P,!
01.80 Q
 
02.10 S A=10*FRAN();S A=1+FITR(6*(A-FITR(A)))
 
03.10 S T=0
03.20 T "PLAYER",%1,P," SCORE",%3,S(P)," TURN",%3,T
03.25 D 2;T " ROLL",%1,A," "
03.30 I (A-2)3.55;S T=T+A
03.35 A "- R)OLL OR H)OLD",C
03.40 I (C-0R)3.45,3.2,3.45
03.45 I (C-0H)3.5,3.6,3.5
03.50 T "INVALID INPUT ";G 3.35
03.55 T "- TOO BAD!"!;S T=0
03.60 S S(P)=S(P)+T
03.65 T "PLAYER",%1,P," SCORE",%3,S(P)," TURN FINISHED"!</syntaxhighlight>
 
=={{header|Forth}}==
{{works with|4tH|3.62.1}}
<langsyntaxhighlight lang="forth">include lib/choose.4th
include lib/yesorno.4th
 
Line 1,185 ⟶ 2,353:
; \ show the results
 
pigthedice</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Const numjugadores = 2
Const maxpuntos = 100
Dim As Byte almacenpuntos(numjugadores), jugador, puntos, tirada
Dim As String nuevotiro
 
Cls: Color 15: Print "The game of PIG"
Print String(15, "=") + Chr(13) + Chr(10): Color 7
Print "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
Print "Si jugador saca 2-6, se agrega al total del turno y su turno continúa."
Print "Si jugador elige 'mantener', su total de puntos se añade a su puntuación, "
Print " y se convierte en el turno del siguiente jugador." + Chr(10)
Print "El primer jugador en anotar 100 o más puntos gana." + Chr(13) + Chr(10): Color 7
 
Do
For jugador = 1 To numjugadores
puntos = 0
While almacenpuntos(jugador) <= maxpuntos
Color 15: Print
Print Using "Jugador #: (&_, &)"; jugador;almacenpuntos(jugador);puntos;: Color 11
Input " ¿Tirada? (Sn) ", nuevotiro
If Ucase(nuevotiro) = "S" Then
tirada = Int(Rnd* 5) + 1
Print " Tirada:"; tirada
If tirada = 1 Then
Color 11: Print Chr(10) + "­¡Pierdes tu turno! jugador"; jugador;
Print " pero mantienes tu puntuación anterior de "; almacenpuntos(jugador): Color 7
Exit While
End If
puntos = puntos + tirada
Else
almacenpuntos(jugador) = almacenpuntos(jugador) + puntos
Print " Te quedas con:"; almacenpuntos(jugador)
If almacenpuntos(jugador) >= maxpuntos Then
Color 14: Print Chr(10) + "Gana el jugador"; jugador; " con"; almacenpuntos(jugador); " puntos."
Sleep: End
End If
Exit While
End If
Wend
Next jugador
Loop
</syntaxhighlight>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math/rand"
"strings"
"time"
)
 
func main() {
rand.Seed(time.Now().UnixNano()) //Set seed to current time
 
playerScores := [...]int{0, 0}
turn := 0
currentScore := 0
 
for {
player := turn % len(playerScores)
 
fmt.Printf("Player %v [%v, %v], (H)old, (R)oll or (Q)uit: ", player,
playerScores[player], currentScore)
 
var answer string
fmt.Scanf("%v", &answer)
switch strings.ToLower(answer) {
case "h": //Hold
playerScores[player] += currentScore
fmt.Printf(" Player %v now has a score of %v.\n\n", player, playerScores[player])
 
if playerScores[player] >= 100 {
fmt.Printf(" Player %v wins!!!\n", player)
return
}
 
currentScore = 0
turn += 1
case "r": //Roll
roll := rand.Intn(6) + 1
 
if roll == 1 {
fmt.Printf(" Rolled a 1. Bust!\n\n")
currentScore = 0
turn += 1
} else {
fmt.Printf(" Rolled a %v.\n", roll)
currentScore += roll
}
case "q": //Quit
return
default: //Incorrent input
fmt.Print(" Please enter one of the given inputs.\n")
}
}
fmt.Printf("Player %v wins!!!\n", (turn-1)%len(playerScores))
}</syntaxhighlight>
 
=={{header|Groovy}}==
Currently hard coded for 2 players, but will work for multiple players
<syntaxhighlight lang="groovy">
<lang Groovy>
class PigDice {
 
Line 1,284 ⟶ 2,555:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
import System.Random (randomRIO)
 
data Score = Score { stack :: Int, score :: Int }
 
main :: IO ()
main = loop (Score 0 0) (Score 0 0)
 
loop :: Score -> Score -> IO ()
loop p1 p2 = do
putStrLn $ "\nPlayer 1 ~ " ++ show (score p1)
p1' <- askPlayer p1
if (score p1') >= 100
then putStrLn "P1 won!"
else do
putStrLn $ "\nPlayer 2 ~ " ++ show (score p2)
p2' <- askPlayer p2
if (score p2') >= 100
then putStrLn "P2 won!"
else loop p1' p2'
 
 
askPlayer :: Score -> IO Score
askPlayer (Score stack score) = do
putStr "\n(h)old or (r)oll? "
answer <- getChar
roll <- randomRIO (1,6)
case (answer, roll) of
('h', _) -> do
putStrLn $ " => Score = " ++ show (stack + score)
return $ Score 0 (stack + score)
('r', 1) -> do
putStrLn $ " => 1 => Sorry - stack was resetted"
return $ Score 0 score
('r', _) -> do
putStr $ " => " ++ show roll ++ " => current stack = " ++ show (stack + roll)
askPlayer $ Score (stack + roll) score
_ -> do
putStrLn "\nInvalid input - please try again."
askPlayer $ Score stack score
</syntaxhighlight>
 
Example output:
 
<pre>
 
Player 1 ~ 0
 
(h)old or (r)oll? r => 5 => current stack = 5
(h)old or (r)oll? r => 5 => current stack = 10
(h)old or (r)oll? r => 3 => current stack = 13
(h)old or (r)oll? r => 4 => current stack = 17
(h)old or (r)oll? h => Score = 17
 
Player 2 ~ 0
 
(h)old or (r)oll? r => 4 => current stack = 4
(h)old or (r)oll? r => 3 => current stack = 7
(h)old or (r)oll? r => 1 => Sorry - stack was resetted
 
Player 1 ~ 17
 
(h)old or (r)oll? r => 5 => current stack = 5
(h)old or (r)oll? r => 2 => current stack = 7
(h)old or (r)oll? h => Score = 24
 
...
 
Player 1 ~ 52
 
(h)old or (r)oll? r => 4 => current stack = 4
(h)old or (r)oll? r => 3 => current stack = 7
(h)old or (r)oll? r => 4 => current stack = 11
(h)old or (r)oll? r => 4 => current stack = 15
(h)old or (r)oll? r => 1 => Sorry - stack was resetted
 
Player 2 ~ 97
 
(h)old or (r)oll? r => 4 => current stack = 4
(h)old or (r)oll? h => Score = 101
P2 won!
 
</pre>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'general/misc/prompt' NB. was require'misc' in j6
 
status=:3 :0
Line 1,300 ⟶ 2,656:
getmove=:3 :0
whilst.1~:+/choice do.
choice=.'HRQ' e. prompt ' ..Roll the dice or Hold or Quit? [R or H or Q]: '
end.
choice#'HRQ'
Line 1,311 ⟶ 2,667:
while.100>>./scores do.
for_player.=i.y do.
smoutput 'begining of turn for player ',":pid=.1+I.player
smoutput 'begining of turn for player ',":pid
current=. 0
whilst. (1 ~: roll) *. 'R' = move do.
status pid, current, player+/ .*scores
if.'R'=move=. getmove'' do.
smoutput 'rolled a ',":roll=. 1+?6
if.'R' current=move. (1~:roll)*current+roll end. doend.
smoutput 'rolled a ',":roll
current=. (1~:roll)*current+roll
end.
end.
scores=. scores+(current*player)+100*('Q'e.move)*-.player
smoutput 'player scores now: ',":scores end. end.
end.
end.
smoutput 'player ',(":1+I.scores>:100),' wins'
)</langsyntaxhighlight>
 
Example game:
 
<syntaxhighlight lang="text"> pigsim 2
2 player game of pig
begining of turn for player 1
player 1 potential: 0 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 3
player 1 potential: 3 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 6
player 1 potential: 9 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 4
player 1 potential: 13 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 6
player 1 potential: 19 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 2
player 1 potential: 21 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: H
player scores now: 21 0
begining of turn for player 2
player 2 potential: 0 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 3
player 2 potential: 3 total: 0
Line 1,364 ⟶ 2,713:
rolled a 4
player 2 potential: 13 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 6
player 2 potential: 19 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 3
player 2 potential: 22 total: 0
..Roll the dice or Hold or Quit? [R or H or Q]: H
player scores now: 21 22
begining of turn for player 1
player 1 potential: 0 total: 21
..Roll the dice or Hold or Quit? [R or H or Q]: R
 
...
 
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 6
player 1 potential: 22 total: 62
..Roll the dice or Hold or Quit? [R or H or Q]: H
player scores now: 84 90
begining of turn for player 2
player 2 potential: 0 total: 90
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 6
player 2 potential: 6 total: 90
..Roll the dice or Hold or Quit? [R or H or Q]: R
rolled a 6
player 2 potential: 12 total: 90
..Roll the dice or Hold or Quit? [R or H or Q]: H
player scores now: 84 102
player 2 wins</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
<langsyntaxhighlight lang="java">import java.util.*;
 
public class PigDice {
Line 1,438 ⟶ 2,787:
player, safeScore[player]);
}
}</langsyntaxhighlight>
 
{{works with|Java|8+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
Line 1,507 ⟶ 2,856:
;
}
}</langsyntaxhighlight>
 
<pre> Player 0: (0, 0) Rolling? (y/n) y
Line 1,544 ⟶ 2,893:
Player 1 wins with a score of 102</pre>
 
 
=={{header|Mathematica}}==
=={{header|JavaScript}}==
<lang>DynamicModule[{score, players = {1, 2}, roundscore = 0,
<syntaxhighlight lang="javascript">let players = [
{ name: '', score: 0 },
{ name: '', score: 0 }
];
let curPlayer = 1,
gameOver = false;
 
players[0].name = prompt('Your name, player #1:').toUpperCase();
players[1].name = prompt('Your name, player #2:').toUpperCase();
 
function roll() { return 1 + Math.floor(Math.random()*6) }
 
function round(player) {
let curSum = 0,
quit = false,
dice;
alert(`It's ${player.name}'s turn (${player.score}).`);
while (!quit) {
dice = roll();
if (dice == 1) {
alert('You roll a 1. What a pity!');
quit = true;
} else {
curSum += dice;
quit = !confirm(`
You roll a ${dice} (sum: ${curSum}).\n
Roll again?
`);
if (quit) {
player.score += curSum;
if (player.score >= 100) gameOver = true;
}
}
}
}
// main
while (!gameOver) {
if (curPlayer == 0) curPlayer = 1; else curPlayer = 0;
round(players[curPlayer]);
if (gameOver) alert(`
${players[curPlayer].name} wins (${players[curPlayer].score}).
`);
}
</syntaxhighlight>
 
=={{header|Julia}}==
The game is built around the <tt>PigPlayer</tt> type, which contains the player information, including a reference to the strategy function, <tt>strat</tt>, that is to be used to determined whether a player is going to continue to roll. In this incarnation of the game, there is only one strategy function available, <tt>pig_manual</tt>, which gets this decision from user input.
<syntaxhighlight lang="julia">
type PigPlayer
name::String
score::Int
strat::Function
end
 
function PigPlayer(a::String)
PigPlayer(a, 0, pig_manual)
end
 
function scoreboard(pps::Array{PigPlayer,1})
join(map(x->@sprintf("%s has %d", x.name, x.score), pps), " | ")
end
 
function pig_manual(pps::Array{PigPlayer,1}, pdex::Integer, pot::Integer)
pname = pps[pdex].name
print(pname, " there is ", @sprintf("%3d", pot), " in the pot. ")
print("<ret> to continue rolling? ")
return chomp(readline()) == ""
end
 
function pig_round(pps::Array{PigPlayer,1}, pdex::Integer)
pot = 0
rcnt = 0
while pps[pdex].strat(pps, pdex, pot)
rcnt += 1
roll = rand(1:6)
if roll == 1
return (0, rcnt, false)
else
pot += roll
end
end
return (pot, rcnt, true)
end
 
function pig_game(pps::Array{PigPlayer,1}, winscore::Integer=100)
pnum = length(pps)
pdex = pnum
println("Playing a game of Pig the Dice.")
while(pps[pdex].score < winscore)
pdex = rem1(pdex+1, pnum)
println(scoreboard(pps))
println(pps[pdex].name, " is now playing.")
(pot, rcnt, ispotwon) = pig_round(pps, pdex)
print(pps[pdex].name, " played ", rcnt, " rolls ")
if ispotwon
println("and scored ", pot, " points.")
pps[pdex].score += pot
else
println("and butsted.")
end
end
println(pps[pdex].name, " won, scoring ", pps[pdex].score, " points.")
end
 
pig_game([PigPlayer("Alice"), PigPlayer("Bob")])
</syntaxhighlight>
 
{{out}}
<pre>
Playing a game of Pig the Dice.
Alice has 0 | Bob has 0
Alice is now playing.
Alice there is 0 in the pot. <ret> to continue rolling?
Alice there is 3 in the pot. <ret> to continue rolling?
Alice there is 7 in the pot. <ret> to continue rolling?
Alice there is 13 in the pot. <ret> to continue rolling?
Alice there is 15 in the pot. <ret> to continue rolling?
Alice there is 18 in the pot. <ret> to continue rolling?
Alice played 5 rolls and scored 18 points.
Alice has 18 | Bob has 0
Bob is now playing.
Bob there is 0 in the pot. <ret> to continue rolling?
Bob played 1 rolls and butsted.
Alice has 18 | Bob has 0
Alice is now playing.
Alice there is 0 in the pot. <ret> to continue rolling?
Alice there is 2 in the pot. <ret> to continue rolling?
Alice played 2 rolls and butsted.
...
Alice has 54 | Bob has 94
Alice is now playing.
Alice there is 0 in the pot. <ret> to continue rolling?
Alice there is 3 in the pot. <ret> to continue rolling?
Alice there is 9 in the pot. <ret> to continue rolling?
Alice there is 12 in the pot. <ret> to continue rolling?
Alice there is 17 in the pot. <ret> to continue rolling?
Alice there is 22 in the pot. <ret> to continue rolling?
Alice there is 27 in the pot. <ret> to continue rolling?
Alice there is 31 in the pot. <ret> to continue rolling?
Alice played 7 rolls and scored 31 points.
Alice has 85 | Bob has 94
Bob is now playing.
Bob there is 0 in the pot. <ret> to continue rolling?
Bob there is 3 in the pot. <ret> to continue rolling?
Bob there is 5 in the pot. <ret> to continue rolling?
Bob there is 8 in the pot. <ret> to continue rolling?
Bob played 3 rolls and scored 8 points.
Bob won, scoring 102 points.
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun main(Args: Array<String>) {
print("Player 1 - Enter your name : ")
val name1 = readLine()!!.trim().let { if (it == "") "PLAYER 1" else it.toUpperCase() }
print("Player 2 - Enter your name : ")
val name2 = readLine()!!.trim().let { if (it == "") "PLAYER 2" else it.toUpperCase() }
val names = listOf(name1, name2)
val r = java.util.Random()
val totals = intArrayOf(0, 0)
var player = 0
while (true) {
println("\n${names[player]}")
println(" Your total score is currently ${totals[player]}")
var score = 0
while (true) {
print(" Roll or Hold r/h : ")
val rh = readLine()!![0].toLowerCase()
if (rh == 'h') {
totals[player] += score
println(" Your total score is now ${totals[player]}")
if (totals[player] >= 100) {
println(" So, ${names[player]}, YOU'VE WON!")
return
}
player = if (player == 0) 1 else 0
break
}
if (rh != 'r') {
println(" Must be 'r'or 'h', try again")
continue
}
val dice = 1 + r.nextInt(6)
println(" You have thrown a $dice")
if (dice == 1) {
println(" Sorry, your score for this round is now 0")
println(" Your total score remains at ${totals[player]}")
player = if (player == 0) 1 else 0
break
}
score += dice
println(" Your score for the round is now $score")
}
}
}</syntaxhighlight>
 
{{out}}
<pre>
Player 1 - Enter your name : Donald
Player 2 - Enter your name : Barack
 
DONALD
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 6
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 8
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 12
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 14
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 18
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 24
Roll or Hold r/h : h
Your total score is now 24
 
BARACK
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 5
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 7
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 10
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 15
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 19
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 23
Roll or Hold r/h : h
Your total score is now 23
 
DONALD
Your total score is currently 24
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 5
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 10
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 14
Roll or Hold r/h : r
You have thrown a 1
Sorry, your score for this round is now 0
Your total score remains at 24
.........
.........
DONALD
Your total score is currently 81
Roll or Hold r/h : r
You have thrown a 1
Sorry, your score for this round is now 0
Your total score remains at 81
 
BARACK
Your total score is currently 85
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 5
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 7
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 10
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 13
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 18
Roll or Hold r/h : h
Your total score is now 103
So, BARACK, YOU'VE WON!
</pre>
 
=={{header|Lua}}==
{{works with|lua|5.1}}
Supports any number of players
<syntaxhighlight lang="lua">local numPlayers = 2
local maxScore = 100
local scores = { }
for i = 1, numPlayers do
scores[i] = 0 -- total safe score for each player
end
math.randomseed(os.time())
print("Enter a letter: [h]old or [r]oll?")
local points = 0 -- points accumulated in current turn
local p = 1 -- start with first player
while true do
io.write("\nPlayer "..p..", your score is ".. scores[p]..", with ".. points.." temporary points. ")
local reply = string.sub(string.lower(io.read("*line")), 1, 1)
if reply == 'r' then
local roll = math.random(6)
io.write("You rolled a " .. roll)
if roll == 1 then
print(". Too bad. :(")
p = (p % numPlayers) + 1
points = 0
else
points = points + roll
end
elseif reply == 'h' then
scores[p] = scores[p] + points
if scores[p] >= maxScore then
print("Player "..p..", you win with a score of "..scores[p])
break
end
print("Player "..p..", your new score is " .. scores[p])
p = (p % numPlayers) + 1
points = 0
end
end
</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module GamePig {
Print "Game of Pig"
dice=-1
res$=""
Player1points=0
Player1sum=0
Player2points=0
Player2sum=0
HaveWin=False
score()
\\ for simulation, feed the keyboard buffer with R and H
simulate$=String$("R", 500)
For i=1 to 100
Insert Random(1,Len(simulate$)) simulate$="H"
Next i
Keyboard simulate$
\\ end simulation
while res$<>"Q" {
Print "Player 1 turn"
PlayerTurn(&Player1points, &player1sum)
if res$="Q" then exit
Player1sum+=Player1points
Score()
Print "Player 2 turn"
PlayerTurn(&Player2points,&player2sum)
if res$="Q" then exit
Player2sum+=Player2points
Score()
}
If HaveWin then {
Score()
If Player1Sum>Player2sum then {
Print "Player 1 Win"
} Else Print "Player 2 Win"
}
Sub Rolling()
dice=random(1,6)
Print "dice=";dice
End Sub
Sub PlayOrQuit()
Print "R -Roling Q -Quit"
Repeat {
res$=Ucase$(Key$)
} Until Instr("RQ", res$)>0
End Sub
Sub PlayAgain()
Print "R -Roling H -Hold Q -Quit"
Repeat {
res$=Ucase$(Key$)
} Until Instr("RHQ", res$)>0
End Sub
Sub PlayerTurn(&playerpoints, &sum)
PlayOrQuit()
If res$="Q" then Exit Sub
playerpoints=0
Rolling()
While dice<>1 and res$="R" {
playerpoints+=dice
if dice>1 and playerpoints+sum>100 then {
sum+=playerpoints
HaveWin=True
res$="Q"
} Else {
PlayAgain()
if res$="R" then Rolling()
}
}
if dice=1 then playerpoints=0
End Sub
Sub Score()
Print "Player1 points="; Player1sum
Print "Player2 points="; Player2sum
End Sub
}
GamePig
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">pig := proc()
local Points, pointsThisTurn, answer, rollNum, i, win;
randomize();
Points := [0, 0];
win := [false, 0];
while not win[1] do
for i to 2 do
if not win[1] then
printf("Player %a's turn.\n", i);
answer := "";
pointsThisTurn := 0;
while not answer = "HOLD" do
while not answer = "ROLL" and not answer = "HOLD" do
printf("Would you like to ROLL or HOLD?\n");
answer := StringTools:-UpperCase(readline());
if not answer = "ROLL" and not answer = "HOLD" then
printf("Invalid answer.\n\n");
end if;
end do;
if answer = "ROLL" then
rollNum := rand(1..6)();
printf("You rolled a %a!\n", rollNum);
if rollNum = 1 then
pointsThisTurn := 0;
answer := "HOLD";
else
pointsThisTurn := pointsThisTurn + rollNum;
answer := "";
printf("Your points so far this turn: %a.\n\n", pointsThisTurn);
end if;
end if;
end do;
printf("This turn is over! Player %a gained %a points this turn.\n\n", i, pointsThisTurn);
Points[i] := Points[i] + pointsThisTurn;
if Points[i] >= 100 then
win := [true, i];
end if;
printf("Player 1 has %a points. Player 2 has %a points.\n\n", Points[1], Points[2]);
end if;
end do;
end do;
printf("Player %a won with %a points!\n", win[2], Points[win[2]]);
end proc;
 
pig();</syntaxhighlight>
{{out}}
<pre>
Player 1's turn.
Would you like to ROLL or HOLD?
You rolled a 5!
Your points so far this turn: 5.
 
Would you like to ROLL or HOLD?
This turn is over! Player 1 gained 5 points this turn.
 
Player 1 has 5 points. Player 2 has 0 points.
 
Player 2's turn.
Would you like to ROLL or HOLD?
You rolled a 6!
Your points so far this turn: 6.
 
Would you like to ROLL or HOLD?
You rolled a 1!
This turn is over! Player 2 gained 0 points this turn.
 
Player 1 has 5 points. Player 2 has 0 points.
 
Player 1's turn.
Would you like to ROLL or HOLD?
 
...
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">DynamicModule[{score, players = {1, 2}, roundscore = 0,
roll}, (score@# = 0) & /@ players;
Panel@Dynamic@
Line 1,562 ⟶ 3,401:
players = RotateLeft@players]]},
Button["Play again.",
roundscore = 0; (score@# = 0) & /@ players]]}]</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">// Pig the Dice for two players.
Player = {}
Player.score = 0
Player.doTurn = function()
rolls = 0
pot = 0
print self.name + "'s Turn!"
while true
if self.score + pot >= goal then
print " " + self.name.upper + " WINS WITH " + (self.score + pot) + "!"
inp = "H"
else
inp = input(self.name + ", you have " + pot + " in the pot. [R]oll or Hold? ")
end if
if inp == "" or inp[0].upper == "R" then
die = ceil(rnd*6)
if die == 1 then
print " You roll a 1. Busted!"
return
else
print " You roll a " + die + "."
pot = pot + die
end if
else
self.score = self.score + pot
return
end if
end while
end function
 
p1 = new Player
p1.name = "Alice"
p2 = new Player
p2.name = "Bob"
goal = 100
 
while p1.score < goal and p2.score < goal
for player in [p1, p2]
print
print p1.name + ": " + p1.score + " | " + p2.name + ": " + p2.score
player.doTurn
if player.score >= goal then break
end for
end while</syntaxhighlight>
 
{{out}}
<pre>Alice: 0 | Bob: 0
Alice's Turn!
Alice, you have 0 in the pot. [R]oll or Hold?
You roll a 4.
Alice, you have 4 in the pot. [R]oll or Hold?
You roll a 5.
Alice, you have 9 in the pot. [R]oll or Hold?
You roll a 5.
Alice, you have 14 in the pot. [R]oll or Hold? h
 
Alice: 14 | Bob: 0
Bob's Turn!
Bob, you have 0 in the pot. [R]oll or Hold?
You roll a 6.
Bob, you have 6 in the pot. [R]oll or Hold?
You roll a 4.
Bob, you have 10 in the pot. [R]oll or Hold?
You roll a 4.
Bob, you have 14 in the pot. [R]oll or Hold?
You roll a 6.
Bob, you have 20 in the pot. [R]oll or Hold? h
 
Alice: 14 | Bob: 20
Alice's Turn!
Alice, you have 0 in the pot. [R]oll or Hold?
You roll a 1. Busted!
 
...
 
Alice: 49 | Bob: 90
Bob's Turn!
Bob, you have 0 in the pot. [R]oll or Hold?
You roll a 5.
Bob, you have 5 in the pot. [R]oll or Hold?
You roll a 3.
Bob, you have 8 in the pot. [R]oll or Hold?
You roll a 6.
BOB WINS WITH 104!</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import random, strformat, strutils
 
randomize()
 
stdout.write "Player 1 - Enter your name : "
let name1 = block:
let n = stdin.readLine().strip()
if n.len == 0: "PLAYER 1" else: n.toUpper
stdout.write "Player 2 - Enter your name : "
let name2 = block:
let n = stdin.readLine().strip()
if n.len == 0: "PLAYER 2" else: n.toUpper
 
let names = [name1, name2]
var totals: array[2, Natural]
var player = 0
 
while true:
echo &"\n{names[player]}"
echo &" Your total score is currently {totals[player]}"
var score = 0
 
while true:
stdout.write " Roll or Hold r/h : "
let rh = stdin.readLine().toLowerAscii()
case rh
 
of "h":
inc totals[player], score
echo &" Your total score is now {totals[player]}"
if totals[player] >= 100:
echo &" So, {names[player]}, YOU'VE WON!"
quit QuitSuccess
player = 1 - player
break
 
of "r":
let dice = rand(1..6)
echo &" You have thrown a {dice}"
if dice == 1:
echo " Sorry, your score for this round is now 0"
echo &" Your total score remains at {totals[player]}"
player = 1 - player
break
inc score, dice
echo &" Your score for the round is now {score}"
 
else:
echo " Must be 'r' or 'h', try again"</syntaxhighlight>
 
{{out}}
<pre>Player 1 - Enter your name :
Player 2 - Enter your name :
 
PLAYER 1
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 4
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 10
Roll or Hold r/h : h
Your total score is now 10
 
PLAYER 2
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 2
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 8
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 12
Roll or Hold r/h : h
Your total score is now 12
 
PLAYER 1
Your total score is currently 10
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 4
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 9
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 14
Roll or Hold r/h : h
Your total score is now 24
 
PLAYER 2
Your total score is currently 12
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 5
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 11
Roll or Hold r/h : h
Your total score is now 23
.........</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Pig {
function : Main(args : String[]) ~ Nil {
Line 1,604 ⟶ 3,637:
}
}
</syntaxhighlight>
</lang>
<pre>
Player 0: (0, 0) Rolling? (y/n)
Line 1,636 ⟶ 3,669:
n
</pre>
 
=={{header|OCaml}}==
 
<syntaxhighlight lang="ocaml">class player (name_init : string) =
object
val name = name_init
val mutable total = 0
val mutable turn_score = 0
method get_name = name
method get_score = total
method end_turn = total <- total + turn_score;
turn_score <- 0;
method has_won = total >= 100;
method rolled roll = match roll with
1 -> turn_score <- 0;
|_ -> turn_score <- turn_score + roll;
end;;
 
let print_seperator () =
print_endline "#####";;
 
let rec one_turn p1 p2 =
Printf.printf "What do you want to do %s?\n" p1#get_name;
print_endline " 1)Roll the dice?";
print_endline " 2)Or end your turn?";
let choice = read_int () in
if choice = 1 then
begin
let roll = 1 + Random.int 6 in
Printf.printf "Rolled a %d\n" roll;
p1#rolled roll;
match roll with
1 -> print_seperator ();
one_turn p2 p1
|_ -> one_turn p1 p2
end
else if choice = 2 then
begin
p1#end_turn;
match p1#has_won with
false -> Printf.printf "%s's score is now %d\n" p1#get_name p1#get_score;
print_seperator();
one_turn p2 p1;
|true -> Printf.printf "Congratulations %s! You've won\n" p1#get_name
end
else
begin
print_endline "That's not a choice! Make a real one!";
one_turn p1 p2
end;;
 
Random.self_init ();
let p1 = new player "Steven"
and p2 = new player "John" in
one_turn p1 p2;;</syntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal|2.6.4}}
 
<syntaxhighlight lang="pascal">program Pig;
 
const
WinningScore = 100;
 
type
DieRoll = 1..6;
Score = integer;
Player = record
Name: string;
Points: score;
Victory: Boolean
end;
 
{ Assume a 2-player game. }
var Player1, Player2: Player;
 
function RollTheDie: DieRoll;
{ Return a random number 1 thru 6. }
begin
RollTheDie := random(6) + 1
end;
 
procedure TakeTurn (var P: Player);
{ Play a round of Pig. }
var
Answer: char;
Roll: DieRoll;
NewPoints: Score;
KeepPlaying: Boolean;
begin
NewPoints := 0;
writeln ;
writeln('It''s your turn, ', P.Name, '!');
writeln('So far, you have ', P.Points, ' points in all.');
writeln ;
{ Keep playing until the user rolls a 1 or chooses not to roll. }
write('Do you want to roll the die (y/n)? ');
readln(Answer);
KeepPlaying := upcase(Answer) = 'Y';
while KeepPlaying do
begin
Roll := RollTheDie;
if Roll = 1 then
begin
NewPoints := 0;
KeepPlaying := false;
writeln('Oh no! You rolled a 1! No new points after all.')
end
else
begin
NewPoints := NewPoints + Roll;
write('You rolled a ', Roll:1, '. ');
writeln('That makes ', NewPoints, ' new points so far.');
writeln ;
write('Roll again (y/n)? ');
readln(Answer);
KeepPlaying := upcase(Answer) = 'Y'
end
end;
{ Update the player's score and check for a winner. }
writeln ;
if NewPoints = 0 then
writeln(P.Name, ' still has ', P.Points, ' points.')
else
begin
P.Points := P.Points + NewPoints;
writeln(P.Name, ' now has ', P.Points, ' points total.');
P.Victory := P.Points >= WinningScore
end
end;
 
procedure Congratulate(Winner: Player);
begin
writeln ;
write('Congratulations, ', Winner.Name, '! ');
writeln('You won with ', Winner.Points, ' points.');
writeln
end;
 
begin
{ Greet the players and initialize their data. }
writeln('Let''s play Pig!');
writeln ;
write('Player 1, what is your name? ');
readln(Player1.Name);
Player1.Points := 0;
Player1.Victory := false;
writeln ;
write('Player 2, what is your name? ');
readln(Player2.Name);
Player2.Points := 0;
Player2.Victory := false;
{ Take turns until there is a winner. }
randomize;
repeat
TakeTurn(Player1);
if not Player1.Victory then TakeTurn(Player2)
until Player1.Victory or Player2.Victory;
{ Announce the winner. }
if Player1.Victory then
Congratulate(Player1)
else
Congratulate(Player2)
end.</syntaxhighlight>
 
=={{header|Perl}}==
You can have as many players as you want, simply provide their names on the command line.
<langsyntaxhighlight lang="perl">#!perl
use strict;
use warnings;
Line 1,679 ⟶ 3,880:
}
__END__
</syntaxhighlight>
</lang>
 
=={{header|Perl 6}}==
=={{header|Phix}}==
{{works with|niecza|2012-09-12}}
Initially a translation of [[Pig_the_dice_game#Lua|Lua]], but now quite different.
<lang perl6>constant DIE = 1..6;
<syntaxhighlight lang="phix">constant numPlayers = 2,
sub MAIN (Int :$players = 2, Int :$goal maxScore = 100) {
sequence scores = repeat(0,numPlayers)
my @safe = 0 xx $players;
printf(1,"\nPig The Dice Game\n\n")
for ^$players xx * -> $player {
integer points = 0, -- points accumulated in current turn, 0=swap turn
say "\nOK, player #$player is up now.";
player = 1 -- start with first player
my $safe = @safe[$player];
while true do
my $ante = 0;
integer roll = rand(6)
until $safe + $ante >= $goal or
printf(1,"Player %d, your score is %d, you rolled %d. ",{player,scores[player],roll})
prompt("#$player, you have $safe + $ante = {$safe+$ante}. Roll? [Yn] ") ~~ /:i ^n/
if roll=1 then
{
printf(1," Too bad. :(\n")
given DIE.roll {
points = 0 -- swap turn
say " You rolled a $_.";
else
when 1 {
points += roll
say " Bust! You lose $ante but keep your previous $safe.";
if scores[player]+points>=maxScore then exit end if
$ante = 0;
printf(1,"Round score %d. Roll or Hold?",{points})
last;
integer reply = upper(wait_key())
}
printf(1,"%c\n",{reply})
when 2..* {
if reply == 'H' then
$ante += $_;
scores[player] += points
}
points = 0 -- swap turn
}
end if
}
end if
$safe += $ante;
if points=0 then
if $safe >= $goal {
player = mod(player,numPlayers) + 1
say "\nPlayer #$player wins with a score of $safe!";
last;end if
end while
}
printf(1,"\nPlayer %d wins with a score of %d!\n",{player,scores[player]+points})</syntaxhighlight>
@safe[$player] = $safe;
say " Sticking with $safe." if $ante;
}
}</lang>
The game defaults to the specified task, but we'll play a shorter game with three players for our example:
{{out}}
<pre>> pig help
Pig The Dice Game
Usage:
pig [--players=<Int>] [--goal=<Int>]
> pig --players=3 --goal=20
 
Player 1, your score is 0, you rolled 2. Round score 2. Roll or Hold?R
OK, player #0 is up now.
#0Player 1, youyour havescore is 0, +you 0rolled =5. 0Round score 7. Roll? [Yn]or Hold?R
Player 1, your score is 0, you rolled 3. Round score 10. Roll or Hold?R
You rolled a 6.
#0Player 1, youyour havescore is 0, +you 6rolled =4. 6Round score 14. Roll? [Yn]or Hold?H
Player 2, your score is 0, you rolled 5. Round score 5. Roll or Hold?R
You rolled a 6.
Player 2, your score is 0, you rolled 1. Too bad. :(
#0, you have 0 + 12 = 12. Roll? [Yn] n
Player 1, your score is 14, you rolled 3. Round score 3. Roll or Hold?H
Sticking with 12.
...
 
Player 2, your score is 86, you rolled 3. Round score 9. Roll or Hold?R
OK, player #1 is up now.
Player 2, your score is 86, you rolled 6.
#1, you have 0 + 0 = 0. Roll? [Yn]
Player 2 wins with a score of 101!
You rolled a 4.
</pre>
#1, you have 0 + 4 = 4. Roll? [Yn]
You rolled a 6.
#1, you have 0 + 10 = 10. Roll? [Yn]
You rolled a 6.
#1, you have 0 + 16 = 16. Roll? [Yn] n
Sticking with 16.
 
OK, player #2 is up now.
#2, you have 0 + 0 = 0. Roll? [Yn]
You rolled a 5.
#2, you have 0 + 5 = 5. Roll? [Yn]
You rolled a 1.
Bust! You lose 5 but keep your previous 0.
 
OK, player #0 is up now.
#0, you have 12 + 0 = 12. Roll? [Yn]
You rolled a 1.
Bust! You lose 0 but keep your previous 12.
 
OK, player #1 is up now.
#1, you have 16 + 0 = 16. Roll? [Yn] n
 
OK, player #2 is up now.
#2, you have 0 + 0 = 0. Roll? [Yn]
You rolled a 6.
#2, you have 0 + 6 = 6. Roll? [Yn]
You rolled a 6.
#2, you have 0 + 12 = 12. Roll? [Yn]
You rolled a 4.
#2, you have 0 + 16 = 16. Roll? [Yn]
You rolled a 6.
 
Player #2 wins with a score of 22!</pre>
 
=={{header|PHP}}==
{{trans|D}}
<langsyntaxhighlight lang="php">error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));
 
define('MAXSCORE', 100);
Line 1,800 ⟶ 3,963:
printf('\n\nPlayer %d wins with a score of %d ',
$player, $safeScore[$player]);
</syntaxhighlight>
</lang>
<pre>C:\UniServer\usr\local\php\php pig.php
Player 0: (0, 0) Rolling? (Yn)
Line 1,839 ⟶ 4,002:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">#!/usr/bin/python3
 
'''
Line 1,875 ⟶ 4,038:
score, player = 0, (player + 1) % playercount
print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))</langsyntaxhighlight>
 
;Samples from a game:
Line 1,914 ⟶ 4,077:
 
Player 0 wins with a score of 101</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ stack ] is turnscore ( --> )
[ stack 1 ] is playernum ( --> )
 
[ 3 playernum share -
playernum replace ] is nextplayer ( --> )
 
[ say "Player "
playernum share echo
[ $ " (R)oll or (H)old? " input
space join
0 peek upper dup
char R = iff
[ drop true ] done
char H = iff false done
say " " again ] ] is choose ( --> b )
 
[ 1 playernum replace
0 0
[ 0 turnscore put
[ choose while
say "Dice roll is: "
6 random 1+
dup echo cr cr
dup 1 = iff
[ say "Your turn ends. "
cr drop
0 turnscore replace ]
done
turnscore tally
again ]
turnscore take +
say "Your score is: "
dup echo cr
dup 100 < while
swap nextplayer
cr
again ]
say "You win." cr
2drop ] is play ( --> )</syntaxhighlight>
 
{{out}}
 
As a dialogue in the Quackery shell. For brevity the winning score has been reduced from 100 to 10.
 
<pre>/O> play
...
Player 1 (R)oll or (H)old? bad input
(R)oll or (H)old? r
Dice roll is: 6
 
Player 1 (R)oll or (H)old? hold
Your score is: 6
 
Player 2 (R)oll or (H)old? Roll
Dice roll is: 1
 
Your turn ends.
Your score is: 0
 
Player 1 (R)oll or (H)old? R
Dice roll is: 4
 
Player 1 (R)oll or (H)old? H
Your score is: 10
You win.
 
Stack empty.
 
/O></pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,945 ⟶ 4,180:
 
(pig-the-dice #:print? #t human human)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-30}}
<syntaxhighlight lang="raku" line>constant DIE = 1..6;
sub MAIN (Int :$players = 2, Int :$goal = 100) {
my @safe = 0 xx $players;
for |^$players xx * -> $player {
say "\nOK, player #$player is up now.";
my $safe = @safe[$player];
my $ante = 0;
until $safe + $ante >= $goal or
prompt("#$player, you have $safe + $ante = {$safe+$ante}. Roll? [Yn] ") ~~ /:i ^n/
{
given DIE.roll {
say " You rolled a $_.";
when 1 {
say " Bust! You lose $ante but keep your previous $safe.";
$ante = 0;
last;
}
when 2..* {
$ante += $_;
}
}
}
$safe += $ante;
if $safe >= $goal {
say "\nPlayer #$player wins with a score of $safe!";
last;
}
@safe[$player] = $safe;
say " Sticking with $safe." if $ante;
}
}</syntaxhighlight>
The game defaults to the specified task, but we'll play a shorter game with three players for our example:
{{out}}
<pre>> pig help
Usage:
pig [--players=<Int>] [--goal=<Int>]
> pig --players=3 --goal=20
 
OK, player #0 is up now.
#0, you have 0 + 0 = 0. Roll? [Yn]
You rolled a 6.
#0, you have 0 + 6 = 6. Roll? [Yn]
You rolled a 6.
#0, you have 0 + 12 = 12. Roll? [Yn] n
Sticking with 12.
 
OK, player #1 is up now.
#1, you have 0 + 0 = 0. Roll? [Yn]
You rolled a 4.
#1, you have 0 + 4 = 4. Roll? [Yn]
You rolled a 6.
#1, you have 0 + 10 = 10. Roll? [Yn]
You rolled a 6.
#1, you have 0 + 16 = 16. Roll? [Yn] n
Sticking with 16.
 
OK, player #2 is up now.
#2, you have 0 + 0 = 0. Roll? [Yn]
You rolled a 5.
#2, you have 0 + 5 = 5. Roll? [Yn]
You rolled a 1.
Bust! You lose 5 but keep your previous 0.
 
OK, player #0 is up now.
#0, you have 12 + 0 = 12. Roll? [Yn]
You rolled a 1.
Bust! You lose 0 but keep your previous 12.
 
OK, player #1 is up now.
#1, you have 16 + 0 = 16. Roll? [Yn] n
 
OK, player #2 is up now.
#2, you have 0 + 0 = 0. Roll? [Yn]
You rolled a 6.
#2, you have 0 + 6 = 6. Roll? [Yn]
You rolled a 6.
#2, you have 0 + 12 = 12. Roll? [Yn]
You rolled a 4.
#2, you have 0 + 16 = 16. Roll? [Yn]
You rolled a 6.
 
Player #2 wins with a score of 22!</pre>
 
=={{header|REXX}}==
This REXX program has the following features:
:::* any number of human players can play
:::* any number of computer players can play
:::* human and computers can play together (humans always go first)
:::* names of the human players can be specified
:::* names of the computer players can be specified
:::* the score needed to win may be specified
:::* verbosity was chosen as it's assumed that a human is playing
:::* code was written to allow for an &nbsp; '''N''' &nbsp; sided die
:::* names are used for the die faces (asin welladdition asto the pip value)
:::* a simple strategy (but aggressive) wasstrategy is used (that favors a human player)
<langsyntaxhighlight lang="rexx">/*REXX program plays "pig (the dice game)" with at(any leastnumber oneof humanCBLFs playerand/or silicons or HALs).*/
sw= linesize() - 1 /*get the width of the terminal screen,*/
signal on syntax; signal on novalue /*handle REXX program errors. */
sw=80-1 parse arg hp cp win die _ . '(' names ")" /*theobtain LINESIZEoptional bifarguments wouldfrom bethe nicerCL*/
/*names with blanks should use an _ */
parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments.*/
if _\=='' then call err 'too many arguments were specified: ' _
@nhp = 'number of human players' ; hp hp = scrutinize( hp, @nhp , 0, 0, 0)
@ncp = 'number of computer players' ; cp cp = scrutinize( cp, @ncp , 0, 0, 2)
@sn2w = 'score needed to win' ; win win= scrutinize(win, @sn2w , 1,100 1e6, 60)
@nsid = 'number of sides in die' ; die die= scrutinize(die, @nsid , 2, 999, 6)
if hp==0 & cp==0 then cp= 2 /*if both counts are zero, 2two HALs. */
if hp==1 & cp==0 then cp= 1 /*if one human, then use 1one HAL. */
Lname.=0 /*maximumnullify lengthall ofnames (to a playerblank). name*/
L= 0 do i=1 for hp+cp /*getmaximum thelength player'sof names,a maybeplayer name. */
ifdo i>=1 for hp+cp then @='HAL_'i"_the_computer" /*useget thisthe player's names, for default... maybe. */
if i>hp elsethen @= 'player_HAL_'i "_the_computer" /*use "this for default name. " " " */
else @= 'player_'i /* " " " " " */
name.i = translate( word( strip( word(names,i)) @, 1),,'_')
L=max(L, length(name.i)) = translate( word( strip( word( names, i) /*use) L@, for1), nice, name formatting.*/'_')
endL= max(L, length( /*name.i*/) ) /*use L /*underscores arefor nice name formatting. changed─�blanks*/
end /*i*/ /*underscores are changed ──► blanks. */
 
hpn=hp; if hpn==0 then hpn= 'no' /*use normal English for the display. */
cpn=cp; if cpn==0 then cpn=" 'no"' /* " " " " " " */
say 'Pig (the dice game) is being played with'
if cpn\==0 then say right(cpn,9) 'computer player's(cp)
if hpn\==0 then say right(hpn,9) 'human player's(hp)
say 'and the' @sn2w "is: " win ' (or greater).'
!.=; dieNames='ace duece trey square nickle boxcar' /*die face names.*/
/*note: snake eyes is for 2 aces.*/
do i=1 for 6; !.i=' ['word(dieNames,i)"] "; end /*i*/
s.=0 /*set all player's scores to zero*/
@=copies('─',9) /*an eyecatcher (for prompting). */
@jra='just rolled a '; @ati=', and the inning' /*nice literals to have.*/
/*──────────────────────────────────────────────────let's play some pig.*/
do game=1; in.=0 /*set each inning's score to zero*/
say; say copies('█',sw) /*display a fence for da eyeballs*/
 
say 'Pig (the dice game) is being played with:' /*the introduction to pig-the-dice-game*/
do k=1 for hp+cp /*display the scores (as a recap)*/
say 'The score for' left(name.k,L) "is " right(s.k,length(win))'.'
end /*k*/
 
say copies('█',sw) if cpn\==0 then say right(cpn, 9) /*display a'computer fence for da eyeballs*/player's(cp)
if hpn\==0 then say right(hpn, 9) 'human player's(hp)
!.=
say 'and the' @sn2w "is: " win ' (or greater).'
dieNames= 'ace deuce trey square nickle boxcar' /*some slangy vernacular die─face names*/
!w= 0 /*note: snake eyes is for two aces. */
do i=1 for die /*assign the vernacular die─face names.*/
!.i= ' ['word(dieNames,i)"]" /*pick a word from die─face name lists.*/
!w= max(!w, length(!.i) ) /*!w ──► maximum length die─face name. */
end /*i*/
s.= 0 /*set all player's scores to zero. */
!w= !w + length(die) + 3 /*pad the die number and die names. */
@= copies('─', 9) /*eyecatcher (for the prompting text). */
@jra= 'just rolled a ' /*a nice literal to have laying 'round.*/
@ati= 'and the inning' /*" " " " " " " */
/*═══════════════════════════════════════════════════let's play some pig.*/
do game=1; in.= 0; call score /*set each inning's score to 0; display*/
 
do j=1 for hp+cp; say /*let each player roll their dice. */
say; say copies('─', sw); /*display a fence for da ole eyeballs. */
it= name.j
it=word('You It', 1 + (j>hp)) /*pronoun choice: You or It */
say name.jit', your total score (so far) in this pig game is: ' s.j"."
 
do until stopped /*keep prompting/rolling 'til notstopped. */
r= random(1, die); !=space(r !.r) /*for color, use /*get a random die- face name(number). */
!= left(space(r !.r','), !w) /*for color, use a die─face name. */
in.j=in.j+r
ifin.j= in.j + r==1 then do; say it @jra ! || @ati "is a bust /*add die─face number to the inning."; leave; end*/
 
say it @jra ! || @ati "total is:" in.j
stoppedif r==what2do(j)1 then do; say it @jra ! /*determine|ask| to@ati stop rolling"is a bust.*/"; leave; end
if j>hp & stopped then say 'it and' name.j@jra ! || @ati "electedtotal tois: stop" rolling in."j
 
stopped= what2do(j) /*determine or ask to stop rolling. */
if j>hp & stopped then say ' and' name.j "elected to stop rolling."
end /*until stopped*/
 
if r\==1 then s.j= s.j + in.j /*if not a bust, then add to the inning.*/
if s.j>=win then leave game /*we have a winner, so the game ends. */
end /*j*/ /*that's the end of the players. */
end /*game*/
 
call score; say; say; say; say; say center(''name.j "won! ", sw, '═'); say; say; exit
exit say; say; exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────S subroutine────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural?pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────SCRUTINIZE subroutine───────────────*/
score: say; say copies('█', sw) /*display a fence for da ole eyeballs. */
scrutinize: parse arg ?,what,minimum /*? is the number, or maybe not. */
if ?=='' | ?==',' then return arg(4)
if \datatype(?,'N') then call err what "isn't numeric: " ?; ?=?/1
if \datatype(?,'W') then call err what "isn't an integer: " ?
if ?==0 & minimum>0 then call err what "can't be zero."
if ?<minimum then call err what "can't be less than" minimum': ' ?
return ?
/*──────────────────────────────────what2do subroutine──────────────────*/
what2do: parse arg who /*"who" is a human or a computer.*/
if (j>hp & r+in.j>=win) then return 1 /*an easy choice for HAL.*/
if (j>hp & in.j>=win%4) then return 1 /*a simple stategy for HAL.*/
if j>hp then return 0 /*HAL says, keep truckin'! */
say @ name.who', what do you want to do? (a QUIT will stop the game),'
say @ 'press ENTER to roll again, or anything else to STOP rolling.'
pull action; action=space(action) /*remove any superfluous blanks. */
if \abbrev('QUIT',action,1) then return action\==''
say; say; say; say center(' quitting. ',sw,'─'); say; say; say; exit
/*───────────────────────────────error handling subroutines and others.─*/
err: say; say; say center(' error! ',max(40,linesize()%2),"*"); say
do j=1 for arg(); say arg(j); say; end; say; exit 13
 
do k=1 for hp+cp /*display the scores (as a recap). */
novalue: syntax: call err 'REXX program' condition('C') "error",,
say 'The score for ' left(name.k, L) " is " right(s.k, length(win) ).
condition('D'),'REXX source statement (line' sigl"):",,
end sourceline(sigl)/*k*/
 
</lang>
say copies('█', sw); return /*display a fence for da ole eyeballs. */
'''output''' when using the input of: <tt> 0 2 44 ( HAL R2D2</tt>
/*──────────────────────────────────────────────────────────────────────────────────────*/
<br>[This plays a simulated game with '''no''' humans, '''two''' computers, and the score to win is '''44'''.]
scrutinize: parse arg ?,what,min,max /*? is the number, ... or maybe not. */
<pre style="height:50ex;overflow:scroll">
if ?=='' | ?==',' then return arg(5)
Pig (the dice game) is being played with
if \datatype(?, 'N') then call err what "isn't numeric: " ?; ?= ?/1
if \datatype(?, 'W') then call err what "isn't an integer: " ?
if ?==0 & min>0 then call err what "can't be zero."
if ?<min then call err what "can't be less than" min': ' ?
if ?==0 & max>0 then call err what "can't be zero."
if ?>max & max\==0 then call err what "can't be greater than" max': ' ?
return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
what2do: parse arg who /*"who" is a human or a computer.*/
if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL. */
if j>hp & in.j>=win%4 then return 1 /*a simple strategy for HAL. */
if j>hp then return 0 /*HAL says, keep truckin'! */
say @ name.who', what do you want to do? (a QUIT will stop the game),'
say @ 'press ENTER to roll again, or anything else to STOP rolling.'
pull action; action= space(action) /*remove any superfluous blanks. */
if \abbrev('QUIT', action, 1) then return action\==''
say; say; say center(' quitting. ', sw, '─'); say; say; exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say; say center(' error! ', max(40, linesize() % 2), "*"); say
do j=1 for arg(); say arg(j); say; end; say; exit 13</syntaxhighlight>
This REXX program makes use of &nbsp; '''LINESIZE''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
<br>The &nbsp; '''LINESIZE.REX''' &nbsp; REXX program is included here &nbsp; ──► &nbsp; [[LINESIZE.REX]].
 
 
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 0 &nbsp; 2 &nbsp; 44 &nbsp; ( &nbsp; HAL &nbsp; R2D2 </tt>}}
 
[This plays a simulated game with '''no''' humans, '''two''' computers, and the score to win is '''44''', player names are specified.]
<pre style="height:104ex">
Pig (the dice game) is being played with:
2 computer players
no human players
and the score needed to win is: 44 (or greater).
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
The score for HAL is 0.
The score for R2D2 RdD2 is 0.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
HAL, your total score (so far) in this pig game is: 0.
ItHAL just rolled a 54 [nicklesquare], and the inning total is: 5 4
ItHAL just rolled a 25 [duecenickle], and the inning total is: 7 9
ItHAL just rolled a 23 [duecetrey], and the inning total is: 9 12
It just rolled a 6 [boxcar], and the inning total is: 15
and HAL elected to stop rolling.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
R2D2RdD2, your total score (so far) in this pig game is: 0.
ItRdD2 just rolled a 64 [boxcarsquare], and the inning total is: 6 4
ItRdD2 just rolled a 64 [boxcarsquare], and the inning total is: 12 8
RdD2 just rolled a 4 [square], and the inning total is: 12
and R2D2 elected to stop rolling.
and RdD2 elected to stop rolling.
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
The score for HAL is 1512.
The score for R2D2 RdD2 is 12.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
HAL, your total score (so far) in this pig game is: 15 12.
ItHAL just rolled a 12 [acedeuce], and the inning total is: a bust.2
HAL just rolled a 1 [ace], and the inning is a bust.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
R2D2RdD2, your total score (so far) in this pig game is: 12.
ItRdD2 just rolled a 62 [boxcardeuce], and the inning total is: 6 2
ItRdD2 just rolled a 51 [nickleace], and the inning total is: 11a bust.
and R2D2 elected to stop rolling.
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
The score for HAL is 1512.
The score for R2D2 RdD2 is 2312.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
HAL, your total score (so far) in this pig game is: 15 12.
ItHAL just rolled a 26 [dueceboxcar], and the inning total is: 2 6
ItHAL just rolled a 5 [nickle], and the inning total is: 7 11
It just rolled a 5 [nickle], and the inning total is: 12
and HAL elected to stop rolling.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
R2D2RdD2, your total score (so far) in this pig game is: 23 12.
ItRdD2 just rolled a 52 [nickledeuce], and the inning total is: 5 2
ItRdD2 just rolled a 36 [treyboxcar], and the inning total is: 8
ItRdD2 just rolled a 53 [nickletrey], and the inning total is: 13 11
and R2D2RdD2 elected to stop rolling.
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
The score for HAL is 2723.
The score for R2D2 RdD2 is 3623.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
HAL, your total score (so far) in this pig game is: 27 23.
ItHAL just rolled a 51 [nickleace], and the inning total is: 5a bust.
It just rolled a 4 [square], and the inning total is: 9
It just rolled a 3 [trey], and the inning total is: 12
and HAL elected to stop rolling.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
R2D2RdD2, your total score (so far) in this pig game is: 36 23.
ItRdD2 just rolled a 36 [treyboxcar], and the inning total is: 3 6
ItRdD2 just rolled a 5 [nickle], and the inning total is: 8 11
and RdD2 elected to stop rolling.
It just rolled a 1 [ace], and the inning is a bust.
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
The score for HAL is 3923.
The score for R2D2 RdD2 is 3634.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
HAL, your total score (so far) in this pig game is: 39 23.
ItHAL just rolled a 26 [dueceboxcar], and the inning total is: 2 6
ItHAL just rolled a 21 [dueceace], and the inning total is: 4a bust.
It just rolled a 1 [ace], and the inning is a bust.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
R2D2RdD2, your total score (so far) in this pig game is: 36 34.
ItRdD2 just rolled a 61 [boxcarace], and the inning total is: 6a bust.
It just rolled a 4 [square], and the inning total is: 10
It just rolled a 1 [ace], and the inning is a bust.
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
The score for HAL is 3923.
The score for R2D2 RdD2 is 3634.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
███████████████████████████████████████████████████████████████████████████████
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
HAL, your total score (so far) in this pig game is: 39 23.
ItHAL just rolled a 46 [squareboxcar], and the inning total is: 4 6
ItHAL just rolled a 16 [aceboxcar], and the inning total is: a bust.12
and HAL elected to stop rolling.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────────────────────
R2D2RdD2, your total score (so far) in this pig game is: 36 34.
ItRdD2 just rolled a 26 [dueceboxcar], and the inning total is: 2 6
ItRdD2 just rolled a 2 [duecedeuce], and the inning total is: 4 8
ItRdD2 just rolled a 62 [boxcardeuce], and the inning total is: 10
and RdD2 elected to stop rolling.
It just rolled a 3 [trey], and the inning total is: 13
and R2D2 elected to stop rolling.
 
███████████████████████████████████████████████████████████████████████████████████████████████████████████
The score for HAL is 35.
The score for RdD2 is 44.
███████████████████████████████████████████████████████████████████████████████████████████████████████████
 
 
 
════════════════════════════════════════════════RdD2 won! ═════════════════════════════════════════════════
══════════════════════════════════R2D2 won! ═══════════════════════════════════
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Pig the dice game
 
numPlayers = 2
maxScore = 100
safescore = list(numPlayers)
while true
rolling = ""
for player = 1 to numPlayers
score = 0
while safeScore[player] < maxScore
see "Player " + player + " Rolling? (Y) "
give rolling
if upper(rolling) = "Y"
rolled = random(5) + 1
see "Player " + player + " rolled " + rolled + nl
if rolled = 1
see "Bust! you lose player " + player + " but still keep your previous score of " + safeScore[player] + nl
exit
ok
score = score + rolled
else
safeScore[player] = safeScore[player] + score
ok
end
next
end
see "Player " + player + " wins with a score of " + safeScore[player]
</syntaxhighlight>
Output:
<pre>
Player 1 Rolling? (Y) y
Player 1 rolled 6
Player 1 Rolling? (Y) y
Player 1 rolled 5
Player 1 Rolling? (Y) y
Player 1 rolled 6
Player 1 Rolling? (Y) y
Player 1 rolled 4
Player 1 Rolling? (Y) y
Player 1 rolled 3
Player 1 Rolling? (Y) y
Player 1 rolled 3
Player 1 Rolling? (Y) y
Player 1 rolled 3
Player 1 Rolling? (Y) y
Player 1 rolled 3
Player 1 Rolling? (Y) y
Player 1 rolled 3
Player 1 Rolling? (Y) y
Player 1 rolled 2
Player 1 Rolling? (Y) y
Player 1 rolled 6
Player 1 Rolling? (Y) y
Player 1 rolled 2
Player 1 Rolling? (Y) y
Player 1 rolled 4
Player 1 Rolling? (Y) y
Player 1 rolled 5
Player 1 Rolling? (Y) y
Player 1 rolled 4
Player 1 Rolling? (Y) y
Player 1 rolled 1
Bust! you lose player 1 but still keep your previous score of 0
Player 2 Rolling? (Y)
</pre>
 
Line 2,175 ⟶ 4,578:
* transparent game logic
 
<langsyntaxhighlight lang="ruby">class PigGame
Player = Struct.new(:name, :safescore, :score) do
def bust!() self.score = safescore end
def stay!() self.safescore = score end
def roll!to_s(die_sides) rand"#{name} (1..die_sides#{safescore}, #{score})" end
def wants_to_roll?
print("#{name} (#{safescore}, #{score})", ": Roll? (Y) ")
['Y','y',''].include?(gets.chomp)
end
end
 
def initialize(names, maxscore=100, die_sides=6)
def bust?(roll) roll==1 ? (puts("Busted!",'') || true) : false end
rotation = names.map {|name| Player.new(name,0,0) }
 
def play(names, maxscore=100, die_sides=6)
rotation.cycle =do names.map {|nameplayer| Player.new(name,0,0) }.cycle
 
while player = rotation.next
loop do
if player.wants_to_roll?(player)
puts "Rolled: #{roll=player.roll!roll_dice(die_sides)}"
if bust?( roll )
player.bustputs "Busted! && break",''
player.bust!
break
else
player.score += roll
return player if player.score >= maxscore
puts player.name + " wins!"
return
end
end
else
player.stay! && puts("Staying with #{player.safescore}!", '')
puts "Staying with #{player.safescore}!", ''
break
end
end
end
end
def roll_dice(die_sides) rand(1..die_sides) end
def bust?(roll) roll==1 end
def wants_to_roll?(player)
print "#{player}: Roll? (Y) "
['Y','y',''].include?(gets.chomp)
end
end
 
print PigGame.new.play( %w|Samuel Elizabeth| ).name, " wins!"</langsyntaxhighlight>
 
;Samples from a game:
Line 2,248 ⟶ 4,658:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">numPlayers = 2
maxScore = 100
dim safeScore(numPlayers)
Line 2,273 ⟶ 4,683:
goto [loop]
[winner]
print "Player ";plater;" wins with a score of ";safeScore(player)</langsyntaxhighlight>
 
=={{header|Rust}}==
{{works with|Rust|2018}}
<syntaxhighlight lang="rust">use rand::prelude::*;
 
fn main() {
println!("Beginning game of Pig...");
 
let mut players = vec![
Player::new(String::from("PLAYER (1) ONE")),
Player::new(String::from("PLAYER (2) TWO")),
];
 
'game: loop {
for player in players.iter_mut() {
if player.cont() {
println!("\n# {} has {:?} Score", player.name, player.score);
player.resolve();
} else {
println!("\n{} wins!", player.name);
break 'game;
}
}
}
 
println!("Thanks for playing!");
}
 
type DiceRoll = u32;
type Score = u32;
type Name = String;
 
enum Action {
Roll,
Hold,
}
 
#[derive(PartialEq)]
enum TurnStatus {
Continue,
End,
}
 
struct Player {
name: Name,
score: Score,
status: TurnStatus,
}
 
impl Player {
fn new(name: Name) -> Player {
Player {
name,
score: 0,
status: TurnStatus::Continue,
}
}
 
fn roll() -> DiceRoll {
// Simple 1d6 dice.
let sides = rand::distributions::Uniform::new(1, 6);
rand::thread_rng().sample(sides)
}
 
fn action() -> Action {
// Closure to determine userinput as action.
let command = || -> Option<char> {
let mut cmd: String = String::new();
match std::io::stdin().read_line(&mut cmd) {
Ok(c) => c.to_string(),
Err(err) => panic!("Error: {}", err),
};
 
cmd.to_lowercase().trim().chars().next()
};
 
'user_in: loop {
match command() {
Some('r') => break 'user_in Action::Roll,
Some('h') => break 'user_in Action::Hold,
Some(invalid) => println!("{} is not a valid command!", invalid),
None => println!("Please input a command!"),
}
}
}
 
fn turn(&mut self) -> Score {
let one = |die: DiceRoll| {
println!("[DICE] Dice result is: {:3}!", die);
println!("[DUMP] Dumping Score! Sorry!");
println!("###### ENDING TURN ######");
};
 
let two_to_six = |die: DiceRoll, score: Score, player_score: Score| {
println!("[DICE] Dice result is: {:3}!", die);
println!("[ROLL] Total Score: {:3}!", (score + die));
println!("[HOLD] Possible Score: {:3}!", (score + die + player_score));
};
 
let mut score: Score = 0;
'player: loop {
println!("# {}'s Turn", self.name);
println!("###### [R]oll ######\n###### --OR-- ######\n###### [H]old ######");
 
match Player::action() {
Action::Roll => match Player::roll() {
0 | 7..=u32::MAX => panic!("outside dice bounds!"),
die @ 1 => {
one(die);
self.status = TurnStatus::End;
break 'player 0;
}
die @ 2..=6 => {
two_to_six(die, score, self.score);
self.status = TurnStatus::Continue;
score += die
}
},
Action::Hold => {
self.status = TurnStatus::End;
break 'player score;
}
}
}
}
 
fn resolve(&mut self) {
self.score += self.turn()
}
 
fn cont(&self) -> bool {
self.score <= 100 || self.status == TurnStatus::Continue
}
}</syntaxhighlight>
 
=={{header|Scala}}==
===Functional Style, Tail recursive===
{{libheader|Scala CLI Game}}
{{works with|Scala|2.13}}
{{libheader|Scala Functional Style}}
{{libheader|Scala Tail recursion}}
{{libheader|Scala 100% Immutable variables}}
{{libheader|Scala Concise}}
<syntaxhighlight lang="scala">object PigDice extends App {
private val (maxScore, nPlayers) = (100, 2)
private val rnd = util.Random
 
private case class Game(gameOver: Boolean, idPlayer: Int, score: Int, stickedScores: Vector[Int])
 
@scala.annotation.tailrec
private def loop(play: Game): Unit =
play match {
case Game(true, _, _, _) =>
case Game(false, gPlayer, gScore, gStickedVals) =>
val safe = gStickedVals(gPlayer)
val stickScore = safe + gScore
val gameOver = stickScore >= maxScore
 
def nextPlayer = (gPlayer + 1) % nPlayers
 
def gamble: Game = play match {
case Game(_: Boolean, lPlayer: Int, lScore: Int, lStickedVals: Vector[Int]) =>
val rolled: Int = rnd.nextInt(6) + 1
 
println(s" Rolled $rolled")
if (rolled == 1) {
println(s" Bust! You lose $lScore but keep ${lStickedVals(lPlayer)}\n")
play.copy(idPlayer = nextPlayer, score = 0)
} else play.copy(score = lScore + rolled)
}
 
def stand: Game = play match {
case Game(_, lPlayer, _, lStickedVals) =>
 
println(
(if (gameOver) s"\n\nPlayer $lPlayer wins with a score of" else " Sticking with")
+ s" $stickScore.\n")
 
Game(gameOver, nextPlayer, 0, lStickedVals.updated(lPlayer, stickScore))
}
 
if (!gameOver && Seq("y", "").contains(
io.StdIn.readLine(f" Player $gPlayer%d: ($safe%d, $gScore%d) Rolling? ([y]/n): ").toLowerCase)
) loop(gamble )else loop(stand)
}
 
loop(Game(gameOver = false, 0, 0, Array.ofDim[Int](nPlayers).toVector))
}</syntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program pig;
setrandom(0);
scores := {[1,0], [2,0]};
 
t := 1;
loop until exists n = scores(p) | n >= 100 do
print("Current score: player 1 = " + str scores(1) +
", player 2 = " + str scores(2));
scores(t) +:= turn(t);
t := 3-t;
end loop;
 
print("Player " + str p + " wins!");
print("Final score: player 1 = " + str scores(1) +
", player 2 = " + str scores(2));
 
proc turn(p);
score := 0;
loop do
putchar("Player " + str p + " - " + str score + " - R)oll or H)old? ");
loop doing
flush(stdout);
choice := to_upper getline(stdin);
while choice notin {"R","H"} do
putchar("Invalid input. R)oll or H)old? ");
end loop;
 
if choice = "H" then
print("Player " + str p + "'s turn ends with " + str score + " points.");
return score;
end if;
 
if (die := roll()) = 6 then
print("You rolled a 6. You lose your points and your turn ends.");
return 0;
end if;
 
print("You rolled a " + str die + ".");
score +:= die;
end loop;
end proc;
 
proc roll();
return 1 + random(5);
end proc;
end program;</syntaxhighlight>
 
=={{header|Tcl}}==
<table><tr><td>{{works with|Tcl|8.6}}</td><td>or alternatively with Tcl 8.5 and</td><td>{{libheader|TclOO}}</td></tr></table><!-- dirty trick! -->
<langsyntaxhighlight lang="tcl">package require TclOO
 
oo::class create Player {
Line 2,355 ⟶ 5,001:
rotateList scores
}
}</langsyntaxhighlight>
Demonstrating with human players:
<langsyntaxhighlight lang="tcl">oo::class create HumanPlayer {
variable me
superclass Player
Line 2,388 ⟶ 5,034:
}
 
pig [HumanPlayer new "Alex"] [HumanPlayer new "Bert"]</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 2,409 ⟶ 5,055:
Bert (on 87+8) do you want to roll? (Y/n)
Bert has won! (Score: 101)
Bert is a winner, on 101</pre>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="qbasic">n = 2
m = 100
Dim @s(n)
 
p = 0
s = 0
 
Do
r = Ask(Join ("Player ", Str(p+1)," rolling? (Y/N) "))
 
If OR(Peek(r, 0), 32) = Ord("y") Then
r = Rnd(6) + 1
Print "Player ";p+1;" rolled ";r
 
If r = 1 Then
Print "Bust! you lose player ";p+1;" but still keep your previous score of ";@s(p)
Print : p = (p + 1) % n : s = 0
Else
s = s + r
EndIf
 
Else
@s(p) = @s(p) + s
 
If (@s(p) < m) = 0 Then
Print "Player ";p+1;" wins with a score of ";@s(p)
Break
EndIf
 
Print : p = (p + 1) % n : s = 0
EndIf
Loop</syntaxhighlight>
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
Option Explicit
 
Sub Main_Pig()
Dim Scs() As Byte, Ask As Integer, Np As Boolean, Go As Boolean
Dim Cp As Byte, Rd As Byte, NbP As Byte, ScBT As Byte
'You can adapt these Const, but don't touch the "¤¤¤¤"
Const INPTXT As String = "Enter number of players : "
Const INPTITL As String = "Numeric only"
Const ROL As String = "Player ¤¤¤¤ rolls the die."
Const MSG As String = "Do you want to ""hold"" : "
Const TITL As String = "Total if you keep : "
Const RES As String = "The die give you : ¤¤¤¤ points."
Const ONE As String = "The die give you : 1 point. Sorry!" & vbCrLf & "Next player."
Const WIN As String = "Player ¤¤¤¤ win the Pig Dice Game!"
Const STW As Byte = 100
 
Randomize Timer
NbP = Application.InputBox(INPTXT, INPTITL, 2, Type:=1)
ReDim Scs(1 To NbP)
Cp = 1
Do
ScBT = 0
Do
MsgBox Replace(ROL, "¤¤¤¤", Cp)
Rd = Int((Rnd * 6) + 1)
If Rd > 1 Then
MsgBox Replace(RES, "¤¤¤¤", Rd)
ScBT = ScBT + Rd
If Scs(Cp) + ScBT >= STW Then
Go = True
Exit Do
End If
Ask = MsgBox(MSG & ScBT, vbYesNo, TITL & Scs(Cp) + ScBT)
If Ask = vbYes Then
Scs(Cp) = Scs(Cp) + ScBT
Np = True
End If
Else
MsgBox ONE
Np = True
End If
Loop Until Np
If Not Go Then
Np = False
Cp = Cp + 1
If Cp > NbP Then Cp = 1
End If
Loop Until Go
MsgBox Replace(WIN, "¤¤¤¤", Cp)
End Sub
</syntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">import rand
import rand.seed
import os
fn main() {
rand.seed(seed.time_seed_array(2)) //Set seed to current time
mut player_scores := [0, 0]
mut turn := 0
mut current_score := 0
for {
player := turn % player_scores.len
answer := os.input("Player $player [${player_scores[player]}, $current_score], (H)old, (R)oll or (Q)uit: ").to_lower()
match answer {
"h"{ //Hold
player_scores[player] += current_score
print(" Player $player now has a score of ${player_scores[player]}.\n")
if player_scores[player] >= 100 {
println(" Player $player wins!!!")
return
}
current_score = 0
turn += 1
}
"r"{ //Roll
roll := rand.int_in_range(1, 7) or {1}
if roll == 1 {
println(" Rolled a 1. Bust!\n")
current_score = 0
turn += 1
} else {
println(" Rolled a ${roll}.")
current_score += roll
}
}
"q"{ //Quit
return
}
else{ //Incorrent input
println(" Please enter one of the given inputs.")
}
}
}
println("Player ${(turn-1)%player_scores.len} wins!!!", )
}</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "./ioutil" for Input
import "./str" for Str
import "random" for Random
 
var name1 = Input.text("Player 1 - Enter your name : ").trim()
name1 = (name1 == "") ? "PLAYER1" : Str.upper(name1)
var name2 = Input.text("Player 2 - Enter your name : ").trim()
name2 = (name2 == "") ? "PLAYER2" : Str.upper(name2)
var names = [name1, name2]
var r = Random.new()
var totals = [0, 0]
var player = 0
while (true) {
System.print("\n%(names[player])")
System.print(" Your total score is currently %(totals[player])")
var score = 0
while (true) {
var rh = Str.lower(Input.option(" Roll or Hold r/h : ", "rhRH"))
if (rh == "h") {
totals[player] = totals[player] + score
System.print(" Your total score is now %(totals[player])")
if (totals[player] >= 100) {
System.print(" So, %(names[player]), YOU'VE WON!")
return
}
player = (player == 0) ? 1 : 0
break
}
var dice = r.int(1, 7)
System.print(" You have thrown a %(dice)")
if (dice == 1) {
System.print(" Sorry, your score for this round is now 0")
System.print(" Your total score remains at %(totals[player])")
player = (player == 0) ? 1 : 0
break
}
score = score + dice
System.print(" Your score for the round is now %(score)")
}
}</syntaxhighlight>
 
{{out}}
Sample (abridged) game:
<pre>
Player 1 - Enter your name : Boris
Player 2 - Enter your name : Keir
 
BORIS
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 3
Roll or Hold r/h : r
You have thrown a 1
Sorry, your score for this round is now 0
Your total score remains at 0
 
KEIR
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 2
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 6
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 10
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 16
Roll or Hold r/h : r
You have thrown a 1
Sorry, your score for this round is now 0
Your total score remains at 0
 
BORIS
Your total score is currently 0
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 4
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 8
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 14
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 16
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 19
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 22
Roll or Hold r/h : h
Your total score is now 22
 
.....
 
BORIS
Your total score is currently 63
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 2
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 5
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 10
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 12
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 15
Roll or Hold r/h : r
You have thrown a 3
Your score for the round is now 18
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 22
Roll or Hold r/h : h
Your total score is now 85
 
KEIR
Your total score is currently 73
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 4
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 9
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 11
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 13
Roll or Hold r/h : r
You have thrown a 6
Your score for the round is now 19
Roll or Hold r/h : r
You have thrown a 4
Your score for the round is now 23
Roll or Hold r/h : r
You have thrown a 2
Your score for the round is now 25
Roll or Hold r/h : r
You have thrown a 5
Your score for the round is now 30
Roll or Hold r/h : h
Your total score is now 103
So, KEIR, YOU'VE WON!
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
integer Player, Die, Points, Score(2);
[Score(0):= 0; Score(1):= 0; \starting scores for each player
Line 2,437 ⟶ 5,385:
until Score(Player) >= 100;
Text(0, "Player "); IntOut(0, Player+1); Text(0, " WINS!!!");
]</langsyntaxhighlight>
 
Output:
Line 2,473 ⟶ 5,421:
Player 1 WINS!!!
</pre>
 
=={{header|Yabasic}}==
{{trans|BASIC256}}
<syntaxhighlight lang="vbnet">numjugadores = 2
maxpuntos = 100
dim almacenpuntos(3)
almacenpuntos(1) = 1
almacenpuntos(2) = 1
 
clear screen
print "The game of PIG"
print "===============", chr$(13), chr$(10)
print "Si jugador saca un 1, no anota nada y se convierte en el turno del oponente."
print "Si jugador saca 2-6, se agrega al total del turno y su turno continúa."
print "Si jugador elige 'mantener', su total de puntos se añade a su puntuación,";
print " y se convierte en el turno del siguiente jugador.", chr$(10)
print "El primer jugador en anotar 100 o más puntos gana.", chr$(13), chr$(10)
 
repeat
for jugador = 1 to 2 //numjugadores
puntos = 0
 
while almacenpuntos(jugador) <= maxpuntos
print "\nJugador ", jugador, ": (", almacenpuntos(jugador), ",", puntos, ")";
input " Tirada? (Sn) " nuevotiro$
if upper$(nuevotiro$) = "S" then
tirada = int(ran(5)) + 1
print " Tirada:", tirada
if tirada = 1 then
print chr$(10), "¡Pierdes tu turno! jugador ", jugador;
print " pero mantienes tu puntuación anterior de ", almacenpuntos(jugador)
break
fi
puntos = puntos + tirada
else
almacenpuntos(jugador) = almacenpuntos(jugador) + puntos
print " Te quedas con: ", almacenpuntos(jugador)
if almacenpuntos(jugador) >= maxpuntos then
print chr$(10), "Gana el Jugador ", jugador, " con ", almacenpuntos(jugador), " puntos."
end
fi
break
fi
wend
next jugador
until false</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|D}}
<syntaxhighlight lang="zkl">const WIN=100, PLAYERS=2;
players,safeScores:=Walker.cycle([0..PLAYERS-1]), PLAYERS.pump(List(),0);
rollDie:=(1).random.fp(7);
yes,player,score,S:=T("","y"),players.next(),0,0;
tally:='wrap(player,score){ w:=safeScores[player]+=score; (w>=WIN) };
 
while(True){
print("Player %d: (%d, %d). Rolling? (y/n) ".fmt(player+1,S,score));
if(yes.holds(ask().strip().toLower())){
rolled:=rollDie(); println(" Rolled a %d".fmt(rolled));
if(rolled==1){
println(" Bust! You lose %d but keep %d\n".fmt(score,S));
}else{
score+=rolled;
if(score + S>=WIN){ tally(player,score); break; }
continue;
}
}else{
if(tally(player,score)) break;
println(" Sticking with %d\n".fmt(safeScores[player]));
}
player,score,S=players.next(),0,safeScores[player];
}
println("\n\nPlayer %d wins with a score of %d".fmt(player+1, safeScores[player]));</syntaxhighlight>
{{out}}
<pre>
Player 1: (0, 0). Rolling? (y/n)
Rolled a 5
Player 1: (0, 5). Rolling? (y/n)
Rolled a 4
Player 1: (0, 9). Rolling? (y/n)
Rolled a 1
Bust! You lose 9 but keep 0
 
Player 2: (0, 0). Rolling? (y/n)
Rolled a 1
Bust! You lose 0 but keep 0
...
 
Player 1: (49, 0). Rolling? (y/n)
Rolled a 2
Player 1: (49, 2). Rolling? (y/n)
Rolled a 3
Player 1: (49, 5). Rolling? (y/n)
Rolled a 1
Bust! You lose 5 but keep 49
 
Player 2: (49, 0). Rolling? (y/n)
Rolled a 6
Player 2: (49, 6). Rolling? (y/n)
Rolled a 4
Player 2: (49, 10). Rolling? (y/n)
Rolled a 2
Player 2: (49, 12). Rolling? (y/n) n
Sticking with 61
...
Player 2: (99, 0). Rolling? (y/n)
Rolled a 1
Bust! You lose 0 but keep 99
 
Player 1: (72, 0). Rolling? (y/n)
Rolled a 6
Player 1: (72, 6). Rolling? (y/n)
Rolled a 4
Player 1: (72, 10). Rolling? (y/n) n
Sticking with 82
 
Player 2: (99, 0). Rolling? (y/n)
Rolled a 3
 
Player 2 wins with a score of 102
</pre>
 
{{omit from|XSLT|XSLT lacks standard interactive I/O and pseudorandom number generation facilities.}}
2,044

edits