Я пытался создать базовую игру Монти Пайтон для своего последнего проекта. Я не знаю, как положить приз в случайную дверь или открыть случайную дверь. Я искал другие ресурсы и не нашел никакой информации, которая могла бы помочь мне с этим заданием. Спасибо.
Вот код, который я пытался запустить и получил исключение «За пределами границ»:
using System;
class Guess
{
static void Main (string[] args)
{
Dictionary<int, string> Door = new Dictionary<int, string>();
Door.Add(1, "Nothing");
Door.Add(2, "Car");
Door.Add(3, "Nothing");
Random rng = new Random();
int x = rng.Next(0, Door.Count);
int doors = Door.Keys.ElementAt(x);
string prize = Door.Values.ElementAt(x);
int n = Door.Count;
int PrizeDoor = Convert.ToInt32(new Random());
Console.WriteLine("Which door do you want to select?");
int SelectedDoor = Convert.ToInt32(Console.ReadLine());
int RevealedDoor = Convert.ToInt32(new Random());
Console.WriteLine("Do you want to change your selection?");
string selection = Console.ReadLine();
if (selection == "Yes")
{
// ask user which new door to choose
Console.WriteLine("Which door would you like to choose now?");
int NewSelectedDoor = Convert.ToInt32(Console.ReadLine());
if (NewSelectedDoor == SelectedDoor)
{
Console.WriteLine("You cannot select the same door twice. Please try again.");
}
else if (NewSelectedDoor == PrizeDoor)
{
Console.WriteLine("Congratulations! You won the game!");
return;
}
else
{
Console.WriteLine("Sorry, you lost the game!");
return;
}
}
else
{
// stay with same door and reveal what's in the door
if (SelectedDoor == PrizeDoor)
{
Console.WriteLine("Congratulations! You won the game!");
return;
}
else
{
Console.WriteLine("Sorry, you lost the game!");
return;
}
}
}
}
Какие-либо предложения? Спасибо.
Это Монти Холл (игра и проблема/парадокс: en.m.wikipedia.org/wiki/Monty_Hall_problem). Как бы то ни было, «Давайте заключим сделку» до сих пор показывают по телевидению. Сейчас ведущим является Уэйн Брэйди.
Кори, я пытался сделать приз за случайной дверью и открытую дверь тоже случайной дверью, но при этом не сделать так, чтобы обнаруженная дверь содержала приз. Но я не знаю, как это сделать.





Первая проблема, которую я вижу в вашем коде, приводит к тому, что он выдает исключение и вообще не работает:
Convert.ToInt32(new Random());
new Random() создаёт новый объект типа Random. Это класс генератора случайных чисел, его нельзя преобразовать в целое число.
Вместо того, чтобы вручную добавлять «Ничего» в позиции 1 и 3 и «Автомобиль» в позиции 2, как вы делаете здесь:
Door.Add(1, "Nothing");
Door.Add(2, "Car");
Door.Add(3, "Nothing");
Вам понадобится использовать генератор случайных чисел (который вы создали с помощью Random rng = new Random();), чтобы случайным образом определить, за какой дверью пройдет приз. Предположим, вы используете три двери, что является классическим количеством дверей «проблемы Монти Холла», вот что я бы сделал. Возможно, это не самый эффективный способ сделать это, но я стараюсь держать его на начальном уровне.
// instantiate your doors dictionary
// and random number generator
Dictionary<int, string> doors = new Dictionary<int, string>();
Random rng = new Random();
int totalNumberOfDoors = 3;
// use your random number generator to generate a number
// between 1 (inclusive) and 4 (exclusive)
// whatever number it generates, that's what door the prize is behind
int prizeBehindDoor = rng.Next(1, totalNumberOfDoors + 1);
// fill your doors dictionary now
// I'm using a plain for loop b/c it's a basic concept
// it starts at 1 because your doors are numbered "1", "2", "3" and not "0", "1", and "2"
for (int i = 1; i <= totalNumberOfDoors; i++)
{
// if `i` is the door the prize is behind, add "Car"
if (i == prizeBehindDoor)
{
doors.Add(i, "Car");
}
// otherwise, add "Nothing"
else
{
doors.Add(i, "Nothing");
}
}
Теперь в вашем словаре дверей в случайном месте есть слово «Автомобиль», а в двух других местах — «Ничего».
Я предполагаю, что вы еще не используете LINQ, поэтому я дам вам решение, не использующее LINQ. И опять же, есть более чистые и оптимизированные способы сделать это, но я позволю вам разобраться в этом самостоятельно. Мой ответ скорее направлен на то, чтобы указать вам правильное концептуальное направление.
// the prize could be behind any of the 3 doors,
// so you can't JUST randomly generate a number between 1 and 3 again
// because it might pick the one with the prize
// so let's assign the door numbers that AREN'T the prize to a list
List<int> nonPrizeDoors = new List<int>();
// loop thru the keys of your doors dictionary, and only add items that are not the prize
// the "keys" of the dictionary are your door numbers (1, 2, and 3)
// there's definitely other ways of doing this
foreach (int key in doors.Keys)
{
// only add this key to "nonPrizeDoors" if it's NOT the prize
if (key != prizeBehindDoor)
{
nonPrizeDoors.Add(key);
}
}
// now your "nonPrizeDoors" list contains all the door numbers that are not prize doors
// now you want to use your random number generator to randomly pick one of those
// you're picking an array/list INDEX here
// so you want to generate a number between 0 (inclusive) and the number of items in the list (exclusive)
int randomIndex = rng.Next(0, nonPrizeDoors.Count);
// remember that was just the INDEX,
// saying which of the (two) items in the Keys list you're going to choose
// now you want to get the randomly-chosen Key (door number)
int chosenDoorNumber = nonPrizeDoors[randomIndex];
// now you can get that item from the doors dictionary, and do whatever you need with it
string chosenDoor = doors[chosenDoorNumber]; // will be "Nothing"
На этом этапе вы можете делать все, что захотите, с помощью chosenDoorNumber и chosenDoor. Отобразить его пользователю и т. д.
Если только там нет ничего о глупых прогулках или о том, что там скрывается испанская инквизиция, я полагаю, вы имели в виду «Монти Хоул». Также ваш код не компилируется. Чего вы ожидали
Convert.ToInt32(new Random())сделать?