I am experimenting at the moment with one line in the console displaying a set of 10 randomly generated blocks, each block assigned a separate colour. Here is what I have so far:

Module Module1

    Sub Main()
        Dim rdm As New Random()
        Dim index As Integer
        Dim block(3) As String
        block(0) = "#"
        block(1) = "@"
        block(2) = "."
        block(3) = "~"
        For index = 1 To 10
            Console.Write(block(rdm.Next(1, 4)))
        Next
        Console.ReadLine()
    End Sub

End Module

I want to assign each of the characters a colour so for example the "#" will be green when displayed, and the "~" will be blue. Thanks for any help.

有帮助吗?

解决方案

Instead of declaring your blocks array as String, declare it as your own custom type that has a Char or String property for the text and a ConsoleColor property for the colour. You use your random number as an index into the array as normal, get the colour value and assign it to the ForegroundColor property of the Console class, then write out the text.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top