コンソールで遊ぼう
.NET2.0ではConsoleクラスも結構強化されているみたいです。特にキーが押されているかどうかを判定できるようになったのが嬉しい。早速、ありがちなゲームをこさえてみました。(^^;
using System; class Program { const int W = 79; const int H = 24; static void SetObstacle(int[,] judge) { Random r = new Random(); for (int i = 0; i < 10; ++i) { judge[r.Next(0, W / 3), r.Next(0, H / 3)] = 2; judge[r.Next(0, W / 3), r.Next(H / 3 * 2, H)] = 2; judge[r.Next(W / 3 * 2, W), r.Next(0, H / 4)] = 2; judge[r.Next(W / 3 * 2, W), r.Next(H / 3 * 2, H)] = 2; } } static void ShowObstacle(int[,] judge) { for (int i = 0; i < judge.GetLength(0); ++i) for (int j = 0; j < judge.GetLength(1); ++j) if (judge[i, j] == 2) { Console.SetCursorPosition(i, j); Console.Write('+'); } } static void GameMain() { int x = 40; // x座標 int y = 12; // y座標 int dx = 1; // x移動 int dy = 0; // y移動 int wait = 50; // ウェイト int score = 0; // 得点 char c = '*'; // 自機 // 判定表 int[,] judge = new int[80, 25]; // 障害物の配置 SetObstacle(judge); ShowObstacle(judge); while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo keyinfo = Console.ReadKey(true); switch (keyinfo.Key) { case ConsoleKey.UpArrow: dx = 0; dy = -1; break; case ConsoleKey.DownArrow: dx = 0; dy = 1; break; case ConsoleKey.LeftArrow: dx = -1; dy = 0; break; case ConsoleKey.RightArrow: dx = 1; dy = 0; break; default: break; } } x += dx; y += dy; // 画面枠、障害物または自分にぶつかったらゲームオーバー if (x < 0 || x > 79 || y < 1 || y > 24 || judge[x, y] != 0) { Console.Write(" Game Over!"); break; } judge[x, y] = 1; Console.SetCursorPosition(x, y); Console.Write(c); // 得点の1/10msずつ速くなる int t = wait - score / 10; if (t < 10) t = 10; System.Threading.Thread.Sleep(t * (Math.Abs(dy) + 1)); ++score; Console.SetCursorPosition(0, 0); Console.Write("Score:{0}", score.ToString().PadLeft(4, '0')); } } static void Main(string[] args) { try { GameMain(); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); } } /* Score:0434 Game Over! + *************** + + + + + * * + + + * + ************************************** + + * + * + * + * + * + + + ************************* * * * ********************************************************************* * * * * * *************************** * * *************************************** * * * * ****************************************** * * * * * ++ + * * * * * * + +******************************************************* * * + + + * * + + + + * * + + + * * + + + * * + + * ******************************************************************************** */
入門者がゲーム作ったりするには、やっぱコンソールが使えた方が手軽で良いですね。
あ、バグってる。でも、気にしなーい。(^^;