Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Pig-the-dice-game/00-META.yaml
Normal file
2
Task/Pig-the-dice-game/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Pig_the_dice_game
|
||||
16
Task/Pig-the-dice-game/00-TASK.txt
Normal file
16
Task/Pig-the-dice-game/00-TASK.txt
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
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 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:
|
||||
Create a program to score for, and simulate dice throws for, a two-person game.
|
||||
|
||||
|
||||
;Related task:
|
||||
* [[Pig the dice game/Player]]
|
||||
<br><br>
|
||||
|
||||
25
Task/Pig-the-dice-game/11l/pig-the-dice-game.11l
Normal file
25
Task/Pig-the-dice-game/11l/pig-the-dice-game.11l
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
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]))
|
||||
39
Task/Pig-the-dice-game/AWK/pig-the-dice-game.awk
Normal file
39
Task/Pig-the-dice-game/AWK/pig-the-dice-game.awk
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# 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)
|
||||
}
|
||||
426
Task/Pig-the-dice-game/ActionScript/pig-the-dice-game.as
Normal file
426
Task/Pig-the-dice-game/ActionScript/pig-the-dice-game.as
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
package {
|
||||
|
||||
import flash.display.Graphics;
|
||||
import flash.display.Shape;
|
||||
import flash.display.Sprite;
|
||||
import flash.events.Event;
|
||||
import flash.events.MouseEvent;
|
||||
import flash.text.TextField;
|
||||
import flash.text.TextFieldAutoSize;
|
||||
import flash.text.TextFormat;
|
||||
|
||||
public class PigTheDiceGame extends Sprite {
|
||||
|
||||
/**
|
||||
* The name of the first player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _name1:String = "Player 1";
|
||||
|
||||
/**
|
||||
* The name of the second player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _name2:String = "Player 2";
|
||||
|
||||
/**
|
||||
* True if the next turn is of the second player, false if it is of the first player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _isPlayer2:Boolean = false;
|
||||
|
||||
/**
|
||||
* The score of the first player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var __p1Score:uint;
|
||||
|
||||
/**
|
||||
* The score of the second player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var __p2Score:uint;
|
||||
|
||||
/**
|
||||
* The number of points in the current turn.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var __turnPts:uint;
|
||||
|
||||
/**
|
||||
* The text field displaying the score of the first player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _p1ScoreText:TextField;
|
||||
|
||||
/**
|
||||
* The text field displaying the score of the second player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _p2ScoreText:TextField;
|
||||
|
||||
/**
|
||||
* The button which must be clicked for a player to roll the dice.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _rollButton:Sprite;
|
||||
|
||||
/**
|
||||
* The button which must be clicked for a player to hold.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _holdButton:Sprite;
|
||||
|
||||
/**
|
||||
* The text field displaying the name of the current player.
|
||||
*/
|
||||
private var _currentPlayerText:TextField;
|
||||
|
||||
/**
|
||||
* The text field displaying the number of points in the current turn.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _ptsThisTurnText:TextField;
|
||||
|
||||
/**
|
||||
* The dice.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _dice:Shape;
|
||||
|
||||
/**
|
||||
* The number of points required to win the game.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _maxScore:uint = 100;
|
||||
|
||||
/**
|
||||
* The text field displaying additional information about the game.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private var _statusText:TextField;
|
||||
|
||||
/**
|
||||
* Creates a new PigTheDiceGame instance.
|
||||
*/
|
||||
public function PigTheDiceGame() {
|
||||
if ( stage ) _init();
|
||||
else addEventListener(Event.ADDED_TO_STAGE, _init);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which constructs the dice game when the object is added to the stage.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private function _init(e:Event = null):void {
|
||||
|
||||
// Border and background
|
||||
|
||||
graphics.beginFill(0xFFFFDD);
|
||||
graphics.lineStyle(2, 0xFFCC00);
|
||||
graphics.drawRect(0, 0, 450, 280)
|
||||
|
||||
x = 20;
|
||||
y = 20;
|
||||
|
||||
// Text fields and labels
|
||||
|
||||
var currentPlayerText:TextField = _createTextField(_name1 + "'s turn", 20, 0, 10, 0xDD0000, TextFieldAutoSize.CENTER, width);
|
||||
var p1ScoreLabel:TextField = _createTextField(_name1 + "'s score:", 15, 20, currentPlayerText.y + currentPlayerText.height + 20, 0x000000, TextFieldAutoSize.LEFT, 120);
|
||||
var p1ScoreText:TextField = _createTextField("0", 17, 135, p1ScoreLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50);
|
||||
var p2ScoreLabel:TextField = _createTextField(_name2 + "'s score:", 15, 20, p1ScoreText.y + p1ScoreText.height + 5, 0x000000, TextFieldAutoSize.LEFT, 120);
|
||||
var p2ScoreText:TextField = _createTextField("0", 17, 135, p2ScoreLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50);
|
||||
var ptsThisTurnLabel:TextField = _createTextField("Points in this turn:", 15, 20, p2ScoreText.y + p2ScoreText.height + 15, 0x000000, TextFieldAutoSize.LEFT, 120);
|
||||
var ptsThisTurnText:TextField = _createTextField("0", 17, 135, ptsThisTurnLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50);
|
||||
|
||||
// Dice
|
||||
|
||||
var dice:Shape = new Shape();
|
||||
dice.x = 201;
|
||||
dice.y = ptsThisTurnText.y + ptsThisTurnText.height + 30;
|
||||
dice.visible = false;
|
||||
|
||||
var statusText:TextField = _createTextField("Start Play!", 15, 0, dice.y + 70, 0x0000A0, TextFieldAutoSize.CENTER, 450);
|
||||
|
||||
// "Roll" button
|
||||
|
||||
var rollButton:Sprite = new Sprite();
|
||||
var rollButtonText:TextField = _createTextField("Roll dice", 17, 0, 0, 0x000000, TextFieldAutoSize.CENTER, 100);
|
||||
rollButton.mouseChildren = false;
|
||||
rollButton.buttonMode = true;
|
||||
rollButton.graphics.lineStyle(1, 0x444444);
|
||||
rollButton.graphics.beginFill(0xDDDDDD);
|
||||
rollButton.graphics.drawRect(0, 0, 100, rollButtonText.height);
|
||||
rollButton.x = 330;
|
||||
rollButton.y = 80;
|
||||
rollButton.addChild(rollButtonText);
|
||||
|
||||
// "Hold" button
|
||||
|
||||
var holdButton:Sprite = new Sprite();
|
||||
var holdButtonText:TextField = _createTextField("Hold", 17, 0, 0, 0x000000, TextFieldAutoSize.CENTER, 100);
|
||||
holdButton.mouseChildren = false;
|
||||
holdButton.buttonMode = true;
|
||||
holdButton.graphics.copyFrom(rollButton.graphics);
|
||||
holdButton.x = 330;
|
||||
holdButton.y = rollButton.y + rollButton.height + 10;
|
||||
holdButton.addChild(holdButtonText);
|
||||
|
||||
rollButton.addEventListener(MouseEvent.CLICK, _rollButtonClick);
|
||||
holdButton.addEventListener(MouseEvent.CLICK, _holdButtonClick);
|
||||
|
||||
_currentPlayerText = currentPlayerText;
|
||||
_p1ScoreText = p1ScoreText;
|
||||
_p2ScoreText = p2ScoreText;
|
||||
_ptsThisTurnText = ptsThisTurnText;
|
||||
_rollButton = rollButton;
|
||||
_holdButton = holdButton;
|
||||
_dice = dice;
|
||||
_statusText = statusText;
|
||||
|
||||
addChild(currentPlayerText);
|
||||
addChild(p1ScoreLabel);
|
||||
addChild(p1ScoreText);
|
||||
addChild(p2ScoreLabel);
|
||||
addChild(p2ScoreText);
|
||||
addChild(ptsThisTurnLabel);
|
||||
addChild(ptsThisTurnLabel);
|
||||
addChild(ptsThisTurnText);
|
||||
addChild(statusText);
|
||||
addChild(_dice);
|
||||
addChild(rollButton);
|
||||
addChild(holdButton);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new text field.
|
||||
*
|
||||
* @param text The text to be displayed in the text field.
|
||||
* @param size The font size of the text.
|
||||
* @param x The x-coordinate of the text field.
|
||||
* @param y The y-coordinate of the text field.
|
||||
* @param colour The text colour.
|
||||
* @param autoSize The text alignment mode.
|
||||
* @param width The width of the text field.
|
||||
* @return A TextField object.
|
||||
* @private
|
||||
*/
|
||||
private function _createTextField(text:String, size:Number, x:Number, y:Number, colour:uint, autoSize:String, width:Number):TextField {
|
||||
var t:TextField = new TextField();
|
||||
t.defaultTextFormat = new TextFormat(null, size, colour);
|
||||
t.autoSize = autoSize;
|
||||
t.x = x;
|
||||
t.y = y;
|
||||
t.width = width;
|
||||
t.text = text;
|
||||
t.height = t.textHeight + 5;
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls the dice.
|
||||
*
|
||||
* @return The result of the roll (1-6)
|
||||
* @private
|
||||
*/
|
||||
private function _rollDice():uint {
|
||||
|
||||
// Since Math.random() returns a number between 0 and 1, multiplying it by 6 and then rounding down
|
||||
// gives a number between 0 and 5, so add 1 to it.
|
||||
|
||||
var roll:uint = uint(Math.random() * 6) + 1;
|
||||
|
||||
_dice.visible = true;
|
||||
var diceGraphics:Graphics = _dice.graphics;
|
||||
|
||||
// Draw the dice.
|
||||
|
||||
diceGraphics.clear();
|
||||
diceGraphics.lineStyle(2, 0x555555);
|
||||
diceGraphics.beginFill(0xFFFFFF);
|
||||
diceGraphics.drawRect(0, 0, 48, 48);
|
||||
diceGraphics.beginFill(0x000000);
|
||||
diceGraphics.lineStyle(0);
|
||||
|
||||
switch ( roll ) {
|
||||
case 1:
|
||||
diceGraphics.drawCircle(24, 24, 3);
|
||||
break;
|
||||
case 2:
|
||||
diceGraphics.drawCircle(16, 16, 3);
|
||||
diceGraphics.drawCircle(32, 32, 3);
|
||||
break;
|
||||
case 3:
|
||||
diceGraphics.drawCircle(12, 12, 3);
|
||||
diceGraphics.drawCircle(24, 24, 3);
|
||||
diceGraphics.drawCircle(36, 36, 3);
|
||||
break;
|
||||
case 4:
|
||||
diceGraphics.drawCircle(16, 16, 3);
|
||||
diceGraphics.drawCircle(16, 32, 3);
|
||||
diceGraphics.drawCircle(32, 16, 3);
|
||||
diceGraphics.drawCircle(32, 32, 3);
|
||||
break;
|
||||
case 5:
|
||||
diceGraphics.drawCircle(12, 12, 3);
|
||||
diceGraphics.drawCircle(24, 24, 3);
|
||||
diceGraphics.drawCircle(36, 36, 3);
|
||||
diceGraphics.drawCircle(36, 12, 3);
|
||||
diceGraphics.drawCircle(12, 36, 3);
|
||||
break;
|
||||
case 6:
|
||||
diceGraphics.drawCircle(16, 12, 3);
|
||||
diceGraphics.drawCircle(16, 24, 3);
|
||||
diceGraphics.drawCircle(16, 36, 3);
|
||||
diceGraphics.drawCircle(32, 12, 3);
|
||||
diceGraphics.drawCircle(32, 24, 3);
|
||||
diceGraphics.drawCircle(32, 36, 3);
|
||||
break;
|
||||
}
|
||||
|
||||
return roll;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The score of the first player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private function get _p1Score():uint {
|
||||
return __p1Score;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private function set _p1Score(value:uint):void {
|
||||
__p1Score = value;
|
||||
_p1ScoreText.text = String(value);
|
||||
|
||||
if ( value >= _maxScore ) {
|
||||
_currentPlayerText.text = "Game over!";
|
||||
_statusText.text = _name1 + " wins!";
|
||||
removeChild(_rollButton);
|
||||
removeChild(_holdButton);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The score of the second player.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private function get _p2Score():uint {
|
||||
return __p2Score;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private function set _p2Score(value:uint):void {
|
||||
__p2Score = value;
|
||||
_p2ScoreText.text = String(value);
|
||||
|
||||
if ( value >= _maxScore ) {
|
||||
_currentPlayerText.text = "Game over!";
|
||||
_statusText.text = _name2 + " wins!";
|
||||
removeChild(_rollButton);
|
||||
removeChild(_holdButton);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of points in the current turn.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private function get _turnPts():uint {
|
||||
return __turnPts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private function set _turnPts(value:uint):void {
|
||||
__turnPts = value;
|
||||
_ptsThisTurnText.text = String(value);
|
||||
|
||||
if ( _isPlayer2 && __p2Score + value >= _maxScore ) {
|
||||
_ptsThisTurnText.text = "0";
|
||||
_p2Score += value;
|
||||
}
|
||||
else if ( ! _isPlayer2 && __p1Score + value >= _maxScore ) {
|
||||
_ptsThisTurnText.text = "0";
|
||||
_p1Score += value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function called when the "Roll dice" button is clicked.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private function _rollButtonClick(e:MouseEvent):void {
|
||||
var roll:uint = _rollDice();
|
||||
|
||||
if ( roll == 1 ) {
|
||||
if ( _isPlayer2 ) {
|
||||
_currentPlayerText.text = _name1 + "'s turn";
|
||||
_statusText.text = _name2 + " rolls 1 and loses " + __turnPts + " points. " + _name1 + "'s turn now.";
|
||||
}
|
||||
else {
|
||||
_currentPlayerText.text = _name2 + "'s turn";
|
||||
_statusText.text = _name1 + " rolls 1 and loses " + __turnPts + " points. " + _name2 + "'s turn now.";
|
||||
}
|
||||
|
||||
_isPlayer2 = ! _isPlayer2;
|
||||
_turnPts = 0;
|
||||
}
|
||||
else {
|
||||
_turnPts += roll;
|
||||
_statusText.text = "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function called when the "Hold" button is clicked.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private function _holdButtonClick(e:MouseEvent):void {
|
||||
if ( _isPlayer2 ) {
|
||||
_currentPlayerText.text = _name1 + "'s turn";
|
||||
_statusText.text = _name2 + " holds and wins " + __turnPts + " points. " + _name1 + "'s turn now.";
|
||||
_p2Score += __turnPts;
|
||||
}
|
||||
else {
|
||||
_currentPlayerText.text = _name2 + "'s turn";
|
||||
_statusText.text = _name1 + " holds and wins " + __turnPts + " points. " + _name2 + "'s turn now.";
|
||||
_p1Score += __turnPts;
|
||||
}
|
||||
|
||||
_dice.visible = false;
|
||||
_turnPts = 0;
|
||||
_isPlayer2 = ! _isPlayer2;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
23
Task/Pig-the-dice-game/Ada/pig-the-dice-game-1.ada
Normal file
23
Task/Pig-the-dice-game/Ada/pig-the-dice-game-1.ada
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package Pig is
|
||||
|
||||
type Dice_Score is range 1 .. 6;
|
||||
|
||||
type Player is tagged private;
|
||||
function Recent(P: Player) return Natural;
|
||||
function All_Recent(P: Player) return Natural;
|
||||
function Score(P: Player) return Natural;
|
||||
|
||||
type Actor is abstract tagged null record;
|
||||
function Roll_More(A: Actor; Self, Opponent: Player'Class)
|
||||
return Boolean is abstract;
|
||||
|
||||
procedure Play(First, Second: Actor'Class; First_Wins: out Boolean);
|
||||
|
||||
private
|
||||
type Player is tagged record
|
||||
Score: Natural := 0;
|
||||
All_Recent: Natural := 0;
|
||||
Recent_Roll: Dice_Score := 1;
|
||||
end record;
|
||||
|
||||
end Pig;
|
||||
51
Task/Pig-the-dice-game/Ada/pig-the-dice-game-2.ada
Normal file
51
Task/Pig-the-dice-game/Ada/pig-the-dice-game-2.ada
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
with Ada.Numerics.Discrete_Random;
|
||||
package body Pig is
|
||||
|
||||
function Score(P: Player) return Natural is (P.Score);
|
||||
function All_Recent(P: Player) return Natural is (P.All_Recent);
|
||||
function Recent(P: Player) return Natural is (Natural(P.Recent_Roll));
|
||||
function Has_Won(P: Player) return Boolean is (P.Score >= 100);
|
||||
|
||||
package RND is new Ada.Numerics.Discrete_Random(Dice_Score);
|
||||
Gen: RND.Generator;
|
||||
|
||||
procedure Roll(P: in out Player) is
|
||||
begin
|
||||
P.Recent_Roll := RND.Random(Gen);
|
||||
if P.Recent = 1 then
|
||||
P.All_Recent := 0;
|
||||
else
|
||||
P.All_Recent := P.All_Recent + P.Recent;
|
||||
end if;
|
||||
end Roll;
|
||||
|
||||
procedure Add_To_Score(P: in out Player) is
|
||||
begin
|
||||
P.Score := P.Score + P.All_Recent;
|
||||
P.All_Recent := 0;
|
||||
end Add_To_Score;
|
||||
|
||||
procedure Play(First, Second: Actor'Class;
|
||||
First_Wins: out Boolean) is
|
||||
P1, P2: Player;
|
||||
begin
|
||||
loop
|
||||
Roll(P1);
|
||||
while First.Roll_More(P1, P2) and then P1.Recent > 1 loop
|
||||
Roll(P1);
|
||||
end loop;
|
||||
Add_To_Score(P1);
|
||||
exit when P1.Score >= 100;
|
||||
Roll(P2);
|
||||
while Second.Roll_More(P2, P1) and then P2.Recent > 1 loop
|
||||
Roll(P2);
|
||||
end loop;
|
||||
Add_To_Score(P2);
|
||||
exit when P2.Score >= 100;
|
||||
end loop;
|
||||
First_Wins := P1.Score >= 100;
|
||||
end Play;
|
||||
|
||||
begin
|
||||
RND.Reset(Gen);
|
||||
end Pig;
|
||||
32
Task/Pig-the-dice-game/Ada/pig-the-dice-game-3.ada
Normal file
32
Task/Pig-the-dice-game/Ada/pig-the-dice-game-3.ada
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
with Pig, Ada.Text_IO;
|
||||
|
||||
procedure Play_Pig is
|
||||
|
||||
use Pig;
|
||||
|
||||
type Hand is new Actor with record
|
||||
Name: String(1 .. 5);
|
||||
end record;
|
||||
function Roll_More(A: Hand; Self, Opponent: Player'Class) return Boolean;
|
||||
|
||||
function Roll_More(A: Hand; Self, Opponent: Player'Class) return Boolean is
|
||||
Ch: Character := ' ';
|
||||
use Ada.Text_IO;
|
||||
begin
|
||||
Put(A.Name & " you:" & Natural'Image(Self.Score) &
|
||||
" (opponent:" & Natural'Image(Opponent.Score) &
|
||||
") this round:" & Natural'Image(Self.All_Recent) &
|
||||
" this roll:" & Natural'Image(Self.Recent) &
|
||||
"; add to score(+)?");
|
||||
Get(Ch);
|
||||
return Ch /= '+';
|
||||
end Roll_More;
|
||||
|
||||
A1: Hand := (Name => "Alice");
|
||||
A2: Hand := (Name => "Bob ");
|
||||
|
||||
Alice: Boolean;
|
||||
begin
|
||||
Play(A1, A2, Alice);
|
||||
Ada.Text_IO.Put_Line("Winner = " & (if Alice then "Alice!" else "Bob!"));
|
||||
end Play_Pig;
|
||||
47
Task/Pig-the-dice-game/AutoHotkey/pig-the-dice-game.ahk
Normal file
47
Task/Pig-the-dice-game/AutoHotkey/pig-the-dice-game.ahk
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
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
|
||||
43
Task/Pig-the-dice-game/BASIC256/pig-the-dice-game.basic
Normal file
43
Task/Pig-the-dice-game/BASIC256/pig-the-dice-game.basic
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
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
|
||||
135
Task/Pig-the-dice-game/C++/pig-the-dice-game.cpp
Normal file
135
Task/Pig-the-dice-game/C++/pig-the-dice-game.cpp
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
#include <windows.h>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
//--------------------------------------------------------------------------------------------------
|
||||
using namespace std;
|
||||
|
||||
//--------------------------------------------------------------------------------------------------
|
||||
const int PLAYERS = 2, MAX_POINTS = 100;
|
||||
|
||||
//--------------------------------------------------------------------------------------------------
|
||||
class player
|
||||
{
|
||||
public:
|
||||
player() { reset(); }
|
||||
void reset()
|
||||
{
|
||||
name = "";
|
||||
current_score = round_score = 0;
|
||||
}
|
||||
string getName() { return name; }
|
||||
void setName( string n ) { name = n; }
|
||||
int getCurrScore() { return current_score; }
|
||||
void addCurrScore() { current_score += round_score; }
|
||||
int getRoundScore() { return round_score; }
|
||||
void addRoundScore( int rs ) { round_score += rs; }
|
||||
void zeroRoundScore() { round_score = 0; }
|
||||
|
||||
private:
|
||||
string name;
|
||||
int current_score, round_score;
|
||||
};
|
||||
//--------------------------------------------------------------------------------------------------
|
||||
class pigGame
|
||||
{
|
||||
public:
|
||||
pigGame() { resetPlayers(); }
|
||||
|
||||
void play()
|
||||
{
|
||||
while( true )
|
||||
{
|
||||
system( "cls" );
|
||||
int p = 0;
|
||||
while( true )
|
||||
{
|
||||
if( turn( p ) )
|
||||
{
|
||||
praise( p );
|
||||
break;
|
||||
}
|
||||
|
||||
++p %= PLAYERS;
|
||||
}
|
||||
|
||||
string r;
|
||||
cout << "Do you want to play again ( y / n )? "; cin >> r;
|
||||
if( r != "Y" && r != "y" ) return;
|
||||
resetPlayers();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void resetPlayers()
|
||||
{
|
||||
system( "cls" );
|
||||
string n;
|
||||
for( int p = 0; p < PLAYERS; p++ )
|
||||
{
|
||||
_players[p].reset();
|
||||
cout << "Enter name player " << p + 1 << ": "; cin >> n;
|
||||
_players[p].setName( n );
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void praise( int p )
|
||||
{
|
||||
system( "cls" );
|
||||
cout << "CONGRATULATIONS " << _players[p].getName() << ", you are the winner!" << endl << endl;
|
||||
cout << "Final Score" << endl;
|
||||
drawScoreboard();
|
||||
cout << endl << endl;
|
||||
}
|
||||
|
||||
void drawScoreboard()
|
||||
{
|
||||
for( int p = 0; p < PLAYERS; p++ )
|
||||
cout << _players[p].getName() << ": " << _players[p].getCurrScore() << " points" << endl;
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
bool turn( int p )
|
||||
{
|
||||
system( "cls" );
|
||||
drawScoreboard();
|
||||
_players[p].zeroRoundScore();
|
||||
string r;
|
||||
int die;
|
||||
while( true )
|
||||
{
|
||||
cout << _players[p].getName() << ", your round score is: " << _players[p].getRoundScore() << endl;
|
||||
cout << "What do you want to do (H)old or (R)oll? "; cin >> r;
|
||||
if( r == "h" || r == "H" )
|
||||
{
|
||||
_players[p].addCurrScore();
|
||||
return _players[p].getCurrScore() >= MAX_POINTS;
|
||||
}
|
||||
if( r == "r" || r == "R" )
|
||||
{
|
||||
die = rand() % 6 + 1;
|
||||
if( die == 1 )
|
||||
{
|
||||
cout << _players[p].getName() << ", your turn is over." << endl << endl;
|
||||
system( "pause" );
|
||||
return false;
|
||||
}
|
||||
_players[p].addRoundScore( die );
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
player _players[PLAYERS];
|
||||
};
|
||||
//--------------------------------------------------------------------------------------------------
|
||||
int main( int argc, char* argv[] )
|
||||
{
|
||||
srand( GetTickCount() );
|
||||
pigGame pg;
|
||||
pg.play();
|
||||
return 0;
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------
|
||||
115
Task/Pig-the-dice-game/C-sharp/pig-the-dice-game.cs
Normal file
115
Task/Pig-the-dice-game/C-sharp/pig-the-dice-game.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
83
Task/Pig-the-dice-game/C/pig-the-dice-game.c
Normal file
83
Task/Pig-the-dice-game/C/pig-the-dice-game.c
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
#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;
|
||||
}
|
||||
100
Task/Pig-the-dice-game/CLU/pig-the-dice-game.clu
Normal file
100
Task/Pig-the-dice-game/CLU/pig-the-dice-game.clu
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
% 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
|
||||
41
Task/Pig-the-dice-game/Clojure/pig-the-dice-game.clj
Normal file
41
Task/Pig-the-dice-game/Clojure/pig-the-dice-game.clj
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
(def max 100)
|
||||
|
||||
(defn roll-dice []
|
||||
(let [roll (inc (rand-int 6))]
|
||||
(println "Rolled:" roll) roll))
|
||||
|
||||
(defn switch [player]
|
||||
(if (= player :player1) :player2 :player1))
|
||||
|
||||
(defn find-winner [game]
|
||||
(cond
|
||||
(>= (:player1 game) max) :player1
|
||||
(>= (:player2 game) max) :player2
|
||||
:else nil))
|
||||
|
||||
(defn bust []
|
||||
(println "Busted!") 0)
|
||||
|
||||
(defn hold [points]
|
||||
(println "Sticking with" points) points)
|
||||
|
||||
(defn play-round [game player temp-points]
|
||||
(println (format "%s: (%s, %s). Want to Roll? (y/n) " (name player) (player game) temp-points))
|
||||
(let [input (clojure.string/upper-case (read-line))]
|
||||
(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]
|
||||
(let [winner (find-winner game)]
|
||||
(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]
|
||||
(println "Pig the Dice Game.")
|
||||
(play-game {:player1 0, :player2 0} :player1))
|
||||
32
Task/Pig-the-dice-game/Common-Lisp/pig-the-dice-game.lisp
Normal file
32
Task/Pig-the-dice-game/Common-Lisp/pig-the-dice-game.lisp
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
(defconstant +max-score+ 100)
|
||||
(defconstant +n-of-players+ 2)
|
||||
|
||||
(let ((scores (make-list +n-of-players+ :initial-element 0))
|
||||
(current-player 0)
|
||||
(round-score 0))
|
||||
(loop
|
||||
(format t "Player ~d: (~d, ~d). Rolling? (Y)"
|
||||
current-player
|
||||
(nth current-player scores)
|
||||
round-score)
|
||||
(if (member (read-line) '("y" "yes" "") :test #'string=)
|
||||
(let ((roll (1+ (random 6))))
|
||||
(format t "~tRolled ~d~%" roll)
|
||||
(if (= roll 1)
|
||||
(progn
|
||||
(format t
|
||||
"~tBust! you lose ~d but still keep your previous ~d~%"
|
||||
round-score (nth current-player scores))
|
||||
(setf round-score 0)
|
||||
(setf current-player
|
||||
(mod (1+ current-player) +n-of-players+)))
|
||||
(incf round-score roll)))
|
||||
(progn
|
||||
(incf (nth current-player scores) round-score)
|
||||
(setf round-score 0)
|
||||
(when (>= (apply #'max scores) 100)
|
||||
(return))
|
||||
(format t "~tSticking with ~d~%" (nth current-player scores))
|
||||
(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)))
|
||||
37
Task/Pig-the-dice-game/D/pig-the-dice-game.d
Normal file
37
Task/Pig-the-dice-game/D/pig-the-dice-game.d
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
void main() {
|
||||
import std.stdio, std.string, std.algorithm, std.random;
|
||||
enum maxScore = 100;
|
||||
enum playerCount = 2;
|
||||
immutable confirmations = ["yes", "y", ""];
|
||||
|
||||
int[playerCount] safeScore;
|
||||
int player, score;
|
||||
|
||||
while (true) {
|
||||
writef(" Player %d: (%d, %d). Rolling? (y/n) ", player,
|
||||
safeScore[player], score);
|
||||
if (safeScore[player] + score < maxScore &&
|
||||
confirmations.canFind(readln.strip.toLower)) {
|
||||
immutable rolled = uniform(1, 7);
|
||||
writefln(" Rolled %d", rolled);
|
||||
if (rolled == 1) {
|
||||
writefln(" Bust! You lose %d but keep %d\n",
|
||||
score, safeScore[player]);
|
||||
} else {
|
||||
score += rolled;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
safeScore[player] += score;
|
||||
if (safeScore[player] >= maxScore)
|
||||
break;
|
||||
writefln(" Sticking with %d\n", safeScore[player]);
|
||||
}
|
||||
|
||||
score = 0;
|
||||
player = (player + 1) % playerCount;
|
||||
}
|
||||
|
||||
writefln("\n\nPlayer %d wins with a score of %d",
|
||||
player, safeScore[player]);
|
||||
}
|
||||
82
Task/Pig-the-dice-game/Delphi/pig-the-dice-game.delphi
Normal file
82
Task/Pig-the-dice-game/Delphi/pig-the-dice-game.delphi
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
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.
|
||||
51
Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-1.e
Normal file
51
Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-1.e
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
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
|
||||
45
Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-2.e
Normal file
45
Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-2.e
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
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
|
||||
16
Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-3.e
Normal file
16
Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-3.e
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
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
|
||||
96
Task/Pig-the-dice-game/Erlang/pig-the-dice-game.erl
Normal file
96
Task/Pig-the-dice-game/Erlang/pig-the-dice-game.erl
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
-module( pig_dice ).
|
||||
|
||||
-export( [game/1, goal/0, hold/2, player_name/1, players_totals/1, quit/2, roll/2, score/1, task/0] ).
|
||||
|
||||
-record( player, {name, score=0, total=0} ).
|
||||
|
||||
game( [_Player | _T]=Players ) ->
|
||||
My_pid = erlang:self(),
|
||||
erlang:spawn_link( fun() -> random:seed(os:timestamp()), game_loop( [#player{name=X} || X <- Players], 100, My_pid ) end ).
|
||||
|
||||
goal() -> 100.
|
||||
|
||||
hold( Player, Game ) -> Game ! {next_player, Player}.
|
||||
|
||||
players_totals( Game ) -> ask( Game, players_totals ).
|
||||
|
||||
player_name( Game ) -> ask( Game, name ).
|
||||
|
||||
quit( Player, Game ) -> Game ! {quit, Player}.
|
||||
|
||||
roll( Player, Game ) -> Game ! {roll, Player}.
|
||||
|
||||
score( Game ) -> ask( Game, score ).
|
||||
|
||||
task() ->
|
||||
Game = game( ["Player1", "Player2"] ),
|
||||
Play = erlang:spawn( fun() -> play_loop( Game ) end ),
|
||||
receive
|
||||
{pig, Result, Game} ->
|
||||
erlang:exit( Play, kill ),
|
||||
task_display( Result ),
|
||||
Result
|
||||
end.
|
||||
|
||||
|
||||
|
||||
ask( Game, Question ) ->
|
||||
Game ! {Question, erlang:self()},
|
||||
receive
|
||||
{Question, Answer, Game} -> Answer
|
||||
end.
|
||||
|
||||
game_loop( [], _Goal, Report_pid ) -> Report_pid ! {pig, game_over_all_quite. erlang:self()};
|
||||
game_loop( [#player{name=Name}=Player | T]=Players, Goal, Report_pid ) ->
|
||||
receive
|
||||
{name, Pid} ->
|
||||
Pid ! {name, Player#player.name, erlang:self()},
|
||||
game_loop( Players, Goal, Report_pid );
|
||||
{next_player, Name} ->
|
||||
New_players = game_loop_next_player( Player#player.total + Player#player.score, Players, Goal, Report_pid ),
|
||||
game_loop( New_players, Goal, Report_pid );
|
||||
{players_totals, Pid} ->
|
||||
Pid ! {players_totals, [{X#player.name, X#player.total} || X <- Players], erlang:self()},
|
||||
game_loop( Players, Goal, Report_pid );
|
||||
{quit, Name} -> game_loop( T, Goal, Report_pid );
|
||||
{roll, Name} ->
|
||||
New_players = game_loop_roll( random:uniform(6), Players ),
|
||||
game_loop( New_players, Goal, Report_pid );
|
||||
{score, Pid} ->
|
||||
Pid ! {score, Player#player.score, erlang:self()},
|
||||
game_loop( Players, Goal, Report_pid )
|
||||
end.
|
||||
|
||||
game_loop_next_player( Total, [Player | T], Goal, Report_pid ) when Total >= Goal ->
|
||||
Report_pid ! {pig, [{X#player.name, X#player.total} || X <- [Player | T]]. erlang:self()},
|
||||
[];
|
||||
game_loop_next_player( Total, [Player | T], _Goal, _Report_pid ) ->
|
||||
T ++ [Player#player{score=0, total=Total}].
|
||||
|
||||
game_loop_roll( 1, [Player | T] ) -> T ++ [Player#player{score=0}];
|
||||
game_loop_roll( Score, [#player{score=Old_score}=Player | T] ) -> [Player#player{score=Old_score + Score} | T].
|
||||
|
||||
play_loop( Game ) ->
|
||||
Name = player_name( Game ),
|
||||
io:fwrite( "Currently ~p.~n", [players_totals(Game)] ),
|
||||
io:fwrite( "Name ~p.~n", [Name] ),
|
||||
roll( Name, Game ),
|
||||
Score = score( Game ),
|
||||
io:fwrite( "Rolled, score this round ~p.~n", [Score] ),
|
||||
play_loop_next( Score, Name, Game ),
|
||||
play_loop( Game ).
|
||||
|
||||
play_loop_command( {ok, ["y" ++ _T]}, _Name, _Game ) -> ok;
|
||||
play_loop_command( {ok, ["n" ++ _T]}, Name, Game ) -> hold( Name, Game );
|
||||
play_loop_command( {ok, ["q" ++ _T]}, Name, Game ) -> quit( Name, Game );
|
||||
play_loop_command( {ok, _T}, Name, Game ) -> play_loop_command( io:fread("Roll again (y/n/q): ", "~s"), Name, Game ).
|
||||
|
||||
play_loop_next( 0, _Name, _Game ) -> io:fwrite( "~nScore 0, next player.~n" );
|
||||
play_loop_next( _Score, Name, Game ) -> play_loop_command( io:fread("Roll again (y/n/q): ", "~s"), Name, Game ).
|
||||
|
||||
task_display( Results ) when is_list(Results) ->
|
||||
[{Name, Total} | Rest] = lists:reverse( lists:keysort(2, Results) ),
|
||||
io:fwrite( "Winner is ~p with total of ~p~n", [Name, Total] ),
|
||||
io:fwrite( "Then follows: " ),
|
||||
[io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest];
|
||||
task_display( Result ) -> io:fwrite( "Result: ~p~n", [Result] ).
|
||||
22
Task/Pig-the-dice-game/FOCAL/pig-the-dice-game.focal
Normal file
22
Task/Pig-the-dice-game/FOCAL/pig-the-dice-game.focal
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
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"!
|
||||
21
Task/Pig-the-dice-game/Forth/pig-the-dice-game.fth
Normal file
21
Task/Pig-the-dice-game/Forth/pig-the-dice-game.fth
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
include lib/choose.4th
|
||||
include lib/yesorno.4th
|
||||
|
||||
: turn ( n1 -- n2)
|
||||
." Player " . ." is up" cr \ which player is up
|
||||
0 begin \ nothing so far
|
||||
s" Rolling" yes/no? \ stand or roll?
|
||||
while \ now roll the dice
|
||||
6 choose 1+ dup ." Rolling " . dup 1 =
|
||||
if drop drop 0 else + ." (" dup 0 .r ." )" then cr dup 0=
|
||||
until \ until player stands or 1 is rolled
|
||||
;
|
||||
|
||||
: pigthedice ( --)
|
||||
2 0 1 over \ setup players
|
||||
begin over turn + dup ." Total score: " . cr cr dup 100 < while 2swap repeat
|
||||
." Player " swap . ." won with " . ." points." cr
|
||||
." Player " swap . ." lost with " . ." points." cr
|
||||
; \ show the results
|
||||
|
||||
pigthedice
|
||||
42
Task/Pig-the-dice-game/FreeBASIC/pig-the-dice-game.basic
Normal file
42
Task/Pig-the-dice-game/FreeBASIC/pig-the-dice-game.basic
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
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
|
||||
55
Task/Pig-the-dice-game/Go/pig-the-dice-game.go
Normal file
55
Task/Pig-the-dice-game/Go/pig-the-dice-game.go
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
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))
|
||||
}
|
||||
94
Task/Pig-the-dice-game/Groovy/pig-the-dice-game.groovy
Normal file
94
Task/Pig-the-dice-game/Groovy/pig-the-dice-game.groovy
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
class PigDice {
|
||||
|
||||
final static int maxScore = 100;
|
||||
final static yesses = ["yes", "y", "", "Y", "YES"]
|
||||
|
||||
static main(args) {
|
||||
def playersCount = 2
|
||||
Scanner sc = new Scanner(System.in)
|
||||
Map scores = [:]
|
||||
def current = 0
|
||||
def player = 0
|
||||
def gameOver = false
|
||||
def firstThrow = true
|
||||
Random rnd = new Random()
|
||||
|
||||
// Initialise the players' scores
|
||||
(0..(playersCount-1)).each{ it->
|
||||
scores[it] = 0
|
||||
}
|
||||
|
||||
// Game starts
|
||||
while (!gameOver) {
|
||||
def nextPlayer = false
|
||||
String ln
|
||||
|
||||
// Automatic rolls for the first dice roll
|
||||
if (firstThrow){
|
||||
println "player ${player+1} Auto Rolling... "
|
||||
ln = 'y'
|
||||
firstThrow = false
|
||||
} else {
|
||||
println "player ${player+1} Rolling? Yes(y) or No(n) "
|
||||
ln = sc.nextLine()
|
||||
}
|
||||
|
||||
if (ln in yesses){
|
||||
// if yes then roll the dice
|
||||
int rolled = rnd.nextInt(6) + 1
|
||||
print "The Roll was $rolled --- "
|
||||
|
||||
if (rolled == 1) {
|
||||
println " Bust! Player ${player+1} loses $current but keep ${scores[player]}"
|
||||
current = 0
|
||||
nextPlayer = true
|
||||
firstThrow = true
|
||||
} else {
|
||||
// dice rolls 2 to 6
|
||||
current = current + rolled
|
||||
if ((current + scores[player]) > maxScore){
|
||||
gameOver = true
|
||||
}else{
|
||||
// as a session score gets larger the message returned changes
|
||||
switch (current){
|
||||
case 6..15:
|
||||
print "Good. "
|
||||
break
|
||||
case 15..29:
|
||||
print "lucky! "
|
||||
break
|
||||
case 29..39:
|
||||
print "Great! "
|
||||
break
|
||||
default:
|
||||
print "Amazing "
|
||||
}
|
||||
println "Player ${player+1} now has $current this session (possible score of ${current + scores[player]})"
|
||||
}
|
||||
}
|
||||
} else{
|
||||
// if no then bank the session score
|
||||
nextPlayer = true
|
||||
firstThrow = true
|
||||
scores[player] = scores[player] + current
|
||||
current = 0
|
||||
println "chicken! player ${player+1} now has ${scores[player]} and $gameOver"
|
||||
println "Current scores :"
|
||||
for (i in scores){
|
||||
println "player ${i.key + 1}| ${i.value} "
|
||||
}
|
||||
println "------------------------------"
|
||||
|
||||
}
|
||||
println ""
|
||||
|
||||
if (nextPlayer) {
|
||||
player = (player+1)%playersCount
|
||||
println "** Next player is ${player+1}"
|
||||
}
|
||||
}
|
||||
|
||||
// Game ends
|
||||
println "Player ${player+1} wins"
|
||||
}
|
||||
}
|
||||
39
Task/Pig-the-dice-game/Haskell/pig-the-dice-game.hs
Normal file
39
Task/Pig-the-dice-game/Haskell/pig-the-dice-game.hs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
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
|
||||
54
Task/Pig-the-dice-game/IS-BASIC/pig-the-dice-game.basic
Normal file
54
Task/Pig-the-dice-game/IS-BASIC/pig-the-dice-game.basic
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
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
|
||||
34
Task/Pig-the-dice-game/J/pig-the-dice-game-1.j
Normal file
34
Task/Pig-the-dice-game/J/pig-the-dice-game-1.j
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
require'general/misc/prompt' NB. was require'misc' in j6
|
||||
|
||||
status=:3 :0
|
||||
'pid cur tot'=. y
|
||||
player=. 'player ',":pid
|
||||
potential=. ' potential: ',":cur
|
||||
total=. ' total: ',":tot
|
||||
smoutput player,potential,total
|
||||
)
|
||||
|
||||
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'
|
||||
)
|
||||
|
||||
NB. simulate an y player game of pig
|
||||
pigsim=:3 :0
|
||||
smoutput (":y),' player game of pig'
|
||||
scores=.y#0
|
||||
while.100>>./scores do.
|
||||
for_player.=i.y do.
|
||||
smoutput 'begining of turn for player ',":pid=.1+I.player
|
||||
current=. 0
|
||||
whilst. (1 ~: roll) *. 'R' = move do.
|
||||
status pid, current, player+/ .*scores
|
||||
if.'R'=move=. getmove'' do.
|
||||
smoutput 'rolled a ',":roll=. 1+?6
|
||||
current=. (1~:roll)*current+roll end. end.
|
||||
scores=. scores+(current*player)+100*('Q'e.move)*-.player
|
||||
smoutput 'player scores now: ',":scores end. end.
|
||||
smoutput 'player ',(":1+I.scores>:100),' wins'
|
||||
)
|
||||
62
Task/Pig-the-dice-game/J/pig-the-dice-game-2.j
Normal file
62
Task/Pig-the-dice-game/J/pig-the-dice-game-2.j
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
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
|
||||
Roll the dice or Hold or Quit? [R or H or Q]: R
|
||||
rolled a 6
|
||||
player 2 potential: 9 total: 0
|
||||
Roll the dice or Hold or Quit? [R or H or Q]: R
|
||||
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
|
||||
42
Task/Pig-the-dice-game/Java/pig-the-dice-game-1.java
Normal file
42
Task/Pig-the-dice-game/Java/pig-the-dice-game-1.java
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import java.util.*;
|
||||
|
||||
public class PigDice {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int maxScore = 100;
|
||||
final int playerCount = 2;
|
||||
final String[] yesses = {"y", "Y", ""};
|
||||
|
||||
int[] safeScore = new int[2];
|
||||
int player = 0, score = 0;
|
||||
|
||||
Scanner sc = new Scanner(System.in);
|
||||
Random rnd = new Random();
|
||||
|
||||
while (true) {
|
||||
System.out.printf(" Player %d: (%d, %d) Rolling? (y/n) ", player,
|
||||
safeScore[player], score);
|
||||
if (safeScore[player] + score < maxScore
|
||||
&& Arrays.asList(yesses).contains(sc.nextLine())) {
|
||||
final int rolled = rnd.nextInt(6) + 1;
|
||||
System.out.printf(" Rolled %d\n", rolled);
|
||||
if (rolled == 1) {
|
||||
System.out.printf(" Bust! You lose %d but keep %d\n\n",
|
||||
score, safeScore[player]);
|
||||
} else {
|
||||
score += rolled;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
safeScore[player] += score;
|
||||
if (safeScore[player] >= maxScore)
|
||||
break;
|
||||
System.out.printf(" Sticking with %d\n\n", safeScore[player]);
|
||||
}
|
||||
score = 0;
|
||||
player = (player + 1) % playerCount;
|
||||
}
|
||||
System.out.printf("\n\nPlayer %d wins with a score of %d",
|
||||
player, safeScore[player]);
|
||||
}
|
||||
}
|
||||
67
Task/Pig-the-dice-game/Java/pig-the-dice-game-2.java
Normal file
67
Task/Pig-the-dice-game/Java/pig-the-dice-game-2.java
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.Scanner;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public interface PigDice {
|
||||
public static void main(String... arguments) {
|
||||
final int maxScore = 100;
|
||||
final int playerCount = 2;
|
||||
final String[] yesses = {"y", "Y", ""};
|
||||
|
||||
final Scanner scanner = new Scanner(System.in);
|
||||
final Random random = new Random();
|
||||
|
||||
final int[] safeScore = new int[2];
|
||||
final int[] score = new int[2];
|
||||
|
||||
IntStream.iterate(0, player -> (player + 1) % playerCount)
|
||||
.map(player -> {
|
||||
boolean isRolling = true;
|
||||
while (isRolling) {
|
||||
System.out.printf(
|
||||
"Player %d: (%d, %d) Rolling? (y/n) ",
|
||||
player,
|
||||
safeScore[player],
|
||||
score[player]
|
||||
);
|
||||
isRolling =
|
||||
safeScore[player] + score[player] < maxScore
|
||||
&& Arrays.asList(yesses).contains(scanner.nextLine())
|
||||
;
|
||||
if (isRolling) {
|
||||
final int rolled = random.nextInt(6) + 1;
|
||||
System.out.printf("Rolled %d\n", rolled);
|
||||
if (rolled == 1) {
|
||||
System.out.printf(
|
||||
"Bust! You lose %d but keep %d\n\n",
|
||||
score[player],
|
||||
safeScore[player]
|
||||
);
|
||||
return -1;
|
||||
} else {
|
||||
score[player] += rolled;
|
||||
}
|
||||
} else {
|
||||
safeScore[player] += score[player];
|
||||
if (safeScore[player] >= maxScore) {
|
||||
return player;
|
||||
}
|
||||
System.out.printf("Sticking with %d\n\n", safeScore[player]);
|
||||
}
|
||||
}
|
||||
score[player] = 0;
|
||||
return -1;
|
||||
})
|
||||
.filter(player -> player > -1)
|
||||
.findFirst()
|
||||
.ifPresent(player ->
|
||||
System.out.printf(
|
||||
"\n\nPlayer %d wins with a score of %d",
|
||||
player,
|
||||
safeScore[player]
|
||||
)
|
||||
)
|
||||
;
|
||||
}
|
||||
}
|
||||
43
Task/Pig-the-dice-game/JavaScript/pig-the-dice-game.js
Normal file
43
Task/Pig-the-dice-game/JavaScript/pig-the-dice-game.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
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}).
|
||||
`);
|
||||
}
|
||||
57
Task/Pig-the-dice-game/Julia/pig-the-dice-game.julia
Normal file
57
Task/Pig-the-dice-game/Julia/pig-the-dice-game.julia
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
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")])
|
||||
45
Task/Pig-the-dice-game/Kotlin/pig-the-dice-game.kotlin
Normal file
45
Task/Pig-the-dice-game/Kotlin/pig-the-dice-game.kotlin
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
34
Task/Pig-the-dice-game/Lua/pig-the-dice-game.lua
Normal file
34
Task/Pig-the-dice-game/Lua/pig-the-dice-game.lua
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
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
|
||||
45
Task/Pig-the-dice-game/Maple/pig-the-dice-game.maple
Normal file
45
Task/Pig-the-dice-game/Maple/pig-the-dice-game.maple
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
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();
|
||||
18
Task/Pig-the-dice-game/Mathematica/pig-the-dice-game.math
Normal file
18
Task/Pig-the-dice-game/Mathematica/pig-the-dice-game.math
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
DynamicModule[{score, players = {1, 2}, roundscore = 0,
|
||||
roll}, (score@# = 0) & /@ players;
|
||||
Panel@Dynamic@
|
||||
Column@{Grid[
|
||||
Prepend[{#, score@#} & /@ players, {"Player", "Score"}],
|
||||
Background -> {None, 2 -> Gray}], roundscore,
|
||||
If[ValueQ@roll, Row@{"Rolled ", roll}, ""],
|
||||
If[IntegerQ@roundscore,
|
||||
Row@{Button["Roll", roll = RandomInteger[{1, 6}];
|
||||
If[roll == 1, roundscore = 0; players = RotateLeft@players,
|
||||
roundscore += roll]],
|
||||
Button["Hold", score[players[[1]]] += roundscore;
|
||||
roundscore = 0;
|
||||
If[score[players[[1]]] >= 100, roll =.;
|
||||
roundscore = Row@{players[[1]], " wins."},
|
||||
players = RotateLeft@players]]},
|
||||
Button["Play again.",
|
||||
roundscore = 0; (score@# = 0) & /@ players]]}]
|
||||
44
Task/Pig-the-dice-game/MiniScript/pig-the-dice-game.mini
Normal file
44
Task/Pig-the-dice-game/MiniScript/pig-the-dice-game.mini
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// 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
|
||||
49
Task/Pig-the-dice-game/Nim/pig-the-dice-game.nim
Normal file
49
Task/Pig-the-dice-game/Nim/pig-the-dice-game.nim
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
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"
|
||||
52
Task/Pig-the-dice-game/OCaml/pig-the-dice-game.ocaml
Normal file
52
Task/Pig-the-dice-game/OCaml/pig-the-dice-game.ocaml
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
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;;
|
||||
39
Task/Pig-the-dice-game/Objeck/pig-the-dice-game.objeck
Normal file
39
Task/Pig-the-dice-game/Objeck/pig-the-dice-game.objeck
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
class Pig {
|
||||
function : Main(args : String[]) ~ Nil {
|
||||
player_count := 2;
|
||||
max_score := 100;
|
||||
safe_score := Int->New[player_count];
|
||||
player := 0; score := 0;
|
||||
|
||||
while(true) {
|
||||
safe := safe_score[player];
|
||||
" Player {$player}: ({$safe}, {$score}) Rolling? (y/n) "->PrintLine();
|
||||
rolling := IO.Console->ReadString();
|
||||
if(safe_score[player] + score < max_score & (rolling->Equals("y") | rolling->Equals("yes"))) {
|
||||
rolled := ((Float->Random() * 100.0)->As(Int) % 6) + 1;
|
||||
" Rolled {$rolled}"->PrintLine();
|
||||
if(rolled = 1) {
|
||||
safe := safe_score[player];
|
||||
" Bust! you lose {$score} but still keep your previous {$safe}\n"->PrintLine();
|
||||
score := 0;
|
||||
player := (player + 1) % player_count;
|
||||
}
|
||||
else {
|
||||
score += rolled;
|
||||
};
|
||||
}
|
||||
else {
|
||||
safe_score[player] += score;
|
||||
if(safe_score[player] >= max_score) {
|
||||
break;
|
||||
};
|
||||
safe := safe_score[player];
|
||||
" Sticking with {$safe}\n"->PrintLine();
|
||||
score := 0;
|
||||
player := (player + 1) % player_count;
|
||||
};
|
||||
};
|
||||
safe := safe_score[player];
|
||||
"\n\nPlayer {$player} wins with a score of {$safe}"->PrintLine();
|
||||
}
|
||||
}
|
||||
32
Task/Pig-the-dice-game/PHP/pig-the-dice-game.php
Normal file
32
Task/Pig-the-dice-game/PHP/pig-the-dice-game.php
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));
|
||||
|
||||
define('MAXSCORE', 100);
|
||||
define('PLAYERCOUNT', 2);
|
||||
|
||||
$confirm = array('Y', 'y', '');
|
||||
|
||||
while (true) {
|
||||
printf(' Player %d: (%d, %d) Rolling? (Yn) ', $player,
|
||||
$safeScore[$player], $score);
|
||||
if ($safeScore[$player] + $score < MAXSCORE &&
|
||||
in_array(trim(fgets(STDIN)), $confirm)) {
|
||||
$rolled = rand(1, 6);
|
||||
echo " Rolled $rolled \n";
|
||||
if ($rolled == 1) {
|
||||
printf(' Bust! You lose %d but keep %d \n\n',
|
||||
$score, $safeScore[$player]);
|
||||
} else {
|
||||
$score += $rolled;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
$safeScore[$player] += $score;
|
||||
if ($safeScore[$player] >= MAXSCORE)
|
||||
break;
|
||||
echo ' Sticking with ', $safeScore[$player], '\n\n';
|
||||
}
|
||||
$score = 0;
|
||||
$player = ($player + 1) % PLAYERCOUNT;
|
||||
}
|
||||
printf('\n\nPlayer %d wins with a score of %d ',
|
||||
$player, $safeScore[$player]);
|
||||
109
Task/Pig-the-dice-game/Pascal/pig-the-dice-game.pas
Normal file
109
Task/Pig-the-dice-game/Pascal/pig-the-dice-game.pas
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
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.
|
||||
40
Task/Pig-the-dice-game/Perl/pig-the-dice-game.pl
Normal file
40
Task/Pig-the-dice-game/Perl/pig-the-dice-game.pl
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
#!perl
|
||||
use strict;
|
||||
use warnings;
|
||||
my @players = @ARGV;
|
||||
@players = qw(Joe Mike);
|
||||
my @scores = (0) x @players;
|
||||
while( 1 ) {
|
||||
PLAYER: for my $i ( 0 .. $#players ) {
|
||||
my $name = $players[$i];
|
||||
my $score = $scores[$i];
|
||||
my $roundscore = 1 + int rand 6;
|
||||
print "$name, your score so far is $score.\n";
|
||||
print "You rolled a $roundscore.\n";
|
||||
next PLAYER if $roundscore == 1;
|
||||
while($score + $roundscore < 100) {
|
||||
print "Roll again, or hold [r/h]: ";
|
||||
my $answer = <>;
|
||||
$answer = 'h' unless defined $answer;
|
||||
if( $answer =~ /^h/i ) {
|
||||
$score += $roundscore;
|
||||
$scores[$i] = $score;
|
||||
print "Your score is now $score.\n";
|
||||
next PLAYER;
|
||||
} elsif( $answer =~ /^r/ ) {
|
||||
my $die = 1 + int rand 6;
|
||||
print "$name, you rolled a $die.\n";
|
||||
next PLAYER if $die == 1;
|
||||
$roundscore += $die;
|
||||
print "Your score for the round is now $roundscore.\n";
|
||||
} else {
|
||||
print "I did not understand that.\n";
|
||||
}
|
||||
}
|
||||
$score += $roundscore;
|
||||
print "With that, your score became $score.\n";
|
||||
print "You won!\n";
|
||||
exit;
|
||||
}
|
||||
}
|
||||
__END__
|
||||
28
Task/Pig-the-dice-game/Phix/pig-the-dice-game.phix
Normal file
28
Task/Pig-the-dice-game/Phix/pig-the-dice-game.phix
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
constant numPlayers = 2,
|
||||
maxScore = 100
|
||||
sequence scores = repeat(0,numPlayers)
|
||||
printf(1,"\nPig The Dice Game\n\n")
|
||||
integer points = 0, -- points accumulated in current turn, 0=swap turn
|
||||
player = 1 -- start with first player
|
||||
while true do
|
||||
integer roll = rand(6)
|
||||
printf(1,"Player %d, your score is %d, you rolled %d. ",{player,scores[player],roll})
|
||||
if roll=1 then
|
||||
printf(1," Too bad. :(\n")
|
||||
points = 0 -- swap turn
|
||||
else
|
||||
points += roll
|
||||
if scores[player]+points>=maxScore then exit end if
|
||||
printf(1,"Round score %d. Roll or Hold?",{points})
|
||||
integer reply = upper(wait_key())
|
||||
printf(1,"%c\n",{reply})
|
||||
if reply == 'H' then
|
||||
scores[player] += points
|
||||
points = 0 -- swap turn
|
||||
end if
|
||||
end if
|
||||
if points=0 then
|
||||
player = mod(player,numPlayers) + 1
|
||||
end if
|
||||
end while
|
||||
printf(1,"\nPlayer %d wins with a score of %d!\n",{player,scores[player]+points})
|
||||
37
Task/Pig-the-dice-game/Python/pig-the-dice-game.py
Normal file
37
Task/Pig-the-dice-game/Python/pig-the-dice-game.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/python3
|
||||
|
||||
'''
|
||||
See: http://en.wikipedia.org/wiki/Pig_(dice)
|
||||
|
||||
This program scores and throws the dice for a two player game of Pig
|
||||
|
||||
'''
|
||||
|
||||
from random import randint
|
||||
|
||||
playercount = 2
|
||||
maxscore = 100
|
||||
safescore = [0] * playercount
|
||||
player = 0
|
||||
score=0
|
||||
|
||||
while max(safescore) < maxscore:
|
||||
rolling = input("Player %i: (%i, %i) Rolling? (Y) "
|
||||
% (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
|
||||
if rolling:
|
||||
rolled = randint(1, 6)
|
||||
print(' Rolled %i' % rolled)
|
||||
if rolled == 1:
|
||||
print(' Bust! you lose %i but still keep your previous %i'
|
||||
% (score, safescore[player]))
|
||||
score, player = 0, (player + 1) % playercount
|
||||
else:
|
||||
score += rolled
|
||||
else:
|
||||
safescore[player] += score
|
||||
if safescore[player] >= maxscore:
|
||||
break
|
||||
print(' Sticking with %i' % safescore[player])
|
||||
score, player = 0, (player + 1) % playercount
|
||||
|
||||
print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))
|
||||
39
Task/Pig-the-dice-game/Quackery/pig-the-dice-game.quackery
Normal file
39
Task/Pig-the-dice-game/Quackery/pig-the-dice-game.quackery
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
[ 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 ( --> )
|
||||
100
Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx
Normal file
100
Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
/*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*/
|
||||
/*names with blanks should use an _ */
|
||||
if _\=='' then call err 'too many arguments were specified: ' _
|
||||
@nhp = 'number of human players' ; hp = scrutinize( hp, @nhp , 0, 0, 0)
|
||||
@ncp = 'number of computer players' ; cp = scrutinize( cp, @ncp , 0, 0, 2)
|
||||
@sn2w = 'score needed to win' ; win= scrutinize(win, @sn2w, 1, 1e6, 60)
|
||||
@nsid = 'number of sides in die' ; die= scrutinize(die, @nsid, 2, 999, 6)
|
||||
if hp==0 & cp==0 then cp= 2 /*if both counts are zero, two HALs. */
|
||||
if hp==1 & cp==0 then cp= 1 /*if one human, then use one HAL. */
|
||||
name.= /*nullify all names (to a blank). */
|
||||
L= 0 /*maximum length of a player name. */
|
||||
do i=1 for hp+cp /*get the player's names, ... maybe. */
|
||||
if i>hp then @= '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) ) /*use L for nice name formatting. */
|
||||
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:' /*the introduction to pig-the-dice-game*/
|
||||
|
||||
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 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 copies('─', sw) /*display a fence for da ole eyeballs. */
|
||||
it= name.j
|
||||
say it', your total score (so far) in this pig game is: ' s.j"."
|
||||
|
||||
do until stopped /*keep prompting/rolling 'til stopped. */
|
||||
r= random(1, die) /*get a random die face (number). */
|
||||
!= left(space(r !.r','), !w) /*for color, use a die─face name. */
|
||||
in.j= in.j + r /*add die─face number to the inning. */
|
||||
|
||||
if r==1 then do; say it @jra ! || @ati "is a bust."; leave; end
|
||||
say it @jra ! || @ati "total is: " 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 /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
score: say; say copies('█', sw) /*display a fence for da ole eyeballs. */
|
||||
|
||||
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); return /*display a fence for da ole eyeballs. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
scrutinize: parse arg ?,what,min,max /*? is the number, ... or maybe not. */
|
||||
if ?=='' | ?==',' then return arg(5)
|
||||
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
|
||||
28
Task/Pig-the-dice-game/Racket/pig-the-dice-game.rkt
Normal file
28
Task/Pig-the-dice-game/Racket/pig-the-dice-game.rkt
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#lang racket
|
||||
|
||||
(define (pig-the-dice #:print? [print? #t] . players)
|
||||
(define prn (if print? (λ xs (apply printf xs) (flush-output)) void))
|
||||
(define names (for/list ([p players] [n (in-naturals 1)]) n))
|
||||
(define points (for/list ([p players]) (box 0)))
|
||||
(with-handlers ([(negate exn?) identity])
|
||||
(for ([nm (in-cycle names)] [tp (in-cycle points)] [pl (in-cycle players)])
|
||||
(prn (string-join (for/list ([n names] [p points])
|
||||
(format "Player ~a, ~a points" n (unbox p)))
|
||||
"; " #:before-first "Status: " #:after-last ".\n"))
|
||||
(let turn ([p 0] [n 0])
|
||||
(prn "Player ~a, round #~a, [R]oll or [P]ass? " nm (+ 1 n))
|
||||
(define roll? (pl (unbox tp) p n))
|
||||
(unless (eq? pl human) (prn "~a\n" (if roll? 'R 'P)))
|
||||
(if (not roll?) (set-box! tp (+ (unbox tp) p))
|
||||
(let ([r (+ 1 (random 6))])
|
||||
(prn " Dice roll: ~s => " r)
|
||||
(if (= r 1) (prn "turn lost\n")
|
||||
(let ([p (+ p r)]) (prn "~a points\n" p) (turn p (+ 1 n)))))))
|
||||
(prn "--------------------\n")
|
||||
(when (<= 100 (unbox tp)) (prn "Player ~a wins!\n" nm) (raise nm)))))
|
||||
|
||||
(define (human total-points turn-points round#)
|
||||
(case (string->symbol (car (regexp-match #px"[A-Za-z]?" (read-line))))
|
||||
[(R r) #t] [(P p) #f] [else (human total-points turn-points round#)]))
|
||||
|
||||
(pig-the-dice #:print? #t human human)
|
||||
32
Task/Pig-the-dice-game/Raku/pig-the-dice-game.raku
Normal file
32
Task/Pig-the-dice-game/Raku/pig-the-dice-game.raku
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
28
Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring
Normal file
28
Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# 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]
|
||||
43
Task/Pig-the-dice-game/Ruby/pig-the-dice-game.rb
Normal file
43
Task/Pig-the-dice-game/Ruby/pig-the-dice-game.rb
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
class PigGame
|
||||
Player = Struct.new(:name, :safescore, :score) do
|
||||
def bust!() self.score = safescore end
|
||||
def stay!() self.safescore = score end
|
||||
def to_s() "#{name} (#{safescore}, #{score})" end
|
||||
end
|
||||
|
||||
def initialize(names, maxscore=100, die_sides=6)
|
||||
rotation = names.map {|name| Player.new(name,0,0) }
|
||||
|
||||
rotation.cycle do |player|
|
||||
loop do
|
||||
if wants_to_roll?(player)
|
||||
puts "Rolled: #{roll=roll_dice(die_sides)}"
|
||||
if bust?(roll)
|
||||
puts "Busted!",''
|
||||
player.bust!
|
||||
break
|
||||
else
|
||||
player.score += roll
|
||||
if player.score >= maxscore
|
||||
puts player.name + " wins!"
|
||||
return
|
||||
end
|
||||
end
|
||||
else
|
||||
player.stay!
|
||||
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
|
||||
|
||||
PigGame.new( %w|Samuel Elizabeth| )
|
||||
26
Task/Pig-the-dice-game/Run-BASIC/pig-the-dice-game.basic
Normal file
26
Task/Pig-the-dice-game/Run-BASIC/pig-the-dice-game.basic
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
numPlayers = 2
|
||||
maxScore = 100
|
||||
dim safeScore(numPlayers)
|
||||
|
||||
[loop]
|
||||
for player = 1 to numPlayers
|
||||
score = 0
|
||||
|
||||
while safeScore(player) < maxScore
|
||||
input "Player ";player;" Rolling? (Y) ";rolling$
|
||||
if upper$(rolling$) = "Y" then
|
||||
rolled = int(rnd(0) * 5) + 1
|
||||
print "Player ";player;" rolled ";rolled
|
||||
if rolled = 1 then
|
||||
print "Bust! you lose player ";player;" but still keep your previous score of ";safeScore(plater)
|
||||
exit while
|
||||
end if
|
||||
score = score + rolled
|
||||
else
|
||||
safeScore(player) = safeScore(player) + score
|
||||
end if
|
||||
wend
|
||||
next player
|
||||
goto [loop]
|
||||
[winner]
|
||||
print "Player ";plater;" wins with a score of ";safeScore(player)
|
||||
131
Task/Pig-the-dice-game/Rust/pig-the-dice-game.rust
Normal file
131
Task/Pig-the-dice-game/Rust/pig-the-dice-game.rust
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
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
|
||||
}
|
||||
}
|
||||
45
Task/Pig-the-dice-game/Scala/pig-the-dice-game.scala
Normal file
45
Task/Pig-the-dice-game/Scala/pig-the-dice-game.scala
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
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))
|
||||
}
|
||||
79
Task/Pig-the-dice-game/Tcl/pig-the-dice-game-1.tcl
Normal file
79
Task/Pig-the-dice-game/Tcl/pig-the-dice-game-1.tcl
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
package require TclOO
|
||||
|
||||
oo::class create Player {
|
||||
variable me
|
||||
constructor {name} {
|
||||
set me $name
|
||||
}
|
||||
method name {} {
|
||||
return $me
|
||||
}
|
||||
|
||||
method wantToRoll {safeScore roundScore} {}
|
||||
method stuck {score} {}
|
||||
method busted {score} {}
|
||||
method won {score} {}
|
||||
|
||||
method rolled {who what} {
|
||||
if {$who ne [self]} {
|
||||
#puts "[$who name] rolled a $what"
|
||||
}
|
||||
}
|
||||
method turnend {who score} {
|
||||
if {$who ne [self]} {
|
||||
puts "End of turn for [$who name] on $score"
|
||||
}
|
||||
}
|
||||
method winner {who score} {
|
||||
if {$who ne [self]} {
|
||||
puts "[$who name] is a winner, on $score"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proc rollDie {} {
|
||||
expr {1+int(rand() * 6)}
|
||||
}
|
||||
proc rotateList {var} {
|
||||
upvar 1 $var l
|
||||
set l [list {*}[lrange $l 1 end] [lindex $l 0]]
|
||||
}
|
||||
proc broadcast {players message score} {
|
||||
set p0 [lindex $players 0]
|
||||
foreach p $players {
|
||||
$p $message $p0 $score
|
||||
}
|
||||
}
|
||||
|
||||
proc pig {args} {
|
||||
set players $args
|
||||
set scores [lrepeat [llength $args] 0]
|
||||
while 1 {
|
||||
set player [lindex $players 0]
|
||||
set safe [lindex $scores 0]
|
||||
set s 0
|
||||
while 1 {
|
||||
if {$safe + $s >= 100} {
|
||||
incr safe $s
|
||||
$player won $safe
|
||||
broadcast $players winner $safe
|
||||
return $player
|
||||
}
|
||||
if {![$player wantToRoll $safe $s]} {
|
||||
lset scores 0 [incr safe $s]
|
||||
$player stuck $safe
|
||||
break
|
||||
}
|
||||
set roll [rollDie]
|
||||
broadcast $players rolled $roll
|
||||
if {$roll == 1} {
|
||||
$player busted $safe
|
||||
break
|
||||
}
|
||||
incr s $roll
|
||||
}
|
||||
broadcast $players turnend $safe
|
||||
rotateList players
|
||||
rotateList scores
|
||||
}
|
||||
}
|
||||
32
Task/Pig-the-dice-game/Tcl/pig-the-dice-game-2.tcl
Normal file
32
Task/Pig-the-dice-game/Tcl/pig-the-dice-game-2.tcl
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
oo::class create HumanPlayer {
|
||||
variable me
|
||||
superclass Player
|
||||
method wantToRoll {safeScore roundScore} {
|
||||
while 1 {
|
||||
puts -nonewline "$me (on $safeScore+$roundScore) do you want to roll? (Y/n)"
|
||||
flush stdout
|
||||
if {[gets stdin line] < 0} {
|
||||
# EOF detected
|
||||
puts ""
|
||||
exit
|
||||
}
|
||||
if {$line eq "" || $line eq "y" || $line eq "Y"} {
|
||||
return 1
|
||||
}
|
||||
if {$line eq "n" || $line eq "N"} {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
method stuck {score} {
|
||||
puts "$me sticks with score $score"
|
||||
}
|
||||
method busted {score} {
|
||||
puts "Busted! ($me still on score $score)"
|
||||
}
|
||||
method won {score} {
|
||||
puts "$me has won! (Score: $score)"
|
||||
}
|
||||
}
|
||||
|
||||
pig [HumanPlayer new "Alex"] [HumanPlayer new "Bert"]
|
||||
50
Task/Pig-the-dice-game/V-(Vlang)/pig-the-dice-game.v
Normal file
50
Task/Pig-the-dice-game/V-(Vlang)/pig-the-dice-game.v
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
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!!!", )
|
||||
}
|
||||
50
Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba
Normal file
50
Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
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
|
||||
40
Task/Pig-the-dice-game/Wren/pig-the-dice-game.wren
Normal file
40
Task/Pig-the-dice-game/Wren/pig-the-dice-game.wren
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
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)")
|
||||
}
|
||||
}
|
||||
25
Task/Pig-the-dice-game/XPL0/pig-the-dice-game.xpl0
Normal file
25
Task/Pig-the-dice-game/XPL0/pig-the-dice-game.xpl0
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
include c:\cxpl\codes; \intrinsic 'code' declarations
|
||||
integer Player, Die, Points, Score(2);
|
||||
[Score(0):= 0; Score(1):= 0; \starting scores for each player
|
||||
Player:= 1; \second player
|
||||
repeat Player:= if Player = 1 then 0 else 1; \next player
|
||||
Points:= 0; \points for current turn
|
||||
loop [Text(0, "Player "); IntOut(0, Player+1);
|
||||
Text(0, " is up. Roll or hold (r/h)? ");
|
||||
OpenI(0); \discard any chars in keyboard buffer (like CR)
|
||||
if ChIn(0) = ^h then quit \default is 'r' to roll
|
||||
else [Die:= Ran(6)+1; \roll the die
|
||||
Text(0, "You get "); IntOut(0, Die); CrLf(0);
|
||||
if Die = 1 then [Points:= 0; quit];
|
||||
Points:= Points + Die; \add up points for turn
|
||||
Text(0, "Total points are "); IntOut(0, Points);
|
||||
Text(0, " for a tentative score of ");
|
||||
IntOut(0, Score(Player)+Points); CrLf(0);
|
||||
];
|
||||
];
|
||||
Score(Player):= Score(Player) + Points; \show scores
|
||||
Text(0, "Player 1 has "); IntOut(0, Score(0));
|
||||
Text(0, " and player 2 has "); IntOut(0, Score(1)); CrLf(0);
|
||||
until Score(Player) >= 100;
|
||||
Text(0, "Player "); IntOut(0, Player+1); Text(0, " WINS!!!");
|
||||
]
|
||||
24
Task/Pig-the-dice-game/Zkl/pig-the-dice-game.zkl
Normal file
24
Task/Pig-the-dice-game/Zkl/pig-the-dice-game.zkl
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
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]));
|
||||
Loading…
Add table
Add a link
Reference in a new issue