I seem to be having trouble with my program working and I am finding it hard to understand what I have done wrong, first of all I need a simple ( not really complicated) way of checking that the user cannot enter a string or a number over the requested amount (which currently is 1- 9 for menu options and 10 for a save option - which I need to do later) The code below is the code for the number and string checker relating to the menu and the code below the line is the whole code.
I have tried doing this but it just loops when you enter it for the row and lets you through whatever number you enter on the column. I need help also on other question relating to this like
Telling the user what ship they have hit,
Saving and Loading the game
And a score counter - I had this working then it got deleted when trying to fix first question
And a limit on the amount of goes they can have.
I will upload the code required tomorrow as cannot now, But if anybody has access to the AQA As Level free pseudocode that they give you - (its not illegal ! ) Please help me !
Sub GetRowColumn(ByRef Row As Integer, ByRef Column As Integer) ' Asks the user about where they want to go in the code
Console.WriteLine()
Dim checkcol, checkrow As String ' Defining the variables that I will user later
Dim AscCol, AscRow As Integer
Console.Write("Please enter a column:") ' Asks users to enter a column
checkcol = Console.ReadLine()
AscCol = Asc(checkcol(0)) ' It will check it on the ASCII scale to see if it isnt a letter
While AscCol > 57 Or AscCol < 48 ' If it doesnt fit in here, it is not one of the alloacated numbers
Console.WriteLine("This is not a number.")
Console.Write("Please enter a column")
checkcol = Console.ReadLine() ' Does the same for checkcol
AscCol = Asc(checkcol(0))
End While
checkcol = ((Chr(AscCol)))
Column = CInt(checkcol)
Console.WriteLine() ' This is a printed space for spacing when printed as a code
Do
If Column < 0 Or Column > 9 Then ' Now if it fits the column alloation e.g. 1 to 9 it will be allowed through
Console.WriteLine()
Console.WriteLine(" That is an invalid Input") ' Tell the user that they cannot go through as it doesn't fit the right requrirments
Column = Console.ReadLine()
End If
Console.WriteLine()
Loop Until Column < 10 And Column >= 0 ' This part of the code will run until their answer is under 10 and over 0
Console.Write("Please enter a row:") ' Here is same for rows as it is for columns
checkrow = Console.ReadLine()
AscRow = Asc(checkrow(0))
While AscRow > 57 Or AscRow < 48
Console.WriteLine("This is not a number.")
Console.Write("Please enter a row")
AscRow = Asc(checkrow(0))
End While
Row = CInt(checkrow)
Do
If Row < 0 Or Row > 9 Then
Console.WriteLine()
Console.WriteLine("That is an invalid Input.")
End If
Console.WriteLine()
Loop Until Row < 10 And Row >= 0
End Sub
Other code
'Skeleton Program for the AQA AS Paper 1 Summer 2016 examination
'this code should be used in conjunction with the Preliminary Material
'written by the AQA Programmer Team
'developed in the Visual Studio 2008 programming environment
'Version Number 1.0
Imports System.IO
Module Module1
Const TrainingGame As String = "Training.txt" ' Calls the training text file used by new players
Structure TShip ' Starts a new structure for use later that includes a stringed name and a size as an integer
Dim Name As String
Dim Size As Integer
End Structure
Sub MakePlayerMove(ByRef Board(,) As Char, ByRef Ships() As TShip) ' This part of the code advances on their column and row selection from earlier
Dim Row As Integer
Dim Column As Integer
GetRowColumn(Row, Column)
If Board(Row, Column) = "m" Or Board(Row, Column) = "h" Then ' m is miss h is a hit
Console.WriteLine("Sorry, you have already shot at the square (" & Column & "," & Row & "). Please try again.")
ElseIf Board(Row, Column) = "-" Then ' Message to user to say that they have shot in a sqaure they habe already shot in
Console.WriteLine("Sorry, (" & Column & "," & Row & ") is a miss.")
Board(Row, Column) = "m"
Else
Console.WriteLine("Hit at (" & Column & "," & Row & ").")
Board(Row, Column) = "h"
End If
End Sub
Sub SetUpBoard(ByRef Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
For Row = 0 To 9
For Column = 0 To 9
Board(Row, Column) = "-"
Next
Next
End Sub
Sub LoadGame(ByVal Filename As String, ByRef Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
Dim Line As String
Using FileReader As StreamReader = New StreamReader(Filename)
For Row = 0 To 9
Line = FileReader.ReadLine()
For Column = 0 To 9
Board(Row, Column) = Line(Column)
Next
Next
End Using
End Sub
Sub PlaceRandomShips(ByRef Board(,) As Char, ByVal Ships() As TShip)
Dim Valid As Boolean
Dim Row As Integer
Dim Column As Integer
Dim Orientation As Char
Dim HorV As Integer
For Each Ship In Ships
Valid = False
While Not Valid
Row = Int(Rnd() * 10)
Column = Int(Rnd() * 10)
HorV = Int(Rnd() * 2)
If HorV = 0 Then
Orientation = "v"
Else
Orientation = "h"
End If
Valid = ValidateBoatPosition(Board, Ship, Row, Column, Orientation)
End While
Console.WriteLine("Computer placing the " & Ship.Name)
PlaceShip(Board, Ship, Row, Column, Orientation)
Next
End Sub
Sub PlaceShip(ByRef Board(,) As Char, ByVal Ship As TShip, ByVal Row As Integer, ByVal Column As Integer, ByVal Orientation As Char)
Dim Scan As Integer
If Orientation = "v" Then
For Scan = 0 To Ship.Size - 1
Board(Row + Scan, Column) = Ship.Name(0)
Next
ElseIf Orientation = "h" Then
For Scan = 0 To Ship.Size - 1
Board(Row, Column + Scan) = Ship.Name(0)
Next
End If
End Sub
Function ValidateBoatPosition(ByVal Board(,) As Char, ByVal Ship As TShip, ByVal Row As Integer, ByVal Column As Integer, ByVal Orientation As Char)
Dim Scan As Integer
If Orientation = "v" And Row + Ship.Size > 10 Then
Return False
ElseIf Orientation = "h" And Column + Ship.Size > 10 Then
Return False
Else
If Orientation = "v" Then
For Scan = 0 To Ship.Size - 1
If Board(Row + Scan, Column) <> "-" Then
Return False
End If
Next
ElseIf (Orientation = "h") Then
For Scan = 0 To Ship.Size - 1
If Board(Row, Column + Scan) <> "-" Then
Return False
End If
Next
End If
End If
Return True
End Function
Function CheckWin(ByVal Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
For Row = 0 To 9
For Column = 0 To 9
If Board(Row, Column) = "A" Or Board(Row, Column) = "B" Or Board(Row, Column) = "S" Or Board(Row, Column) = "D" Or Board(Row, Column) = "P" Then
Return False
End If
Next
Next
Return True
End Function
Sub PrintBoard(ByVal Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
Console.WriteLine()
Console.WriteLine("The board looks like this: ")
Console.WriteLine()
Console.Write(" ")
For Column = 0 To 9
Console.Write(" " & Column & " ")
Next
Console.WriteLine()
For Row = 0 To 9
Console.Write(Row & " ")
For Column = 0 To 9
If Board(Row, Column) = "-" Then
Console.Write(" ")
ElseIf Board(Row, Column) = "A" Or Board(Row, Column) = "B" Or Board(Row, Column) = "S" Or Board(Row, Column) = "D" Or Board(Row, Column) = "P" Then
Console.Write(" ")
Else
Console.Write(Board(Row, Column))
End If
If Column <> 9 Then
Console.Write(" | ")
End If
Next
Console.WriteLine()
Next
End Sub
Sub DisplayMenu()
Console.WriteLine("MAIN MENU") ' Main Menu Screen that is displayed to the user
Console.WriteLine()
Console.WriteLine("1. Start new game")
Console.WriteLine("2. Load training game")
Console.WriteLine(" 3. Change game limit")
Console.WriteLine("4. Load Saved Game")
Console.WriteLine("9. Quit")
Console.WriteLine()
End Sub
Function GetMainMenuChoice() ' Will check if the menu choice is picked can go through
Dim Choice As Integer ' Dim choice as an integer
Try
Console.Write("Please enter your choice: ") ' Ask user to enter their choice for the menu option
Choice = Console.ReadLine() ' User enters here
Console.WriteLine()
If Choice <> "1" And Choice <> "2" And Choice <> "9" And Choice <> "10" Then
Console.WriteLine("ERROR: Invalid input!") ' If their choice doesnt fit 1, 2 or 9 then it says this message
End If
Return Choice ' Return the choice to another part of code
Catch Ex As Exception
Console.WriteLine("Please enter a valid input (1, 2,9 or 10)")
End Try
End Function
Sub PlayGame(ByVal Board(,) As Char, ByVal Ships() As TShip)
Dim GameWon As Boolean = False
Dim score As Integer = 0
Dim gamelimit As Integer = 50
Do
PrintBoard(Board)
MakePlayerMove(Board, Ships)
score = score + 1
Console.WriteLine("You have taken {0} number of moves,", score)
GameWon = CheckWin(Board)
If GameWon Then
Console.WriteLine("All ships sunk!")
Console.WriteLine()
End If
Loop Until GameWon Or score = 50
If score = 50 Then
Console.WriteLine("You used all your moves up. Try again ")
End If
End Sub
Sub SaveGame(ByRef Board(,) As Char)
Dim SaveGameWrite As StreamWriter
SaveGameWrite = New StreamWriter("TEST.txt", True)
For x As Integer = 0 To 9
For y As Integer = 0 To 9
SaveGameWrite.Write(Board(x, y))
Next
Next
SaveGameWrite.Close()
End Sub
Sub LoadSavedGame(ByVal Filename As String, ByRef Board(,) As Char)
Dim Row, Column As Integer
Dim Line As String
Console.WriteLine("Load training game or open a saved game? T for training or S for saved")
If Console.ReadLine = "" Then
Console.WriteLine("Enter the filename: ")
Filename = Console.ReadLine
End If
Using FileReader As StreamReader = New StreamReader("C:\" & Filename)
For Row = 0 To 9
Line = FileReader.ReadLine()
For Column = 0 To 9
Board(Row, Column) = Line(Column)
Next
Next
End Using
End Sub
Sub SetUpShips(ByRef Ships() As TShip)
Ships(0).Name = "Aircraft Carrier"
Ships(0).Size = 5
Ships(1).Name = "Battleship"
Ships(1).Size = 4
Ships(2).Name = "Submarine"
Ships(2).Size = 3
Ships(3).Name = "Destroyer"
Ships(3).Size = 3
Ships(4).Name = "Patrol Boat"
Ships(4).Size = 2
End Sub
Sub Main()
Dim Board(9, 9) As Char
Dim Ships(4) As TShip
Dim MenuOption As Integer
Do
SetUpBoard(Board)
SetUpShips(Ships)
DisplayMenu()
MenuOption = GetMainMenuChoice()
If MenuOption = 1 Then
PlaceRandomShips(Board, Ships)
PlayGame(Board, Ships)
ElseIf MenuOption = 2 Then
LoadGame(TrainingGame, Board)
PlayGame(Board, Ships)
ElseIf MenuOption = 3 Then
PlaceRandomShips(Board, Ships)
PlayGame(Board, Ships)
End If
Loop Until MenuOption = 9
End Sub
End Module
Thanks in advance,
The Scottish Warrior
Related
I making matrix calculator. so, Textbox_A contains vbCrLf and tries to put it in Array_A.
and I would like to put Array_A in Result Matrix.
It's like
Textbox_a:
(1 2 3)
(4 5 6)
[Matrix to Array]
Array_a(0)(0) = 1
Array_a(0)(1) = 2
Array_a(0)(2) = 3
Array_a(1)(0) = 4
...
I have done string splits through several articles, but changing them to integers causes many problems.
This picture is Matrix_A and result Matrix
I don't know if the size of your initial matrix, formatted as text, is fixed, but here is some code to help you get started. The code tries to calculate the number of columns and rows.
The actual code is in the TextToArray function, that takes as input as string formatted as you described:
(1 2 3) (cr/lf)
(4 5 6)
and outputs a two dimensional array. The Main sub is just used to call TextToArray and display results.
So, in your example, you should pass TextBox_A.Text to TextToArray
There is minimal error checking here - you should add more to validate that data entered are numbers (check the Integer.TryParse function) and that the number of columns is the same across lines.
Sub Main(args As String())
Dim myInput As String = "(1 2 3)" & vbCrLf & "(4 5 6)"
Dim ret As Integer(,) = TextToArray(myInput)
If ret IsNot Nothing Then
For i As Integer = 0 To ret.GetUpperBound(0) - 1
For n As Integer = 0 To ret.GetUpperBound(1) - 1
Console.WriteLine(i & "," & n & "=" & ret(i, n))
Next
Next
Else
Console.WriteLine("No results - wrong input format")
End If
Console.ReadLine()
End Sub
Private Function TextToArray(matrix As String) As Integer(,)
Dim noOfRows As Integer = matrix.Split(vbCrLf).Count
Dim noOfColumns As Integer = 0
If noOfRows > 0 Then
noOfColumns = matrix.Split(vbCrLf)(0).Split(" ").Count
End If
If noOfColumns > 0 And noOfRows > 0 Then
Dim ret(noOfRows, noOfColumns) As Integer
Dim lines As String() = matrix.Split(vbCrLf)
Dim row As Integer = 0
For Each line As String In lines
Dim col As Integer = 0
line = line.Replace("(", "")
line = line.Replace(")", "")
For Each s As String In line.Split(" ")
ret(row, col) = Integer.Parse(s)
col += 1
Next
row += 1
Next
Return ret
Else
Return Nothing
End If
End Function
This outputs:
0,0=1
0,1=2
0,2=3
1,0=4
1,1=5
1,2=6
I have made a program that displays an example of a particular piece of code. The available pieces of code come from a database. When the user selects an example the code itself is displayed in a RichTextbox. I also want the words to have coloring just like it would in the compiler.
I have a list of words and their associated RGB colors. I have another method which loops through the list of words and sends each one to this function:
Private Sub FindAndFormatWords(ByVal SearchString As String, ByVal r As Integer, ByVal g As Integer, ByVal b As Integer)
If r > -1 And g > -1 And b > -1 And SearchString <> "" Then
Dim richText As String = rtxtCode.Text.ToLower() 'store the rtxtCode as all lower case
Dim keyText As String = SearchString.ToLower() 'store the SearchString as all lower case
Dim wordIndex As Integer = 0
While (wordIndex < richText.LastIndexOf(keyText, StringComparison.InvariantCultureIgnoreCase)) 'loop through each of the instances of the lowercase searchString in the lowercase textbox
wordIndex = richText.IndexOf(keyText, wordIndex) 'get the index of the next instance of the search string
rtxtCode.SelectionStart = wordIndex 'select the text that contains the search string
rtxtCode.SelectionLength = keyText.Length
rtxtCode.SelectionColor = Color.FromArgb(r, g, b) 'give the selected string color
rtxtCode.SelectionFont = New Font("Verdana", 9, FontStyle.Regular)
wordIndex = wordIndex + keyText.Length + 1
End While
Else
MessageBox.Show("Error (1013): " & SearchString & " failed. Missing information.")
End If
End Sub
This works perfectly well. EXCEPT it does not find the occurrence of a word when it is the very first word. When the word begins at character index 0 in the RichTextbox, it cannot find the word. It will find every occurrence of the word after character index 0.
How can I correct this so that it finds words even at index 0?
Here's your original code refactored a bit, and searching forwards instead of backwards. It already can do a case-insensitive match, you don't have to convert to all lower case:
Private Sub FindAndFormatWords(ByVal SearchString As String, ByVal r As Integer, ByVal g As Integer, ByVal b As Integer)
If r > -1 And g > -1 And b > -1 And SearchString <> "" Then
Dim C As Color = Color.FromArgb(r, g, b)
Dim F As New Font("Verdana", 9, FontStyle.Regular)
Dim wordIndex As Integer = rtxtCode.Find(SearchString, 0, RichTextBoxFinds.NoHighlight)
While (wordIndex <> -1)
rtxtCode.SelectionStart = wordIndex
rtxtCode.SelectionLength = SearchString.Length
rtxtCode.SelectionColor = C
rtxtCode.SelectionFont = F
wordIndex = wordIndex + SearchString.Length
If (wordIndex < rtxtCode.Text.Length) Then
wordIndex = rtxtCode.Find(SearchString, wordIndex, RichTextBoxFinds.NoHighlight)
Else
wordIndex = -1
End If
End While
Else
MessageBox.Show("Error (1013): " & SearchString & " failed. Missing information.")
End If
End Sub
This code correctly finds each occurrence of a word. Even when the word begins at char index 0. You must Imports System.Text.RegularExpressions to use Regex.
Private Sub FindAndFormatWords(ByVal SearchString As String, ByVal r As Integer, ByVal g As Integer, ByVal b As Integer)
If r > -1 And g > -1 And b > -1 And SearchString <> "" Then
Dim pattern As String = SearchString
Dim regx As New Regex(pattern, RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = regx.Matches(rtxtCode.Text)
For Each match As Match In matches
rtxtCode.Select(match.Index, match.Length)
rtxtCode.SelectionColor = Color.FromArgb(r, g, b) 'give the selected string color
Next
Else
MessageBox.Show("Error (1013): " & SearchString & " failed. Missing information.")
End If
End Sub
my code is working i tried it separately but the problem here is that when i'm putting them together , the readkey or readline don't stop the program and the do loop is not working too, can someone take a look please thank in advance
Dim count As Integer
Dim first(5) As Integer
Dim temp As Integer
Dim answer As String
Sub Main()
Do
Console.WriteLine("Please enter your first number")
first(0) = Console.ReadLine
Console.WriteLine("Please enter your second number")
first(1) = Console.ReadLine
Console.WriteLine("Please enter your third number")
first(2) = Console.ReadLine
Console.WriteLine("Please enter your fourth number")
first(3) = Console.ReadLine
Console.WriteLine("Please enter your fifth number")
first(4) = Console.ReadLine
Console.WriteLine("Please enter your sixth number")
first(5) = Console.ReadLine
randomnumber()
Console.WriteLine("do you want to continue?")
answer = Console.ReadLine
Loop Until (answer = "n" Or answer = "No")
Console.ReadKey()
End Sub
Sub randomnumber()
Dim r As New List(Of Integer)
Dim rg As New Random
Dim rn As Integer
Dim arraywinner(5) As Integer
Do
rn = rg.Next(1, 40)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
'store bane random value in array'
arraywinner(0) = r(0)
arraywinner(1) = r(1)
arraywinner(2) = r(2)
arraywinner(3) = r(3)
arraywinner(4) = r(4)
arraywinner(5) = r(5)
'print random numbers
count = 0
While count <= 5
Console.WriteLine("the randoms numbers are : " & arraywinner(count))
count = count + 1
End While
'look for the amount of number
temp = 0
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If arraywinner(count1) = first(count2) Then
temp = temp + 1
End If
Next
Next
If temp = 1 Or temp = 0 Then
Console.WriteLine("You have got " & temp & " number")
Else
Console.WriteLine("You have got " & temp & " numbers")
End If
money(temp)
End Sub
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
You have two problems in money():
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
Your parameter is t1, but you're using temp in all of your code. As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all.
Secondly, you have End in the block for 0, 1, or 2 matches. The End statement Terminates execution immediately., which means the program just stops. Get rid of that line.
There are so many other things you could change, but that should fix your immediate problem...
I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place.
Module Module1
Private rg As New Random
Public Sub Main()
'keep variables with as narrow a scope as possible
Dim answer As String = Nothing
'This line initializes and array of strings called words
Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"}
Dim WinnersChosen(5) As Integer
Do
'To shorten your code use a For loop
For index = 0 To 5
Console.WriteLine($"Please enter your {words(index)} number")
WinnersChosen(index) = CInt(Console.ReadLine)
Next
Dim RandomWinners = GetRandomWinners()
Console.WriteLine("The random winners are:")
For Each i As Integer In RandomWinners
Console.WriteLine(i)
Next
Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen)
If WinnersCount = 1 Then
Console.WriteLine($"You have guessed {WinnersCount} number")
Else
Console.WriteLine($"You have guessed {WinnersCount} numbers")
End If
Dim Winnings = Money(WinnersCount)
'The formatting :N0 will add the commas to the number
Console.WriteLine($"Your winnings are {Winnings:N0}")
Console.WriteLine("do you want to continue? y/n")
answer = Console.ReadLine.ToLower
Loop Until answer = "n"
Console.ReadKey()
End Sub
'Too much happening in the Sub
'Try to have a Sub or Function do only one job
'Name the Sub accordingly
Private Function GetRandomWinners() As List(Of Integer)
Dim RandomWinners As New List(Of Integer)
Dim rn As Integer
'Good use of .Contains and good logic in Loop Until
Do
rn = rg.Next(1, 40)
If Not RandomWinners.Contains(rn) Then
RandomWinners.Add(rn)
End If
Loop Until RandomWinners.Count = 6
Return RandomWinners
End Function
Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer
Dim temp As Integer
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If r(count1) = WinnersChosen(count2) Then
temp = temp + 1
End If
Next
Next
Return temp
End Function
Private Function Money(Count As Integer) As Integer
'A Select Case reads a little cleaner
Select Case Count
Case 3
Return 120
Case 4
Return 500
Case 5
Return 10000
Case 6
Return 1000000
Case Else
Return 0
End Select
End Function
End Module
I've been working on a game of blackjack on visual basic but have been stuck on a particular task which states:
"Create a game loop to play a one-player version of the game. The game should end with the player going bust or holding on a valid score under 22."
I have gotten to code working up until that point with subroutines that manage "shuffling" the stack of figurative cards, dealing a card, checking if the player has busted or not and one that processes the player's turn.
(The commented out section is my attempt at the game loop, it does not work as once i input S or T it carries on asking if i want to stick or twist over and over)
Here is my full code:
Module Module1
Sub Main()
'task 1
Dim deck() As String = {"AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H",
"9H", "10H", "JH", "QH", "KH",
"AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD",
"AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
"AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC"}
Dim hand As New List(Of String)
Dim cardPile As New Stack(Of String)
cardPile = Shuffle(deck)
Dealing(cardPile, hand)
Dealing(cardPile, hand)
Dim BustOrNot As String
BustOrNot = Left(Bust(hand), 2)
Dim total As Integer
total = Mid(Bust(hand), 3, Bust(hand).Length)
If total = 21 Then
BlackJack(total)
End If
Console.WriteLine("Your total so far is: " & total)
'Dim stickOrTwist As Boolean
'stickOrTwist = PlayerTurn(hand)
'While BustOrNot = "NB" Or stickOrTwist = False Or total = 21
'Dealing(cardPile, hand)
'BustOrNot = Left(Bust(hand), 2)
'stickOrTwist = PlayerTurn(hand)
'End While
'If stickOrTwist = False Then
'Win(total)
'ElseIf BustOrNot = "BB" Then
'Lose(total)
'ElseIf total = 21 Then
'BlackJack(total)
'End If
Console.ReadKey()
End Sub
Function Shuffle(ByVal deck As Array)
'task 2
Dim rand As New Random()
Dim card As String
Dim card2 As String
Dim indexToShuffle As Integer
Dim indexToShuffle2 As Integer
Dim cardStack As New Stack(Of String)
For i = 1 To 1000
indexToShuffle = rand.Next(0, 51)
card = deck(indexToShuffle)
indexToShuffle2 = rand.Next(0, 51)
card2 = deck(indexToShuffle2)
deck(indexToShuffle2) = card
deck(indexToShuffle) = card2
Next
For j = 0 To 51
cardStack.Push(deck(j))
Next
Return cardStack
End Function
Sub Dealing(ByRef cardPile As Stack(Of String), hand As List(Of String))
'task 3
hand.Add(cardPile.Pop)
End Sub
Function Bust(ByVal hand As List(Of String))
'task 4
Dim total As Integer = 0
For Each item In hand
If IsNumeric(Left(item, 1)) Then
total = total + Left(item, 1)
ElseIf Left(item, 1) = "A" Then
total = total + 11
ElseIf Left(item, 1) = "J" Or Left(item, 1) = "Q" Or Left(item, 1) = "K" Then
total = total + 10
End If
Next
If total > 21 Then
Return ("BB" & total)
Else
Return ("NB" & total)
End If
End Function
Function PlayerTurn(ByRef hand As List(Of String))
'task 5
Console.WriteLine("Would you like to stick or twist? (Input S or T)")
Dim stickOrTwist As String = UCase(Console.ReadLine())
If stickOrTwist = "S" Then
Return False
ElseIf stickOrTwist = "T" Then
Return True
Else
Console.WriteLine("That isn't a valid input. Try again")
Console.WriteLine("...")
PlayerTurn(hand)
End If
End Function
Sub Lose(ByVal total As Integer)
Console.WriteLine("Oh no! you lose.")
Console.WriteLine("Your final score was: " & total)
Console.ReadKey()
End Sub
Sub Win(ByVal total As Integer)
Console.WriteLine("Well done! your score is: " & total)
Console.ReadKey()
End Sub
Sub BlackJack(ByVal total As Integer)
Console.WriteLine("Well done you scored blackjack! Your score is: " & total)
Console.ReadKey()
End Sub
End Module
I am facing an issue to perform numbers comparison between the integers inputted by user and random numbers generated by the codes.
Each of the integers input by the user should then be compared with the LOTTO numbers to check for a match. A For each… loop needs to be used to achieve this.
After checking all the 7 user input integers against the LOTTO numbers, the total number of matches should be output to the user. If there are no matches the output should read “LOOSER!”.
Here are my codes, I'm currently only stuck at the comparison portion, and we need to use for each loop to achieve this.
Imports System
Module Lotto
Sub Main()
'Declaration
Dim numbers(6) As Integer
Dim IsStarted As Boolean = True
'Prompt user to enter
Console.WriteLine("Please enter your 7 lucky numbers from 0 - 9 ONLY")
'Use Do While Loop to re-iterate the prompts
Do While IsStarted
For pos As Integer = 0 To 6
Console.Write("Enter number {0}: ", pos + 1)
'How it stores into an array
numbers(pos) = Console.ReadLine()
'Check if it is a number: use IsNumberic()
If IsNumeric(numbers(pos)) Then 'proceed
'Check if it is NOT 0 < x > 9
If numbers(pos) < 0 Or numbers(pos) > 9 Then
'Don't proceed
Console.WriteLine("Invalid Input")
IsStarted = True
'When any number is invalid, exit the loop
Exit For
End If
End If
IsStarted = False
Next
Loop
'Printing out the array. It can also be written as
'For pos = LBound(numbers) To UBound(numbers)
For pos = 0 To 6
Console.Write(numbers(pos) & " ")
Next
Console.WriteLine()
'Random number generator
Randomize()
Dim random_numbers(6) As Integer
Dim upperbound As Integer = 7
Dim lowerbound As Integer = 0
Dim rnd_number As Double = 0
For pos = 0 To 6
rnd_number = CInt((upperbound - lowerbound) * Rnd() + lowerbound)
random_numbers(pos) = rnd_number
Console.Write(random_numbers(pos) & " ")
Next
'Iterate and compare
Dim isSame As Boolean = False
Dim pos2 As Integer = 0
Dim Counter As Integer = 0
'For check = 0 To 6
'If numbers(pos2).Equals(random_numbers(pos2)) Then
For Each number As Integer In numbers
'Console.WriteLine(pos2 + 1 & ":" & number & ":")
If number.Equals(random_numbers(pos2)) Then
'Console.WriteLine("here is the number that matched:" & number & ":")
isSame = True
pos2 = pos2 + 1
End If
For Each num As Integer In random_numbers
If random_numbers Is numbers Then
Counter = Counter + 1
End If
Next
Next
Console.WriteLine()
'Display result
If isSame = True Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If
Console.ReadLine()
End Sub
End Module
Dim intCursor As Integer = 0
For Each intNumber As Integer In numbers
'Assumes first user chosen number must equal
'the first random number to be considered a match,
'the second user number must equal the second random,
'etc (Ordering is a factor).
If random_numbers(intCursor) = intNumber Then
Counter += 1
End If
intCursor += 1
Next
If (Counter > 0) Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If