Dice throwing game variable players and throws

TrustyTony 0 Tallied Votes 828 Views Share

I wrote this as reaction for Pascal newbie's question in Pascal Delphi forum.

import random

# get Python 2 to use Python 3 style input
try:
    input = raw_input
except:
    pass

def number_of_things(thing='turns'):
    while True:
        try:
            return int(input('Give number of %s decided: ' % thing))
        except ValueError:
            print('Please enter integer value')
        
def throws(times=1, players=2):
    return [[random.randint(1,6) for count in range(times)] for playercount in range(players)]

def show_n_players(number_of_players=2):
    game = throws(number_of_things(), number_of_players)
    for number, got in enumerate(game, 1):
        print('Player %i: throws: %s, sum %i' % (number, got, sum(got)))
    print('')
    print(('Winner was player %i' %
           max((sum(got), no)
               for no, got in enumerate(game, 1))[1]).center(
                   60, '*'))

show_n_players(number_of_things('players'))

Dani AI

Generated

Nice, compact demo by . For readers coming from the Delphi/Pascal side, here is a concise console equivalent with a few practical improvements: validated integer input, a single seed call, dynamic arrays for arbitrary player/throw counts, and explicit tie detection so the code does not silently favour any particular player when scores match.

program DiceGame;

{$APPTYPE CONSOLE}

uses
  SysUtils;

function ReadInt(const Prompt: string): Integer;
var
  s: string;
begin
  repeat
    Write(Prompt);
    ReadLn(s);
    if TryStrToInt(Trim(s), Result) then Exit;
    Writeln('Please enter an integer value.');
  until False;
end;

var
  Players, Throws, i, j, MaxSum, CountWinners, k: Integer;
  Rolls: array of array of Integer;
  Sums: array of Integer;
  WinnerList: array of Integer;
begin
  Randomize;
  Players := ReadInt('Number of players: ');
  Throws := ReadInt('Number of throws per player: ');

  if (Players < 1) or (Throws < 1) then
  begin
    Writeln('Players and throws must be >= 1.');
    Exit;
  end;

  SetLength(Rolls, Players);
  SetLength(Sums, Players);

  for i := 0 to Players - 1 do
  begin
    SetLength(Rolls[i], Throws);
    Sums[i] := 0;
    for j := 0 to Throws - 1 do
    begin
      Rolls[i][j] := Random(6) + 1;
      Inc(Sums[i], Rolls[i][j]);
    end;
  end;

  for i := 0 to Players - 1 do
  begin
    Write('Player ', i+1, ': throws: ');
    for j := 0 to Throws - 1 do
      Write(Rolls[i][j], ' ');
    Writeln(', sum ', Sums[i]);
  end;

  MaxSum := -1;
  for i := 0 to Players - 1 do
    if Sums[i] > MaxSum then MaxSum := Sums[i];

  CountWinners := 0;
  for i := 0 to Players - 1 do
    if Sums[i] = MaxSum then Inc(CountWinners);

  SetLength(WinnerList, CountWinners);
  k := 0;
  for i := 0 to Players - 1 do
    if Sums[i] = MaxSum then
    begin
      WinnerList[k] := i + 1;
      Inc(k);
    end;

  Writeln;
  if CountWinners = 1 then
    Writeln('Winner is player ', WinnerList[0])
  else
  begin
    Write('Tie between players: ');
    for i := 0 to CountWinners - 1 do
    begin
      if i > 0 then Write(', ');
      Write(WinnerList[i]);
    end;
    Writeln;
  end;

  ReadLn;
end.

Notes: call Randomize once at startup (or set RandSeed explicitly for reproducible tests). Use Random(6)+1 to get 1..6. Watch indexing (Delphi dynamic arrays are 0-based) and check inputs for <1. For GUI or threaded apps keep the game logic separate from UI and avoid the global RNG in concurrent code (use a per-thread generator if needed). This approach preserves clarity and handles ties explicitly rather than choosing a single index by accident.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.