Saturday, 7 July 2012

Bulls and Cows


Бикове и крави  е логическа игра за отгатване на цифри. Играе се от двама противника (в случая единият е компютър), като всеки се стреми да отгатне тайното число, намислено от другия. След всеки ход, противникът дава броя на съвпаденията.
Играта протича по следния начин. Записва се тайно число. Тайните числа са четирицифрени. След това се задава въпрос дали дадено четирицифрено число е тайното число. Противникът отговаря, като посочва броя на съвпаденията -- ако дадена цифра от предположението се съдържа в тайното число и се намира на точното място, тя е „бик“, ако пък е на различно място, е „крава“.
Пример:
Тайно число: 4271
Предположение: 1234
Отговор: „1 бик и 2 крави“. (Бикът е „2“, а кравите са „4“ и „1“.)
На всеки ход играчите записват предположените числа и отговорите, за да могат чрез дедукция да идентифицират цифрите в тайното число на противника.
Когато се открие тайното число, играта приключва.
В кода представен по-долу играта се играе по следния начин:
  • Пишат се 4 цифри и конзолата връща броя на биковете и кравите;
  • Когато се напише top излиза списъка с резултатите на игрите изиграни досега;
  • Когато се напише help конзолата връща тайното число;
  • Когато се напише restart играта започва отначало и сменя тайното число с ново;
  • Когато се напише exit играта приключва;
  • След като се познае числото, играта иска име и показва резултатите, заедно с броя пробвания за познаване;
using System;
using System.Linq;
using System.Collections.Generic;
public class BullsAndCows
{
private static string secret;
private static int attempts = 0;
private static int count = 0;
private static Dictionary<int, string> scores = new Dictionary<int, string>();
static void Main()
{
PlayGame();
}
private static void PlayGame()
{
Console.WriteLine("Welcome to “Bulls and Cows” game. Please try to guess my secret 4-digit number.Use 'top' to view the top scoreboard, 'restart' to start a new game and 'help' to cheat and 'exit' to quit the game.");
bool finished = false;
secret = GenerateSecret();
while (finished == false)
{
attempts++;
Console.Write("Enter your guess or command: ");
string input = ReadNumber();
Console.Write(Respond(input, ref finished));
Console.WriteLine();
}
Console.WriteLine("Congratulations! You guessed the secret number in {0} attempts.", attempts);
Console.Write("Please enter your name for the top scoreboard: ");
count++;
string name = count+". "+Console.ReadLine() + " ----> " + attempts + " attempts";
Dictionary<int, string> results = Result(attempts, name);
attempts = 0;
PlayGame();
}
private static Dictionary<int, string> Result(int attempts, string name)
{
scores.Add(attempts, name);
scores.OrderByDescending(key => key.Value);
foreach (var pair in scores)
{
Console.WriteLine(pair.Value);
}
return scores;
}
private static Dictionary<int, string> Top()
{
if (scores.Count == 0)
{
Console.WriteLine("Top scoreboard is empty.");
}
else
{
foreach (var pair in scores)
{
Console.WriteLine(pair.Value);
}
}
return scores;
}
private static string GenerateSecret()
{
string result = string.Empty;
Random generator = new Random();
for (int i = 0; i < 4; i++)
{
result+=(generator.Next(0, 10));
}
result = "7725";
return result;
}
private static string Respond(string input, ref bool finished)
{
int bulls = GetBulls(input);
int cows = GetCows(input);
cows = cows - bulls;
if (cows<0)
{
cows = 0;
}
if (bulls == input.Length)
{
finished = true;
}
else
{
return string.Format("Wrong number! Bulls: {0}, Cows: {1}", bulls, cows);
}
return string.Empty;
}
private static int GetCows(string input)
{
return input.Intersect(secret).Count();
}
private static int GetBulls(string input)
{
int bulls = 0;
for (int i = 0; i < input.Length; i++)
{
if (secret[i] == input[i])
{
bulls++;
}
}
return bulls;
}
private static string ReadNumber()
{
string input;
while (true)
{
input = Console.ReadLine();
if (input=="restart")
{
PlayGame();
}
else if (input == "help")
{
Console.WriteLine(secret);
continue;
}
else if (input=="exit")
{
Console.WriteLine("Good bye!");
Environment.Exit(0);
continue;
}
else if (input == "top")
{
Dictionary<int, string> top = Top();
continue;
}
else
{
if (input.Length != 4)
{
Console.WriteLine("Incorrect guess or command!");
continue;
}
if (!input.All((char x) => char.IsDigit(x)))
{
Console.WriteLine("Incorrect guess or command!");
continue;
}
}
HashSet<char> digits = new HashSet<char>(input);
return input;
}
}
}
view raw BullsAndCows hosted with ❤ by GitHub

No comments:

Post a Comment