Skip to content

Instantly share code, notes, and snippets.

@honux77
Created February 20, 2013 01:59
Show Gist options
  • Save honux77/4992076 to your computer and use it in GitHub Desktop.
Save honux77/4992076 to your computer and use it in GitHub Desktop.
C# baseball game
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace NEXTCSharp
{
class BaseballGame
{
public int[] guess, answer;
const int Length = 3;
public BaseballGame()
{
guess = new int[Length];
answer = new int[Length];
genrateAns(answer);
}
private void genrateAns(int[] answer)
{
List<int> queue = new List<int>();
for (int i = 1; i <= 9; i++)
queue.Add(i);
MyOp.shuffle(queue);
for (int i = 0; i < answer.Length; i++)
answer[i] = queue[i];
//printData(answer);
}
private void printData(int[] arr)
{
//foreach (int i in answer.num)
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
if (i != arr.Length - 1)
Console.Write(":");
else
Console.Write("\n");
}
}
/// <summary>
/// main loop for baseball game
/// debug true if you want to display debug message
/// </summary>
private void loop(bool debug)
{
bool bdebug = debug;
Console.WriteLine("야구게임");
Console.WriteLine("=================================");
if (debug)
{
Console.Write("정답: ");
printData(answer);
Console.WriteLine("=================================");
Console.WriteLine();
}
int b, s, n_try;
s = n_try = 0;
//start main loop
while (s != 3)
{
n_try++;
b = s = 0;
Console.Write("숫자 " + Length + "개를 입력하세요[예: 2, 3, 4] ");
string str = Console.ReadLine();
string[] str_input = str.Split(',');
//convert each string to int and compare it with all answer number
for (int i = 0; i < guess.Length; i++)
{
guess[i] = Convert.ToInt16(str_input[i]);
for (int j = 0; j < answer.Length; j++)
if (guess[i] == answer[j])
if (i == j)
s++;
else
b++;
}
//display result of this try
if (s == 0 && b == 0)
Console.WriteLine("아웃!");
else if (s == 3)
Console.WriteLine("홈런!");
else
{
string tmp = "";
tmp += (s != 0) ? s + "스트라이크 " : "";
tmp += (b != 0) ? b + "볼" : "";
Console.WriteLine(tmp);
}
} //end of main while loop
Console.WriteLine(n_try + "번 만에 맞추셨어요 :D\n");
}
/// <summary>
/// main test program
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
BaseballGame b = new BaseballGame();
//b.loop(false);
b.loop(true);
}
}
static class MyOp
{
public static void shuffle<T>(this List<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
@sunghwanJo
Copy link

학생들 C#스터디를 위해 작성하신건가요?! 아니면 교수님께서 공부중인신건가요?! ㅋㅋ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment