DEV Community

Discussion on: Daily Challenge #41 - Greed is Good

Collapse
 
jacksoncds profile image
Jackson DaSilva

C#

Repl.it

using System;
using System.Linq;
using System.Threading;

class MainClass {
  public static void Main (string[] args) {
    try {
        var greed = new Greed();
        greed.Throw();

        while (true) {
          Thread.Sleep(5);
          greed.Throw();
        }
    } catch(Exception) {
      Console.WriteLine("\nYou win!, game over.");
    }
  }
}

class Greed {

  public int Score = 0;
  public int Throws = 0;

  public double GetAveragePerThrow(){
    if(this.Throws == 0){
      return 0;
    }

    return this.Score / this.Throws;
  }

  public int Roll(Random random){
    var rolled = random.Next(1, 7);

    Console.Write(rolled);

    return rolled;
  }

  public int GetScore(int[] rolls){
    var score = 0;

    var one = rolls.Count(c => c == 1);
    var two = rolls.Count(c => c == 2);
    var three = rolls.Count(c => c == 3);
    var four = rolls.Count(c => c == 4);
    var five = rolls.Count(c => c == 5);
    var six = rolls.Count(c => c == 6);

    if(one == 1){
      score += 100;
    }

    if(one == 3){
      score += 1000;
    }

    if(two == 3){
      score += 200;
    }

    if(three == 3){
      score += 300;
    }

    if(four == 3){
      score += 400;
    }

    if(five == 1){
      score += 50;
    }

    if(five == 3){
      score += 500;
    }

    if(six == 3){
      score += 600;
    }

    if(one == 5){
      throw new Exception("You win."); 
    }

    return score;
  }

  public int[] Throw(){
    var rollsPerThrow = 5;
    var rolls = new int[rollsPerThrow];
    var random = new Random();

    Console.WriteLine("Rolls:");
    for(var i = 0; i < rollsPerThrow; i++){
      rolls[i] = this.Roll(random);
    }

    var rollScore = this.GetScore(rolls);

    this.Throws++;
    this.Score += rollScore;

    Console.WriteLine($"\nScore: \n{rollScore}");
    Console.WriteLine($"Total score: {this.Score} - Throws: {this.Throws} - Average score per throw: {this.GetAveragePerThrow()}");

    return rolls;
  }
}