Хотите изменить ForegroundColor с помощью ввода от пользователя - PullRequest
0 голосов
/ 27 августа 2018

Я хочу создать текстовую игру, в которой в начале вы можете выбрать цвет вашего персонажа. Я искал везде, но, похоже, ничего не нашел! Вот мой код (вероятно, это мусор, так как я начал 4 часа назад) Всякий раз, когда я говорю с главным героем, я пишу «Player ();» строка перед моей Console.WriteLine ("XXXXXX");

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Adventure_game
{
    class Program
    {
        static void Main(string[] args)
        {
            //Start
            menuspeaker();
            Console.WriteLine("Welcome to -- (by: Patrick Sørensen)");
            Thread.Sleep(2000);
            Console.WriteLine("Note: You can escape the anytime by pressing ESC, but be careful you can not save and any progress will be lost!");
            Thread.Sleep(8000);
            Console.WriteLine("First of all select your color!");
            Thread.Sleep(2000);
            Console.WriteLine("Type 1 for Blue");
            Thread.Sleep(1000);
            Console.WriteLine("Type 2 for White");
            Thread.Sleep(1000);
            Console.WriteLine("Type 3 for Green");
            Thread.Sleep(1000);
            Console.WriteLine("Type 4 for Red");
            Thread.Sleep(1000);
            Console.WriteLine("Type 5 for Yellow");
            Thread.Sleep(1000);
            Console.WriteLine("Type 6 for Purple");
            ConsoleKeyInfo keyInfo = Console.ReadKey();
            Thread.Sleep(2000);

            if (keyInfo.KeyChar == '1')
            {
                var Player = Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("");
                Console.WriteLine("You have choosen BLUE!");
            }
            if (keyInfo.KeyChar == '2')
            {
                var Player = Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("");
                Console.WriteLine("You have choosen WHITE!");
            }
            if (keyInfo.KeyChar == '3')
            {
                var Player = Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("");
                Console.WriteLine("You have choosen GREEN!");
            }
            if (keyInfo.KeyChar == '4')
            {
                var Player = Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("");
                Console.WriteLine("You have choosen RED!");
            }
            if (keyInfo.KeyChar == '5')
            {
                var Player = Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("");
                Console.WriteLine("You have choosen YELLOW!");
            }
            if (keyInfo.KeyChar == '6')
            {
                var Player = Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("");
                Console.WriteLine("You have choosen PURPLE!");
            }

            menuspeaker();
            Console.WriteLine("Write Ready when you are ready to begin");

            menuanswer();
            string readyString = Console.ReadLine();

            //Ready command
            if (readyString.ToLower() == "ready")
            {
            Thread.Sleep(2000);
            }

            //Navn
            menuspeaker();
            Console.WriteLine("Before we begin the story, tell me, what is your name?");
            menuanswer();
            string nameString = Console.ReadLine();
            Thread.Sleep(1000);
            menuspeaker();
            Console.WriteLine(""+nameString+"?");
            Thread.Sleep(2000);
            Console.WriteLine("What a wounderfull name!");
            Thread.Sleep(2000);
            Console.WriteLine("Okay, now we can begin with our adventure!");
            Thread.Sleep(500);
            Console.WriteLine("Please wait");
            Thread.Sleep(5000);
            Console.Clear();

            //Start på spillet
            Fred();
            Thread.Sleep(2000);
            Console.WriteLine("Fred: Hurry up "+nameString+" the king is waiting!");
            Thread.Sleep(5000);
            //The Player will speak here vv
            Console.WriteLine(""+nameString+": Why are we in such a hurry? What has happend?");
            Thread.Sleep(5000);
            Fred();
            Console.WriteLine("Fred: I don't know, when the alarm went off the guards requested you in the throne room");
            Thread.Sleep(5000);
            menuspeaker();
            Console.WriteLine("Fred and "+nameString+" entered the the big throne room and on the throne sat the King nervous");
            Thread.Sleep(6000);
            King();
            Console.WriteLine("King: I have been waiting quite a while for you " + nameString + " and Fred, how come");
            Thread.Sleep(5000);
            Fred();
            Console.WriteLine("Fred: I had a hard time finding " + nameString + ", why did the alarm go off?");
            Thread.Sleep(4000);
            King();
            Console.WriteLine("King: The princess have been taken by a Big monster!");
            Thread.Sleep(2000);
            Console.WriteLine("And i want you Fred and " + nameString + " go find the Monsters");



        }
        static void menuspeaker()
        {
            Console.ForegroundColor = ConsoleColor.DarkRed;
        }
        static void menuanswer()
        {
            Console.ForegroundColor = ConsoleColor.White;

        }
        static void Fred()
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
        }
        static void Player()
        {

        }
        static void King()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
        }
        static void Monster()
        {
            Console.ForegroundColor = ConsoleColor.DarkGreen;
        }
    }
}

1 Ответ

0 голосов
/ 27 августа 2018

Я думаю, вам нужно связать цвета с игроками в начале программы, и помнить об этом всюду по программе. Затем, когда конкретный игрок говорит , вы устанавливаете цвет консоли, а после разговора возвращаете его обратно.

Допустим, у вас есть простой класс Player, например:

public class Player
{
    public string Name { get; set; }
    public ConsoleColor Color { get; set; }

    public void Speak(string speech)
    {
        Console.ForegroundColor = Color;
        Console.WriteLine(speech);
        Console.ForegroundColor = ConsoleColor.White;
    }
}

Теперь у каждого игрока есть ассоциированные Name и ConsoleColor, и всякий раз, когда вызывается Speak(), консоль будет настраиваться на цвет этого игрока, записывать речь, а затем возвращать ее в белый цвет (предполагая, что белый цвет по умолчанию).

В вашей основной программе теперь вы, вероятно, можете запросить Name и Color.

static void Main(string[] args)
{
    var player = new Player();
    Console.Write("Enter Name : ");
    var name = Console.ReadLine();
    player.Name = name;

    Console.WriteLine("First of all select your color!");
    Console.WriteLine("Type 1 for Blue");
    Console.WriteLine("Type 2 for Green");
    ConsoleKeyInfo keyInfo = Console.ReadKey();

    if (keyInfo.KeyChar == '1')
    {
        player.Color = ConsoleColor.Blue;
    }
    if (keyInfo.KeyChar == '2')
    {
        player.Color = ConsoleColor.Green;
    }

    player.Speak(string.Format("You have chosen {0}", player.Color.ToString()));

    Console.ReadLine();
}

Теперь вы можете расширить эту идею, и в начале игры спросите имена и цвета многих игроков. Затем сохраните их в List<Player> и используйте их повсюду.


EDIT

Вы даже можете включить получение информации от пользователя в класс Player, чтобы он был более чистым и менее подверженным ошибкам. Вы бы включили этот метод в класс Player:

public void GetPlayerInfo()
{
    Console.Write("Enter Name : ");
    Name = Console.ReadLine();
    Console.WriteLine();
    Console.WriteLine("Pick a Color : ");
    Console.WriteLine("1 : Red");
    Console.WriteLine("2 : Blue");
    Console.WriteLine("3 : Green");
    var key = Console.ReadLine();
    switch (key)
    {
        case "1":
            Color = ConsoleColor.Red;
            break;
        case "2":
            Color = ConsoleColor.Blue;
            break;
        case "3":
            Color = ConsoleColor.Green;
            break;
        default:
            Color = ConsoleColor.White;
            break;
    }
    Console.WriteLine();
}

Тогда на главном конце все, что вам нужно сделать, это вызвать метод:

static void Main(string[] args)
{
    var player1 = new Player();
    player1.GetPlayerInfo();
    player1.Speak(string.Format("You have chosen {0}", player1.Color.ToString()));
    var player2 = new Player();
    player2.GetPlayerInfo();
    player2.Speak(string.Format("You have chosen {0}", player2.Color.ToString()));

    Console.ReadLine();
}
...