Programming a game loop for single player Blackjack - vb.net

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

Related

vb.net readline or readkey don't want to stop my program

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

Removing duplicates in Text Box and adding the corresponding values

I have a VB form with three TextBoxes. Here's an example of what I'd like the program to achieve:
So, that's the form ... the program sorts a text file and gets names, goals, and positions. E.g.
Jordan 26 Center
James 10 Mid
Jordan 4 Center
Jack 6 Forward
James 10 Mid
When the update button is clicked, the program should realize that James and Jordan are written twice, remove one of them and add their goals, so it should output:
Jordan 30 Center
James 20 Mid
Jack 6 Forward
To do this I've had the data transferred into ListBoxes which makes it easier to remove duplicates, the data is then transferred back into a multi-line TextBox so it is editable. Here's my code so far. It either gives the wrong results or an index out of range error.
Dim Count1 As Integer
Dim Count2 As Integer
Dim Count3 As Integer
Dim NewInt As Integer
Dim ValOne As Integer
Dim ValTwo As Integer
ListBox1.Items.Clear()
ListBox2.Items.Clear()
ListBox3.Items.Clear()
NewInt = 0
ValOne = 0
ValTwo = 0
ListBox1.Items.AddRange(Players.Text.Split(vbNewLine))
ListBox2.Items.AddRange(Goals.Text.Split(vbNewLine))
ListBox3.Items.AddRange(Positions.Text.Split(vbNewLine))
Count1 = ListBox1.Items.Count
Count2 = ListBox2.Items.Count
Count3 = ListBox3.Items.Count
If Count1 = Count2 And Count1 = Count3 And Count2 = Count3 Then
'Set two counters to compare all words with each other
For iFirstCounter As Integer = 0 To ListBox1.Items.Count - 1
For iSecondCounter As Integer = 0 To ListBox1.Items.Count - 1
'Make sure there will not be an 'out of range' error,
'because you are removing items from the listbox.
iSecondCounter = Convert.ToInt64(iSecondCounter)
iFirstCounter = Convert.ToInt64(iFirstCounter)
ListBox2.Items.RemoveAt(iSecondCounter)
ListBox2.Items.RemoveAt(iFirstCounter)
If iFirstCounter < iSecondCounter Then
ListBox2.Items.Insert(iFirstCounter, NewInt.ToString)
Else
ListBox2.Items.Insert(iSecondCounter, NewInt.ToString)
End If
Next
Next
Players.Text = ""
Goals.Text = ""
Positions.Text = ""
Dim i As Integer
For i = 0 To ListBox1.Items.Count - 1
If Players.Text = "" Then
Players.Text = ListBox1.Items(i)
Else
Players.Text = Players.Text & vbNewLine & ListBox1.Items(i)
End If
Next
Dim a As Integer
For a = 0 To ListBox2.Items.Count - 1
If Goals.Text = "" Then
Goals.Text = ListBox2.Items(a)
Else
Goals.Text = Goals.Text & vbNewLine & ListBox2.Items(a)
End If
Next
Dim b As Integer
For b = 0 To ListBox3.Items.Count - 1
If Positions.Text = "" Then
Positions.Text = ListBox3.Items(b)
Else
Positions.Text = Positions.Text & vbNewLine & ListBox3.Items(b)
End If
Next
Else
MessageBox.Show("The Text Boxes don't contain an equal number of values ... please add more/remove some values")
End If
Could be done in multiple ways, for example:
If TextBox2.Lines.Count > 1 Then
Dim LineList As List(Of String) = TextBox2.Lines.ToList 'textbox lines
Dim NewLines As List(Of String) = TextBox2.Lines.ToList 'can't edit list we're looping over, a copy of lines
Dim NamesList As New List(Of String)
For x = 0 To LineList.Count - 1
Dim linesplit As String() = LineList(x).Split({" "}, StringSplitOptions.RemoveEmptyEntries)
If NamesList.Contains(linesplit(0)) Then
NewLines.Remove(LineList(x))
Else
NamesList.Add(linesplit(0))
End If
Next
TextBox2.Lines = NewLines.ToArray
End If
Here's an example of code that does this via LINQ and Lambdas.
Module Module1
Sub Main()
Dim ungroupedPlayers(1) As String
ungroupedPlayers(0) = "Jordan 26 Center"
ungroupedPlayers(1) = "Jordan 4 Center"
Dim players = ungroupedPlayers.ToList().ConvertAll(Of Player)(Function(x As String) As Player
Dim split() As String = x.Split(" "c)
Dim p As New Player
p.PlayerName = split(0)
p.Count = split(1)
p.Position = split(2)
Return p
End Function)
Dim playersGrouped = From p In players
Group By PlayerName = p.PlayerName Into g = Group
Select PlayerName, Count = g.Sum(Function(ip As Player) ip.Count), Position = g.Min(Function(ip As Player) ip.Position.ToString())
Dim groupedPlayers() As String = playersGrouped.ToList().ConvertAll(Of String)(Function(ip)
Return ip.PlayerName.ToString() & " " & ip.Count.ToString() & " " & ip.Position.ToString()
End Function).ToArray()
For Each groupedPlayer as String in groupedPlayers
Console.WriteLine(groupedPlayer)
Next
Console.Read()
End Sub
Public Class Player
Public PlayerName As String
Public Count As Integer
Public Position As String
End Class
End Module
You don't need heavy ListBox control for working with players data.
Use List(Of T) and create class Player for better readability.
You can remove duplicates before you will display values in your form.
And instead of multiline textbox you can use DataGridView as "right tool for the editing data".
Public Class Player
Public Property Name As String
Public Property Position As String
Public Property Goals As Integer
End
Public Class PlayersForm : Form
Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
Dim data As List(Of Player) = LoadPlayersData()
Dim players As List(Of Player) = NormalizeData(data)
' Use DataGridView
Me.DataGridView1.DataSource = players
End Sub
Private Function LoadPlayersData() As List(Of Player)
Dim rawData As String() = File.ReadAllLines("pathToTextFile")
Return rawData.Select(Function(line) LineToPlayer(line)).ToList()
End Function
Private Function NormalizeData(players As List(Of Player)) As List(Of Player)
Return players.Group(Function(player) player.Name)
.Select(Function(group)
Return New Player With
{
.Name = group.Key,
.Position = group.First().Position,
.Goals = group.Sum(Function(player) player.Goals)
}
End Function)
.ToList()
End Function
Private Function LineToPlayer(line As String) As Player
Dim values = line.Split(" "c)
Return New Player With
{
.Name = values(0),
.Position = values(2),
.Goals = Integer.Parse(values(1))
}
End Function
End Class
DataGridView control will automatically update your List(Of Players) when you make any change. which give you possibility to have some other controls which automatically display best scorers for example, without extra converting data from string to integer and back.

What has to be done to show a marquee output with a scroll menu?

Today i continue my work, Building a menu with a vb.net console application. I found more samples to build with Windows forms. Still i try to get Basic Knowledge with the console surface.I was not able to put the following marquee text in a scroll menu, the second Code past the marquee text.
Module Module1
Dim aTimer As New System.Timers.Timer
Const marqueeText As String = "The quick brown fox... "
Dim sb As New System.Text.StringBuilder
Dim direction As Boolean = False
Sub Main()
aTimer.AutoReset = True
aTimer.Interval = 100 '1/10 second
AddHandler aTimer.Elapsed, AddressOf tick
aTimer.Start()
Console.ReadKey()
End Sub
Private Sub tick(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
Console.Clear()
If sb.Length = 0 Then sb.Append(marqueeText)
If direction Then
sb.Insert(0, sb(sb.Length - 1))
sb.Remove(sb.Length - 1, 1)
Else
sb.Append(sb(0))
sb.Remove(0, 1)
End If
Console.CursorLeft = 10 'no visible change
Console.CursorTop = 10 'visible change
Console.Write("{0}{1}", vbCr, sb.ToString)
End Sub
End Module
The marquee text Output from above is not easy to manage with the console.cursorleft command. I have no clue how to move it to the right or to put the marquee Output in the following Code, a scroll menu, on the third line.
Module Module1
Dim MenuList As New List(Of String)
Sub PrintMenu(highlight As Integer, left As Integer, top As Integer)
Dim Nickvektor() As Integer = {1, 2, 3, 4, 5}
For I = 0 To MenuList.Count - 1
Console.CursorLeft = left
Console.CursorTop = top + I
If I = highlight Then
Console.Write("{0}", "[" & Nickvektor(I) & "]")
Else
Console.Write(MenuList(I))
End If
Next
End Sub
Sub Main()
Console.CursorVisible = False
Dim x As Integer = 0
Dim Nickvektor() As String = {" "}
For counter As Integer = 0 To 0
Do
For Each s In Nickvektor
MenuList.Add(s)
Next
x += 1
Loop Until x = 5
Next
Console.SetCursorPosition(10, 16)
Console.Write("[ ]")
Dim CurrentItem As Integer = 0
Dim CurrentKey As ConsoleKey
While CurrentKey <> ConsoleKey.Enter
PrintMenu(CurrentItem, 10, 10)
CurrentKey = Console.ReadKey(True).Key
Select Case CurrentKey
Case ConsoleKey.DownArrow
CurrentItem += 1
Case ConsoleKey.UpArrow
CurrentItem -= 1
End Select
CurrentItem = (CurrentItem + MenuList.Count) Mod MenuList.Count
End While
End Sub
End Module
The menu Frame for the above Code can be used with the up and down arrows on the Keyboard.
Maybe it is to much work but i have no clue how to continue.
The first Solution for the marquee Output is an easy change of the original code. The wrap, vbCr, was the main Problem to move the text output toward the right edge oft he screen. The following code can be used to change the cursorTop Positon and also the cursorLeft Position of the Text.
Console.CursorVisible = False
Console.CursorLeft = 30
Console.CursorTop = 10
Console.Write("{0}", sb.ToString)
The heavy part are the Menu code Lines. To answer my own question some additional help was necessary.
I posted my question on the MS developer Network written in german language. With the following link it can be viewed.
For the case the link should be broken or other cases i post the code on this site.
Module Module1
Dim MenuList As New List(Of String)
Dim aTimer As New System.Timers.Timer
Const marqueeText As String = "The quick brown fox... "
Dim sb As New System.Text.StringBuilder
Dim direction As Boolean = False
Sub PrintMenu(highlight As Integer, left As Integer, top As Integer)
Dim Nickvektor() As Integer = {1, 2, 3, 4, 5}
For I = 0 To MenuList.Count - 1
Console.CursorLeft = left
Console.CursorTop = top + I
If I = highlight Then
Console.Write("{0}", "[" & Nickvektor(I) & "]")
Else
Console.Write(MenuList(I))
End If
Next
End Sub
Sub Main()
Console.CursorVisible = False
aTimer.AutoReset = True
aTimer.Interval = 100 '1/10 second
AddHandler aTimer.Elapsed, AddressOf tick
Dim x As Integer = 0
Dim Nickvektor() As String = {" "}
For counter As Integer = 0 To 0
Do
For Each s In Nickvektor
MenuList.Add(s)
Next
x += 1
Loop Until x = 5
Next
Console.SetCursorPosition(10, 16)
Console.Write("[ ]")
Dim CurrentItem As Integer = 0
Dim CurrentKey As ConsoleKey
While CurrentKey <> ConsoleKey.Enter
If CurrentItem = 2 Then ' Zero can be used to show the marquee output prompt
aTimer.Start() ' With a change to two or four the timer can be stoped:
'Else
'If aTimer.Enabled Then
' aTimer.Stop()
'End If
End If
PrintMenu(CurrentItem, 10, 10)
CurrentKey = Console.ReadKey(True).Key
Select Case CurrentKey
Case ConsoleKey.DownArrow
CurrentItem += 1
Case ConsoleKey.UpArrow
CurrentItem -= 1
End Select
CurrentItem = (CurrentItem + MenuList.Count) Mod MenuList.Count
End While
End Sub
Private Sub tick(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
If sb.Length = 0 Then sb.Append(marqueeText)
If direction Then
sb.Insert(0, sb(sb.Length - 1))
sb.Remove(sb.Length - 1, 1)
Else
sb.Append(sb(0))
sb.Remove(0, 1)
End If
Console.CursorVisible = False
Console.CursorLeft = 20
Console.CursorTop = 12 ' For the first Element CursorTop=10, fort he third 12
Console.Write("{0}", sb.ToString)
End Sub
End Module
To learn an other language like English i have to search a lot. Visual Basic Code is mostly written with English key words for the commands. I think it is easier to look up the maintainable changes for your self. To search is not every day funny.

AQA AS Level Problems - VB - Comp 1

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

How can I go about adding a ProgressBar to this code which calculates CRC32 checksum in VB.NET?

Thanks for reading - I am using the class below to calculate the CRC32 checksum of a specified file.
My question is how would I go about reporting the progress of file completion (in %) to a progressbar on a different form. I have tried (i / count) * 100 under the New() sub but I am not having any luck, or setting the progress bar with it for that matter. Can anyone help?
Thanks in advance
Steve
Public Class CRC32
Private crc32Table() As Integer
Private Const BUFFER_SIZE As Integer = 1024
Public Function GetCrc32(ByRef stream As System.IO.Stream) As Integer
Dim crc32Result As Integer
crc32Result = &HFFFFFFFF
Dim buffer(BUFFER_SIZE) As Byte
Dim readSize As Integer = BUFFER_SIZE
Dim count As Integer = stream.Read(buffer, 0, readSize)
Dim i As Integer
Dim iLookup As Integer
Do While (count > 0)
For i = 0 To count - 1
iLookup = (crc32Result And &HFF) Xor buffer(i)
crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
crc32Result = crc32Result Xor crc32Table(iLookup)
Next i
count = stream.Read(buffer, 0, readSize)
Loop
GetCrc32 = Not (crc32Result)
End Function
Public Sub New()
Dim dwPolynomial As Integer = &HEDB88320
Dim i As Integer, j As Integer
ReDim crc32Table(256)
Dim dwCrc As Integer
For i = 0 To 255
Form1.CRCWorker.ReportProgress((i / 255) * 100) 'Report Progress
dwCrc = i
For j = 8 To 1 Step -1
If (dwCrc And 1) Then
dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
dwCrc = dwCrc Xor dwPolynomial
Else
dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
End If
Next j
crc32Table(i) = dwCrc
Next i
'file complete
End Sub
End Class
'------------- END CRC32 CLASS--------------
'-------------- START FORM1 --------------------------
Private Sub CRCWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles CRCWorker.DoWork
For i = CurrentInt To dgv.Rows.Count - 1
CRCWorker.ReportProgress(0, i & "/" & Total_Files)
Current_File_Num = (i + 1)
SetControlText(lblCurrentFile, Str(Current_File_Num) & "/" & Total_Files)
result = CheckFile(SFV_Parent_Directory & "\" & dgv.Rows(i).Cells(0).Value, dgv.Rows(i).Cells(1).Value)
Select Case result
Case 0 ' missing file
UpdateRow(i, 2, "MISSING")
'dgv.Rows(i).Cells(2).Value = "MISSING"
Missing_Files = Missing_Files + 1
SetControlText(lblMissingFiles, Str(Missing_Files))
Case 1 ' crc match
UpdateRow(i, 2, "OK")
' dgv.Rows(i).Cells(2).Value = "OK"
Good_Files = Good_Files + 1
SetControlText(lblGoodFiles, Str(Good_Files))
Case 2 'crc bad
UpdateRow(i, 2, "BAD")
' dgv.Rows(i).Cells(2).Value = "BAD"
Bad_Files = Bad_Files + 1
SetControlText(lblBadFiles, Str(Bad_Files))
End Select
If CRCWorker.CancellationPending = True Then
e.Cancel = True
Exit Sub
End If
Next
End Sub
Private Sub CRCWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles CRCWorker.ProgressChanged
Dim val As Integer = e.ProgressPercentage
ProgressBar2.Maximum = 100
ProgressBar2.Value = e.ProgressPercentage
Debug.Print(val)
End Sub
Function CheckFile(ByVal tocheck_filepath As String, ByVal expected_crc As String) As Integer 'returns result of a file check 0 = missing 1 = good 2 = bad
If File.Exists(tocheck_filepath) = False Then
Return 0 'return file missing
End If
Dim f As FileStream = New FileStream(tocheck_filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
Dim c As New CRC32()
crc = c.GetCrc32(f)
Dim crcResult As String = "00000000"
crcResult = String.Format("{0:X8}", crc)
f.Close()
End Function
It appears your .ReportProgress() call is in the New() subroutine, which is the part that makes the lookup table for the CRC calculation. The New() subroutine is called once, before the main CRC routine. The main CRC routine is the one that takes up all the time and needs the progress bar.
Shouldn't the progress bar updating be in the GetCrc32() function? Something like this:
Public Function GetCrc32(ByRef stream As System.IO.Stream, _
Optional prbr As ProgressBar = Nothing) As UInteger
Dim crc As UInteger = Not CUInt(0)
Dim buffer(BUFFER_SIZE) As Byte
Dim readSize As Integer = BUFFER_SIZE
Dim left As Long = stream.Length
If Not (prbr Is Nothing) Then ' ProgressBar setup for counting down amount left.
prbr.Maximum = 100
prbr.Minimum = 0
prbr.Value = 100
End If
Dim count As Integer : Do
count = stream.Read(buffer, 0, readSize)
For i As Integer = 0 To count - 1
crc = (crc >> 8) Xor tbl((crc And 255) Xor buffer(i))
Next
If Not (prbr Is Nothing) Then ' ProgressBar updated here
left -= count
prbr.Value = CInt(left * 100 \ stream.Length)
prbr.Refresh()
End If
Loop While count > 0
Return Not crc
End Function
In Windows Forms BackgroundWorker Class is often used to run intensive tasks in another thread and update progress bar without blocking the interface.
Example of using BackgroundWorker in VB.Net
The problem is when you use use the form in your code without instantiating it Form1.CRCWorker.ReportProgress((i / 255) * 100) there is a kind of hidden "auto-instantiation" happening and new instance of Form1 is created each time.