Pig the dice game: Difference between revisions

m
 
(20 intermediate revisions by 13 users not shown)
Line 16:
*   [[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 445 ⟶ 477:
}
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Line 459 ⟶ 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 481 ⟶ 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 535 ⟶ 567:
begin
RND.Reset(Gen);
end Pig;</langsyntaxhighlight>
 
===Solving the Task===
Line 542 ⟶ 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 573 ⟶ 605:
Play(A1, A2, Alice);
Ada.Text_IO.Put_Line("Winner = " & (if Alice then "Alice!" else "Bob!"));
end Play_Pig;</langsyntaxhighlight>
 
{{out}}
Line 603 ⟶ 635:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">Gui, Font, s12, Verdana
Gui, Add, Text, vPlayer0, Player 0
Gui, Add, Text, vSum0, 000
Line 649 ⟶ 681:
 
ButtonReload:
Reload</langsyntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PIG_THE_DICE_GAME.AWK
# converted from LUA
Line 691 ⟶ 723:
exit(0)
}
</syntaxhighlight>
</lang>
 
=={{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
<lang BASIC256>
numjugadores = 2
maxpuntos = 100
Dim almacenpuntos(3)
Line 738 ⟶ 909:
End While
Next jugador
Until false</syntaxhighlight>
</lang>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
<lang c>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Line 825 ⟶ 994:
 
return 0;
}</syntaxhighlight>
}
{{Out}}
 
<pre>Player 1 - You have 0 total points and 0 points this turn
</lang>
 
Output:
<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
 
Line 865 ⟶ 1,030:
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>
</pre>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System;
using System.IO;
 
Line 984 ⟶ 1,147:
}
}
}</syntaxhighlight>
}
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 1,124 ⟶ 1,286:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,142 ⟶ 1,304:
What do you want to do (H)old or (R)oll?
</pre>
 
=={{header|Chipmunk Basic}}==
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 numjugadores = 2
110 maxpuntos = 100
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}}==
<langsyntaxhighlight lang="clojure">(def max 100)
 
(defn roll-dice []
Line 1,184 ⟶ 1,391:
(defn -main [& args]
(println "Pig the Dice Game.")
(play-game {:player1 0, :player2 0} :player1))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program uses the RNG included in PCLU's "misc.lib".
 
pig = cluster is play
rep = null
own pi: stream := stream$primary_input()
own po: stream := stream$primary_output()
own scores: array[int] := array[int]$[0,0]
 
% 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()
pig$play()
end start_up</syntaxhighlight>
{{out}}
<pre style='height:50ex'>Game of Pig
---- -- ----
 
Current scores: Player 1 = 0 Player 2 = 0
 
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 1,218 ⟶ 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 1,253 ⟶ 1,710:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.algorithm, std.random;
enum maxScore = 100;
Line 1,289 ⟶ 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,324 ⟶ 1,781:
{{Trans|Go}}
Thanks JensBorrisholt for library [https://github.com/JensBorrisholt/DelphiConsole System.Console].
<langsyntaxhighlight Delphilang="delphi">program Pig_the_dice_game;
 
{$APPTYPE CONSOLE}
Line 1,405 ⟶ 1,862:
writeln(format('Player %d wins!!!', [(turn - 1) mod Length(playerScores)]));
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Player 0 has: 96 points
Line 1,415 ⟶ 1,872:
 
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">
<lang Eiffel>
class
PLAYER
Line 1,470 ⟶ 2,062:
points: INTEGER
end
</syntaxhighlight>
</lang>
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
PIG_THE_DICE
Line 1,517 ⟶ 2,109:
winner: PLAYER
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,536 ⟶ 2,128:
pig: PIG_THE_DICE
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,562 ⟶ 2,154:
=={{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,659 ⟶ 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,714 ⟶ 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,737 ⟶ 2,353:
; \ show the results
 
pigthedice</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Const numjugadores = 2
Const maxpuntos = 100
Line 1,783 ⟶ 2,399:
Next jugador
Loop
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,840 ⟶ 2,456:
}
fmt.Printf("Player %v wins!!!\n", (turn-1)%len(playerScores))
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Currently hard coded for 2 players, but will work for multiple players
<syntaxhighlight lang="groovy">
<lang Groovy>
class PigDice {
 
Line 1,939 ⟶ 2,555:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
import System.Random (randomRIO)
 
Line 1,982 ⟶ 2,598:
putStrLn "\nInvalid input - please try again."
askPlayer $ Score stack score
</syntaxhighlight>
</lang>
 
Example output:
Line 2,025 ⟶ 2,641:
 
</pre>
 
=={{header|IS-BASIC}}==
<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</lang>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'general/misc/prompt' NB. was require'misc' in j6
 
status=:3 :0
Line 2,117 ⟶ 2,677:
smoutput 'player scores now: ',":scores 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
Line 2,182 ⟶ 2,742:
..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 2,227 ⟶ 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 2,296 ⟶ 2,856:
;
}
}</langsyntaxhighlight>
 
<pre> Player 0: (0, 0) Rolling? (y/n) y
Line 2,332 ⟶ 2,892:
 
Player 1 wins with a score of 102</pre>
 
 
=={{header|JavaScript}}==
<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">
<lang Julia>
type PigPlayer
name::String
Line 2,393 ⟶ 3,000:
 
pig_game([PigPlayer("Alice"), PigPlayer("Bob")])
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,439 ⟶ 3,046:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(Args: Array<String>) {
Line 2,483 ⟶ 3,090:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,585 ⟶ 3,192:
{{works with|lua|5.1}}
Supports any number of players
<langsyntaxhighlight lang="lua">local numPlayers = 2
local maxScore = 100
local scores = { }
Line 2,619 ⟶ 3,226:
end
end
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module GamePig {
Print "Game of Pig"
Line 2,699 ⟶ 3,306:
}
GamePig
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">pig := proc()
local Points, pointsThisTurn, answer, rollNum, i, win;
randomize();
Line 2,746 ⟶ 3,353:
end proc;
 
pig();</langsyntaxhighlight>
{{out}}
<pre>
Line 2,776 ⟶ 3,383:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">DynamicModule[{score, players = {1, 2}, roundscore = 0,
roll}, (score@# = 0) & /@ players;
Panel@Dynamic@
Line 2,794 ⟶ 3,401:
players = RotateLeft@players]]},
Button["Play again.",
roundscore = 0; (score@# = 0) & /@ players]]}]</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">// Pig the Dice for two players.
Player = {}
Player.score = 0
Line 2,840 ⟶ 3,447:
if player.score >= goal then break
end for
end while</langsyntaxhighlight>
 
{{out}}
Line 2,884 ⟶ 3,491:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import random, strformat, strutils
 
randomize()
Line 2,932 ⟶ 3,539:
 
else:
echo " Must be 'r' or 'h', try again"</langsyntaxhighlight>
 
{{out}}
Line 2,990 ⟶ 3,597:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Pig {
function : Main(args : String[]) ~ Nil {
Line 3,030 ⟶ 3,637:
}
}
</syntaxhighlight>
</lang>
<pre>
Player 0: (0, 0) Rolling? (y/n)
Line 3,065 ⟶ 3,672:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">class player (name_init : string) =
object
val name = name_init
Line 3,116 ⟶ 3,723:
let p1 = new player "Steven"
and p2 = new player "John" in
one_turn p1 p2;;</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal|2.6.4}}
 
<langsyntaxhighlight lang="pascal">program Pig;
 
const
Line 3,229 ⟶ 3,836:
else
Congratulate(Player2)
end.</langsyntaxhighlight>
 
=={{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 3,273 ⟶ 3,880:
}
__END__
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
Initially a translation of [[Pig_the_dice_game#Lua|Lua]], but now quite different.
<langsyntaxhighlight Phixlang="phix">constant numPlayers = 2,
maxScore = 100
sequence scores = repeat(0,numPlayers)
Line 3,304 ⟶ 3,911:
end if
end while
printf(1,"\nPlayer %d wins with a score of %d!\n",{player,scores[player]+points})</langsyntaxhighlight>
{{out}}
<pre>
Line 3,324 ⟶ 3,931:
=={{header|PHP}}==
{{trans|D}}
<langsyntaxhighlight lang="php">error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));
 
define('MAXSCORE', 100);
Line 3,356 ⟶ 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 3,395 ⟶ 4,002:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">#!/usr/bin/python3
 
'''
Line 3,431 ⟶ 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 3,470 ⟶ 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 3,501 ⟶ 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" perl6line>constant DIE = 1..6;
sub MAIN (Int :$players = 2, Int :$goal = 100) {
Line 3,537 ⟶ 4,216:
say " Sticking with $safe." if $ante;
}
}</langsyntaxhighlight>
The game defaults to the specified task, but we'll play a shorter game with three players for our example:
{{out}}
Line 3,602 ⟶ 4,281:
:::* names are used for the die faces (in addition to the pip value)
:::* a simple (but aggressive) strategy is used (that favors a human player)
<langsyntaxhighlight lang="rexx">/*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/
sw= linesize() - 1 /*get the width of the terminal screen,*/
parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/
Line 3,701 ⟶ 4,380:
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say; say center(' error! ', max(40, linesize() % 2), "*"); say
do j=1 for arg(); say arg(j); say; end; say; exit 13</langsyntaxhighlight>
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]].
Line 3,825 ⟶ 4,504:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Pig the dice game
 
Line 3,854 ⟶ 4,533:
end
see "Player " + player + " wins with a score of " + safeScore[player]
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,899 ⟶ 4,578:
* transparent game logic
 
<langsyntaxhighlight lang="ruby">class PigGame
Player = Struct.new(:name, :safescore, :score) do
def bust!() self.score = safescore end
Line 3,941 ⟶ 4,620:
end
 
PigGame.new( %w|Samuel Elizabeth| )</langsyntaxhighlight>
 
;Samples from a game:
Line 3,979 ⟶ 4,658:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">numPlayers = 2
maxScore = 100
dim safeScore(numPlayers)
Line 4,004 ⟶ 4,683:
goto [loop]
[winner]
print "Player ";plater;" wins with a score of ";safeScore(player)</langsyntaxhighlight>
 
=={{header|Rust}}==
{{works with|Rust|2018}}
<langsyntaxhighlight Rustlang="rust">use rand::prelude::*;
 
fn main() {
Line 4,138 ⟶ 4,817:
self.score <= 100 || self.status == TurnStatus::Continue
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 4,148 ⟶ 4,827:
{{libheader|Scala 100% Immutable variables}}
{{libheader|Scala Concise}}
<langsyntaxhighlight Scalalang="scala">object PigDice extends App {
private val (maxScore, nPlayers) = (100, 2)
private val rnd = util.Random
Line 4,192 ⟶ 4,871:
 
loop(Game(gameOver = false, 0, 0, Array.ofDim[Int](nPlayers).toVector))
}</langsyntaxhighlight>
 
=={{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 4,274 ⟶ 5,001:
rotateList scores
}
}</langsyntaxhighlight>
Demonstrating with human players:
<langsyntaxhighlight lang="tcl">oo::class create HumanPlayer {
variable me
superclass Player
Line 4,307 ⟶ 5,034:
}
 
pig [HumanPlayer new "Alex"] [HumanPlayer new "Bert"]</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 4,330 ⟶ 5,057:
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">
<lang vb>
Option Explicit
 
Line 4,383 ⟶ 5,143:
MsgBox Replace(WIN, "¤¤¤¤", Cp)
End Sub
</syntaxhighlight>
</lang>
 
=={{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}}==
Line 4,389 ⟶ 5,202:
{{libheader|Wren-ioutil}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "./ioutil" for Input
import "./str" for Str
import "random" for Random
 
Line 4,428 ⟶ 5,241:
System.print(" Your score for the round is now %(score)")
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,548 ⟶ 5,361:
 
=={{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 4,572 ⟶ 5,385:
until Score(Player) >= 100;
Text(0, "Player "); IntOut(0, Player+1); Text(0, " WINS!!!");
]</langsyntaxhighlight>
 
Output:
Line 4,608 ⟶ 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}}
<langsyntaxhighlight lang="zkl">const WIN=100, PLAYERS=2;
players,safeScores:=Walker.cycle([0..PLAYERS-1]), PLAYERS.pump(List(),0);
rollDie:=(1).random.fp(7);
Line 4,634 ⟶ 5,493:
player,score,S=players.next(),0,safeScores[player];
}
println("\n\nPlayer %d wins with a score of %d".fmt(player+1, safeScores[player]));</langsyntaxhighlight>
{{out}}
<pre>
2,063

edits