Deutsch
Germany.ruФорумы → Архив Досок→ Программирование

Вопросы по C#

26.10.13 19:58
Re: Вопросы по C#
 
Mahone постоялец
в ответ AlexNek 25.10.13 18:13, Последний раз изменено 26.10.13 22:10 (Mahone)
Получил новое задание - написать игру 21(не очко) со спичками. Игра тупая: дается 21 спичка, игрок берет от 1 до 4 спичек, потом от 1 до 4 спичек забирает компьютер, кто взял последнюю - тот проиграл. Стратегия компьютера - брать количество спичек 5-(количество_взятое_игроком): 21mod5 = 1, игрок всегда проигрывает
В общем, код такой написал:
using System;
namespace Spiel21
{
class Program
{
static void Main()
{
// Title text
Console.WriteLine("Spiel 21\n ======");
Console.WriteLine("Nimm zwischen 1 und 4 Hölzer. Wer das letzte Holz nimmt, hat verloren.");
Console.WriteLine("Du fängst an.");
// The starting amount of matches is 21
int sumMatches = 21;
Console.Write("Streichhölzer auf dem Tisch: ");

// Prints 21 match on the screen
for (int i = 1; i <= sumMatches; i++)
{
Console.Write("| ");
}
Console.WriteLine();
do
{
int playerMatches;
bool Matches = true;
do
{
// Asks to enter the amount of matches
Console.Write("Wie viele Hölzer nimmst Du: ");
playerMatches = Convert.ToInt32(Console.ReadLine());
// Checks if the amount of matches is from 1 to 4.
// If no, asks to re-enter the amount.

if (playerMatches > 4 || playerMatches < 1)
{
Matches = false;
Console.WriteLine("Falsche Zahl. Wiederhole die Eingabe.");
}
else
{
break;
}
}
while(!Matches);
// Calculates amount of remaining matches and print them on the screen
sumMatches = sumMatches - playerMatches;
Console.Write("\nStreichhölzer auf dem Tisch: ");
for (int i = 1; i <= sumMatches; i++)
{
Console.Write("| ");
}
Console.WriteLine();
// Calculates amount of matches taken by a computer
int compMatches = 5 - playerMatches;
if (compMatches > 1)
{
Console.WriteLine("Ich nehme {0} Hölzer.", compMatches);
}
else
{
Console.WriteLine("Ich nehme {0} Holz.", compMatches);
}
// Calculates amount of remaining matches and print them on the screen
sumMatches = sumMatches - compMatches;
Console.Write("\nStreichhölzer auf dem Tisch: ");
for (int i = 1; i <= sumMatches; i++)
{
Console.Write("| ");
}
Console.WriteLine();
}
// Repeats until there remains only one match
while (sumMatches > 1);
// If there remains only one match, prints that you have lost.
if (sumMatches == 1)
{
Console.WriteLine("\nDu hast VERLOREN!");
}
Console.ReadLine();
}
}
}


Пока не совсем в курсе, как правильно писать комментарии, пишу везде, где покажется нужным.
Вопрос: как в программу, дополнительно к проверке ввода числа от 1 до 4, приписать еще и проверку на то, что вводится именно число, а не буква или символ. В общем, чтобы программа не выдавала ошибку при вводе буквы, а предлагала ввести правильное значение.
Пока нашел такой вариант:

if (!int.TryParse(Console.ReadLine(), out playerMatches))
{
Console.WriteLine("Falsche Zahl. Wiederhole die Eingabe.");
Matches = false;
}


Не понимаю, как этот кусок туда внедрить, ибо переменная playerMatches уже использует Console.ReadLine().

 

Перейти на