VB.Net Drawing Binary Trees - vb.net

Essentially, the purpose of this program is for revision. The program will generate a random mathematical expression, convert this into a visual representation of a binary tree and the user will have to traverse the binary tree. However, when I run this code, the initial node is far off centre. How would I go about re-positioning the binary tree to be in the middle of the PictureBox? Here is my code:
Public Class BTT
'VARAIBLES DECLARED CANNOT BE A FAULT
Dim nodes(7) As Object
'maybe try to alter the form so that the user can only get two incorrect answers'
Dim operators(6) As String
Dim actualAnswer As String = ""
Dim ogEquation(11) As String
Dim newLabel As String = "" 'used to store the equation to be stored in the label'
Dim userAnswer As String
Dim myTime As Double
Dim traversal(3) As String
Dim selectedTraversal As String
Dim treeCounter As Integer = 0
Dim draw As Boolean = False
Structure tree
Dim name As String
Dim left As Integer
Dim right As Integer
End Structure
Dim TreeNode(7) As tree
Dim scoreValue As Integer = 0 'stores the user's score for the game just completed'
Dim updating As Boolean = False 'if there are already 10 scores, the first one will need to be removed, so updating = true'
Class node
Public lineColour As Color
Public lineWidth As Integer
Public posX As Integer
Public posY As Integer
Public radius As Integer
Public Sub draw(e As PaintEventArgs)
Dim myPen As New Pen(Me.lineColour, Me.lineWidth)
e.Graphics.DrawEllipse(myPen, Me.posX, Me.posY, Me.radius, Me.radius)
End Sub
End Class
Sub DrawTree()
'these are the coordinates of the top left of the PictureBox
Dim leftX As Integer = 171
Dim rightX As Integer = 171 + PictureBox1.Width 'will be set to the edge of the picturebox
Dim topY As Integer = 138
Dim bottomY As Integer = 138 + PictureBox1.Height 'will be that number of pixels down, WILL NEVER CHANGE
Dim currentNode As Integer = 1 'will initially be the root node
For i = 1 To treeCounter 'loops based on the number of nodes in the array'
'assigns the basic information common to all of the nodes
nodes(i) = New node
nodes(i).radius = 70
nodes(i).lineWidth = 2
nodes(i).lineColour = Color.Black
Next
'need to go through the binary tree and determine x & y positions, with labels inside the ellipses
ConstructTree(currentNode, leftX, rightX, topY, bottomY)
draw = True
PictureBox1.Refresh()
End Sub
Sub ConstructTree(ByRef currentNode As Integer, ByRef leftX As Integer, ByRef rightX As Integer, ByRef topY As Integer, ByRef bottomY As Integer)
'ASK ISABEL ABOUT DYNAMICALLY GENERATING A LABEL'
'e.g. Dim test As New Label
nodes(currentNode).posX = (leftX + rightX) / 2 'gets average of x coordinates'
nodes(currentNode).posY = topY + ((bottomY - topY) * (1 / 3)) 'gets number of pixels down between bottom of form & last node, goes a third of the way down
If TreeNode(currentNode).left <> 0 Then 'if there is a node to the left
ConstructTree(TreeNode(currentNode).left, leftX, (leftX + rightX) / 2, nodes(currentNode).posY, bottomY)
End If
If TreeNode(currentNode).right <> 0 Then 'if there is a node to the right
ConstructTree(TreeNode(currentNode).right, (leftX + rightX) / 2, rightX, nodes(currentNode).posY, bottomY) 'swaps the left and right x-coords which have been changed
End If
End Sub
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
If draw = True Then
For i = 1 To treeCounter
nodes(i).draw(e)
Next
'ALSO need to draw lines between the nodes, but IGNORE FOR NOW
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
TextBox1.Text = myTime - (0.1)
myTime = TextBox1.Text
If myTime = 0 Then
Timer1.Enabled = False
MsgBox("Time is up!")
checkupdate()
resetForm()
End If
'add another if statement checking for two wrong answers, will stop the timer and tell the user that they have got too man questions wrong'
End Sub
Sub resetForm()
Score.Text = "Score:"
Label1.Text = ""
scoreValue = 0
End Sub
Sub writefile()
FileOpen(1, "BTTscores.txt", OpenMode.Output)
Select Case updating
Case True
For i = 2 To 11
WriteLine(1, scores(i))
Next
Case False
For i = 1 To numberOfScores + 1
WriteLine(1, scores(i))
Next
End Select
FileClose()
End Sub
Sub checkupdate()
'need to check whether there are already ten elements in the array. If so, then delete the first score, move all the indices of the other scores 1 to the left and add the new scores on the end'
numberOfScores = 0 'will need to be reset if the user carries on using the program'
FileOpen(1, "BTTscores.txt", OpenMode.Input) 'need to bubble sort values'
Dim line As String
Do Until EOF(1)
line = LineInput(1)
If line <> "" Then
numberOfScores = numberOfScores + 1
scores(numberOfScores) = line 'copies the line to the array'
End If
Loop
If numberOfScores = 10 Then 'if one needs to be updated, need to read all but the first line into the array'
updating = True
scores(11) = scoreValue
Else 'if there are less than 10 scores, the user's current score just needs to be added on the end'
updating = False
scores(numberOfScores + 1) = scoreValue
End If
FileClose(1)
writefile()
End Sub
Private Sub EnterButton_Click(sender As Object, e As EventArgs) Handles EnterButton.Click
userAnswer = Answer.Text
If actualAnswer.Replace(" ", "") = userAnswer.Replace(" ", "") Then
UpdateScore()
End If
Score.Text = ("Score: " & scoreValue)
Answer.Text = ""
InitialSetup()
End Sub
Sub UpdateScore()
Select Case difficulty
Case "Easy"
scoreValue = scoreValue + 10
Case "Medium"
scoreValue = scoreValue + 15
Case "Hard"
scoreValue = scoreValue + 20
End Select
End Sub
Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
scoreValue = 0
Initialisation()
InitialSetup()
myTime = 60
Timer1.Enabled = True
End Sub
Sub InitialSetup()
Dim currentNode As Integer = 1 'will be root node'
actualAnswer = ""
GetEquation()
newLabel = ""
selectedTraversal = traversal(CInt(Math.Floor((3 - 1 + 1) * Rnd())) + 1) 'will choose a random traversal'
newLabel = "Traversal: " + selectedTraversal
Label1.Text = newLabel
If selectedTraversal = "Prefix" Then
PrefixConversion(currentNode)
ElseIf selectedTraversal = "Infix" Then
InfixConversion()
Else
RPConversion()
End If
DrawTree()
End Sub
Sub Initialisation()
operators(1) = "("
operators(2) = "-"
operators(3) = "+"
operators(4) = "*"
operators(5) = "/"
operators(6) = ")"
traversal(1) = "Prefix"
traversal(2) = "Infix"
traversal(3) = "Postfix"
End Sub
Sub GetEquation()
Select Case difficulty
'RANDOM NUMBER FORMAT: CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound'
Case "Easy"
'FORMAT: 17 * 4'
treeCounter = 3
ogEquation(1) = CInt(Math.Floor((20 - 1 + 1) * Rnd())) + 1
ogEquation(2) = operators(CInt(Math.Floor((5 - 2 + 1) * Rnd())) + 2)
ogEquation(3) = CInt(Math.Floor((20 - 1 + 1) * Rnd())) + 1
'initialising the binary tree iteration'
TreeNode(1).name = ogEquation(2) 'operator is the root'
TreeNode(1).left = 2
TreeNode(1).right = 3
TreeNode(2).name = ogEquation(1)
TreeNode(3).name = ogEquation(3)
'EG: * 17 4
Case "Medium"
treeCounter = 5
'FORMAT: 15 * (17 + 4)'
ogEquation(1) = CInt(Math.Floor((50 - 1 + 1) * Rnd())) + 1
ogEquation(2) = operators(CInt(Math.Floor((5 - 2 + 1) * Rnd())) + 2)
ogEquation(3) = operators(1)
ogEquation(4) = CInt(Math.Floor((50 - 1 + 1) * Rnd())) + 1
ogEquation(5) = operators(CInt(Math.Floor((5 - 2 + 1) * Rnd())) + 2)
ogEquation(6) = CInt(Math.Floor((50 - 1 + 1) * Rnd())) + 1
ogEquation(7) = operators(6)
'initialising the binary tree iteration'
TreeNode(1).name = ogEquation(2) 'root node'
TreeNode(1).left = 2
TreeNode(1).right = 3
TreeNode(2).name = ogEquation(1)
TreeNode(3).name = ogEquation(5)
TreeNode(3).left = 4
TreeNode(3).right = 5
TreeNode(4).name = ogEquation(4)
TreeNode(5).name = ogEquation(6)
'EG: * 15 + 17 4
Case "Hard"
'FORMAT: (17 + 4) * (20 / 10), random numbers are 1-150'
treeCounter = 7
ogEquation(1) = operators(1)
ogEquation(2) = CInt(Math.Floor((150 - 1 + 1) * Rnd())) + 1
ogEquation(3) = operators(CInt(Math.Floor((5 - 2 + 1) * Rnd())) + 2)
ogEquation(4) = CInt(Math.Floor((150 - 1 + 1) * Rnd())) + 1
ogEquation(5) = operators(6)
ogEquation(6) = operators(CInt(Math.Floor((5 - 2 + 1) * Rnd())) + 2)
ogEquation(7) = operators(1)
ogEquation(8) = CInt(Math.Floor((150 - 1 + 1) * Rnd())) + 1
ogEquation(9) = operators(CInt(Math.Floor((5 - 2 + 1) * Rnd())) + 2)
ogEquation(10) = CInt(Math.Floor((150 - 1 + 1) * Rnd())) + 1
ogEquation(11) = operators(6)
'initialising the binary tree iteration'
TreeNode(1).name = ogEquation(6) 'root node'
TreeNode(1).left = 2
TreeNode(1).right = 5
TreeNode(2).name = ogEquation(3)
TreeNode(2).left = 3
TreeNode(2).right = 4
TreeNode(3).name = ogEquation(2)
TreeNode(4).name = ogEquation(4)
TreeNode(5).name = ogEquation(9)
TreeNode(5).left = 6
TreeNode(5).right = 7
TreeNode(6).name = ogEquation(8)
TreeNode(7).name = ogEquation(10)
'EG: * + 17 4 / 20 10
End Select
End Sub
'Traversal Solutions'
'Postfix Conversion'
Sub RPConversion()
Dim myStack As New Stack(15)
Dim empty As Boolean = True
Dim temp As String 'used to store the current part of the original equation'
Dim operatorNum As Integer
Dim peekNum As Integer
Dim stoploop As Boolean = True
For i = 1 To ogEquation.Count - 1 'will iterate through the total number of elements in the array ogEquation'
If myStack.Count = 0 Then empty = True
temp = ogEquation(i)
MatchTempOperation(myStack, temp, operatorNum)
If operatorNum > 1 And operatorNum < 6 Then 'if the value is an operator'
If myStack.Count <> 0 Then 'if the stack contains a value'
CheckPeek(myStack, peekNum)
If operatorNum > peekNum Then
myStack.Push(temp)
ElseIf operatorNum = peekNum Then
actualAnswer = actualAnswer + myStack.Pop()
myStack.Push(temp)
Else 'operatorNum < peekNum'
actualAnswer = actualAnswer + myStack.Pop()
Do
stoploop = True
CheckPeek(myStack, peekNum)
If operatorNum > peekNum Then
myStack.Push(temp)
ElseIf operatorNum = peekNum Then
actualAnswer = actualAnswer + myStack.Pop()
myStack.Push(temp)
Else
actualAnswer = actualAnswer + myStack.Pop()
stoploop = False
End If
Loop Until stoploop Or myStack.Count = 0
End If
Else
myStack.Push(temp)
End If
ElseIf temp = "(" Then
myStack.Push(temp)
ElseIf temp = ")" Then
Do
actualAnswer = actualAnswer + myStack.Pop()
Loop Until myStack.Peek() = "("
myStack.Pop()
Else
actualAnswer = actualAnswer + temp
End If
operatorNum = 0
Next
If myStack.Count > 0 Then
For i = 1 To myStack.Count
actualAnswer = actualAnswer + myStack.Pop()
Next
End If
End Sub
Sub CheckPeek(ByVal myStack As Stack, ByRef peekNum As Integer) 'does the same as MatchTempOperation but for the top of the stack'
For i = 2 To 5 'skip one and six because we know it isn't a left or right bracket'
If myStack.Peek() = operators(i) Then
peekNum = i
End If
Next
End Sub
Sub MatchTempOperation(ByVal myStack As Stack, ByVal temp As String, ByRef operatorNum As Integer) 'wants to look at the stack but not be able to change it'
For i = 1 To 6
If temp = operators(i) Then
operatorNum = i
End If
Next
End Sub
'Infix'
Sub InfixConversion()
For i = 1 To 11
'check each element for empty spaces / brackets'
If ogEquation(i) <> "" And ogEquation(i) <> "(" And ogEquation(i) <> ")" Then
actualAnswer = actualAnswer + ogEquation(i)
End If
Next
End Sub
'Prefix'
Sub PrefixConversion(ByRef currentNode As Integer)
actualAnswer = actualAnswer + TreeNode(currentNode).name
If TreeNode(currentNode).left <> 0 Then
PrefixConversion(TreeNode(currentNode).left)
End If
If TreeNode(currentNode).right <> 0 Then
PrefixConversion(TreeNode(currentNode).right)
End If
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Hide()
End Sub
End Class
Apologies for it's inefficiency, please also note that the "difficulty" variable is Public and stored outside of this form. Thanks :)
OUTPUT:
enter image description here
As you can see, the root node is far off centre in the bottom left.

Related

Change subitem backcolor of a listview next item

I have a listview filled with SRT subtitle. I'am trying to change listview color based on subtitle errors. Everything is working fine, but color won't change when subtitles is overlapping. I take end-time of one subtitle and start-time of next subtitle. Based on difference, it decide is there overlapping or not. Calculations are OK but backcolor and forecolor won't change. It does change backcolor for current item but I need to change backcolor for next listview item.
'EXAMPLE #######################################
For i as integer = 0 to listview1.items.count -1
ListView1.Items(i).UseItemStyleForSubItems = False
'this is working #######
ListView1.Items.Item(i).SubItems(1).BackColor = ColorTranslator.FromHtml("#F0A6A7")
'but this is NOT working ( THIS IS WHAT I NEED) ####################
ListView1.Items.Item(i).SubItems(i + 1).BackColor = ColorTranslator.FromHtml("#F0A6A7")
Next i
'########################################################
Public Function Color_Errors(ByVal SubtitleListView As ListView)
For i = 0 To SubtitleListView.Items.Count - 2
SubtitleListView.Items(i).UseItemStyleForSubItems = False
SubtitleListView.Items(i + 1).UseItemStyleForSubItems = False
SubtitleListView.Items.Item(i).SubItems(1).ResetStyle()
SubtitleListView.Items.Item(i).SubItems(2).ResetStyle()
SubtitleListView.Items.Item(i).SubItems(3).ResetStyle()
SubtitleListView.Items.Item(i).SubItems(4).ResetStyle()
SubtitleListView.Items.Item(i).SubItems(5).ResetStyle()
Dim Text As String = SubtitleListView.Items.Item(i + 1).SubItems(5).Text
Dim TextLength As Integer = Get_Longest_Line_Length(Text)
Dim NumberOfLines As Integer = Split(Text, "|").Length
Dim Duration As Double = Convert_Time_to_Milliseconds(SubtitleListView.Items.Item(i).SubItems(4).Text)
Dim Pause As Double = Convert_Time_to_Milliseconds(SubtitleListView.Items.Item(i).SubItems(1).Text)
Dim _Start As Double = Convert_Time_to_Milliseconds(SubtitleListView.Items.Item(i).SubItems(2).Text)
Dim _End As Double = Convert_Time_to_Milliseconds(SubtitleListView.Items.Item(i).SubItems(3).Text)
Dim _NextStart As Double
If i < (SubtitleListView.Items.Count - 1) Then
_NextStart = Convert_TimeSpan_to_Milliseconds(SubtitleListView.Items.Item(i + 1).SubItems(2).Text)
End If
'TOO LONG LINES
If TextLength > MaxLength Then
SubtitleListView.Items.Item(i).SubItems(5).BackColor = ColorTranslator.FromHtml("#F0A6A7")
SubtitleListView.Items.Item(i).SubItems(5).ForeColor = Color.Black
End If
'TOO LONG DURATION
If Duration > 6000 Then
SubtitleListView.Items.Item(i).SubItems(4).BackColor = ColorTranslator.FromHtml("#F5CBD9")
SubtitleListView.Items.Item(i).SubItems(4).ForeColor = ColorTranslator.FromHtml("#6F0021")
SubtitleListView.Items.Item(i).SubItems(3).BackColor = ColorTranslator.FromHtml("#F5CBD9")
SubtitleListView.Items.Item(i).SubItems(3).ForeColor = ColorTranslator.FromHtml("#6F0021")
'SHORTER THAN 2 SECONDS
ElseIf Duration < 2000 AndAlso Duration >= 700 Then
SubtitleListView.Items.Item(i).SubItems(4).BackColor = Color.Red
SubtitleListView.Items.Item(i).SubItems(4).ForeColor = Color.White
'TOO SHORT DURATION
ElseIf Duration < 700 Then
SubtitleListView.Items.Item(i).SubItems(3).BackColor = ColorTranslator.FromHtml("#FFF0E1")
SubtitleListView.Items.Item(i).SubItems(3).ForeColor = ColorTranslator.FromHtml("#A45200")
SubtitleListView.Items.Item(i).SubItems(4).BackColor = ColorTranslator.FromHtml("#FFF0E1")
SubtitleListView.Items.Item(i).SubItems(4).ForeColor = ColorTranslator.FromHtml("#A45200")
End If
''TOO SHORT PAUSE
If Pause < 200 Then
SubtitleListView.Items.Item(i).SubItems(1).BackColor = ColorTranslator.FromHtml("#ACC9E6")
SubtitleListView.Items.Item(i).SubItems(1).ForeColor = Color.Black
SubtitleListView.Items.Item(i).SubItems(2).BackColor = ColorTranslator.FromHtml("#ACC9E6")
SubtitleListView.Items.Item(i).SubItems(2).ForeColor = Color.Black
End If
If NumberOfLines > 2 Then
SubtitleListView.Items.Item(i).SubItems(5).ForeColor = ColorTranslator.FromHtml("#0000FF")
End If
'ERROR PART #################################################
If i < (SubtitleListView.Items.Count - 1) Then
If _End > _NextStart Then
SubtitleListView.Items.Item(i + 1).SubItems(1).BackColor = ColorTranslator.FromHtml("#BB0025")
SubtitleListView.Items.Item(i + 1).SubItems(1).ForeColor = Color.White
SubtitleListView.Items.Item(i).SubItems(2).BackColor = ColorTranslator.FromHtml("#BB0025")
SubtitleListView.Items.Item(i).SubItems(2).ForeColor = Color.White
End If
End If
'############################################################
Next i
Return Nothing
End Function
Public Function Convert_Time_to_Milliseconds(ByVal Time As String)
If Time.Contains(":") = True Then
Dim VremePrviDeo() As String = Split(Time, ":")
If VremePrviDeo.Length = 3 Then
Dim Sati As Integer = VremePrviDeo(0) * 60 * 60 * 1000
Dim Minuti As Integer = VremePrviDeo(1) * 60 * 1000
Dim VremeDrugiDeo() As String = Split(VremePrviDeo(2), ",")
Dim Sekunde As Integer = VremeDrugiDeo(0) * 1000
Dim Milisekunde As Integer = VremeDrugiDeo(1)
Dim Miliseconds As Double = Sati + Minuti + Sekunde + Milisekunde
Return Miliseconds.ToString
ElseIf VremePrviDeo.Length = 2 Then
Dim Minuti As Integer = VremePrviDeo(0) * 60 * 1000
Dim VremeDrugiDeo() As String = Split(VremePrviDeo(2), ",")
Dim Sekunde As Integer = VremeDrugiDeo(0) * 1000
Dim Milisekunde As Integer = VremeDrugiDeo(1)
Dim Miliseconds As Double = Minuti + Sekunde + Milisekunde
Return Miliseconds.ToString
End If
Else
Dim VremePrviDeo() As String = Split(Time, ",")
Dim Sekunde As Integer = VremePrviDeo(0) * 1000
Dim Milisekunde As Integer = VremePrviDeo(1)
Dim Miliseconds As Double = Sekunde + Milisekunde
Return Miliseconds.ToString
End If
Return Nothing
End Function
Public Function Get_Longest_Line_Length(ByVal Text As String)
Dim Duzina As Integer = 0
For Each line As String In Split(Text, "|")
If line.Length > Duzina Then
Duzina = line.Length
End If
Next
Return Duzina
End Function
Public Function Convert_TimeSpan_to_Milliseconds(ByVal Time As String)
'Try
Dim Parsed() As String = Parse_String_to_TimeSpan(Time)
Dim Sat As Double = TimeSpan.FromHours(Parsed(0)).TotalMilliseconds
Dim Minut As Double = TimeSpan.FromMinutes(Parsed(1)).TotalMilliseconds
Dim Sekunda As Double = TimeSpan.FromSeconds(Parsed(2)).TotalMilliseconds
Dim Milisekunda As Double = TimeSpan.FromMilliseconds(Parsed(3)).TotalMilliseconds
Dim TotalTime As Double = Sat + Minut + Sekunda + Milisekunda
Return TotalTime
'Catch ex As Exception
'End Try
'Return Nothing
End Function

Blackjack: Won't add Dealer's Hand

I have a problem with my blackjack game in vb.net. This code I have will add the player's score perfectly, but when it comes to the dealer's score, it will not. It only takes the second card that the dealer has.
It is called with this:
addScore("p") 'add player's score
addScore("d") 'add dealer's score
And this is "addScore()":
Public Function card(player As String, index As Integer) As Label
Try
If player = "p" Then
Return GroupBox1.Controls.OfType(Of Label).Where(Function(l) l.Name = "YouCard" & index.ToString()).Single()
ElseIf player = "d" Then
Return GroupBox1.Controls.OfType(Of Label).Where(Function(l) l.Name = "DealerCard" & index.ToString()).Single()
End If
Catch
Return Nothing
End Try
End Function
Public Sub addScore(ByVal player As String)
Dim currScore As Integer
Dim result As Integer = 0
'Add Score
For value As Integer = 1 To 7
If card(player, value).Text = "A" AndAlso (currScore + 11) <= 21 Then
result = currScore + 11
ElseIf card(player, value).Text = "A" AndAlso (currScore + 1) <= 22 Then
result = currScore + 1
ElseIf IsNumeric(card(player, value).Text) Then
result = currScore + CInt(card(player, value).Text)
ElseIf card(player, value).Text = "" Then
result = result
Else
result = currScore + 10
End If
If player = "p" Then
YouScore.Text = result
Else
DealerScore.Text = result
End If
Next
End Sub
currScore shouldn't be there. Replace it with result
Public Sub addScore(ByVal player As String)
Dim result As Integer = 0
'Add Score
For value As Integer = 1 To 7
If card(player, value).Text = "A" AndAlso (result + 11) <= 21 Then
result = result + 11
ElseIf card(player, value).Text = "A" AndAlso (result + 1) <= 22 Then
result = result + 1
ElseIf IsNumeric(card(player, value).Text) Then
result = result + CInt(card(player, value).Text)
ElseIf card(player, value).Text = "" Then
result = result
Else
result = result + 10
End If
If player = "p" Then
YouScore.Text = result
Else
DealerScore.Text = result
End If
Next
End Sub

Memory Game Help! How to show the unpaired cards

Showing the paired cards on my memory game is working fine. But the problem is I can't show the unpaired cards. There are 20 cards on my game.
Dim paircount As Integer = 0
Dim unpaircount As Integer
Dim Card1 As Integer = 0
Dim Card2 As Integer = 0
Dim Card1pic As Integer = 0
Dim Card2pic As Integer = 0
Dim Score As Integer = 0
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
st = st + 1
Label3.Text = "Time : " & st & " seconds"
Label7.Text = "Pairs : " & paircount
If paircount = 19 And Card1 <> 0 And Card2 <> 0 Then
paircount = paircount + 1
victory()
Label32.Text = "Unpaired : 20" & unpaircount 'This is my code for showing the unpaired card & and it's not working
If unpaircount = 19 And Card1 = 0 And Card2 = 0 Then
unpaircount = unpaircount - paircount
End If
End If
End Sub
'[Begin]Declare Object/Value'
Dim paircount As Integer = 0
Dim unpaircount As Integer
Dim Card1 As Integer = 0
Dim Card2 As Integer = 0
Dim Card1pic As Integer = 0
Dim Card2pic As Integer = 0
Dim Score As Integer = 0
'[End]Declare Object/Value'
'[Begin]Tick handles'
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
st = st + 1
Label3.Text = "Time : " & st & " seconds" ' Default As 1, in your code'
Label7.Text = "Pairs : " & paircount ' Default As 0, in your code'
If paircount = 19 And Card1 <> 0 And Card2 <> 0 Then ' Card1 & 2 default as 0, return False'
paircount = paircount + 1 ' paircount is 20
victory() ' your function or sub'
Label32.Text = "Unpaired : 20" & unpaircount 'Default as null, return 0: Unpaired: 200'
If unpaircount = 19 And Card1 = 0 And Card2 = 0 Then 'unpaircount = 0, will not be active this checking, please make sure your code will change the unpaircount value before this checking'
unpaircount = unpaircount - paircount
End If
End If
End Sub
'[End]Tick handles'
As your code provide by yourself, for first of the checking under
'If paircount = 19 And Card1 <> 0 And Card2 <> 0 Then'
Is any way to change paircound/card1/card2?
If not, that mean the checking will not be accept and for my view,
I think your code was successful display the result: no change, no display
Best Regards,
KT

Calling the same function with different functions called inside

I hope my title is clear. Let me explain. I have 4 buttons that do pretty much the same.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
LimiteGlobalSeparador = InputBox("Introduzca la distancia máxima entre huecos en el tubo", "Cuadro de Datos, Separaciones", "")
Dim a, b, c, d, f, g As New Label
Dim o, p, q, r, s, t As New Label
a.Text = "Medida del Tubo"
b.Text = "Espacio 1"
c.Text = "Espacio 2"
d.Text = "Espacio 3"
f.Text = "Espacio 4"
g.Text = "Espacio 5"
For i = 0 To 5
TableLayoutPanel1.Controls.Add(a, 0, i)
Next
If TextBox1.Text <> 0 Then
For j = 1 To Int(TextBox1.Text)
Dim x As New List(Of Decimal)
x = MedTuboFuncPCT()
For i = 0 To x.Count - 1
Dim lbl As New Label
lbl.Text = Math.Round(x(i), 2)
TableLayoutPanel1.Controls.Add(lbl, j, i)
Next
ContadorGlobal = ContadorGlobal + 1
Next
Else
End If
ContadorGlobal = 0
Dim h As Integer
h = Int(TextBox2.Text - TextBox1.Text)
If TextBox2.Text <> 0 Then
If h = Int(TextBox2.Text) Then
For j = 1 To Int(TextBox2.Text)
Dim x As New List(Of Decimal)
x = MedTuboFunCTCT()
For i = 0 To x.Count - 1
Dim lbl As New Label
lbl.Text = Math.Round(x(i), 2)
TableLayoutPanel1.Controls.Add(lbl, j, i)
Next
ContadorGlobal = ContadorGlobal + 1
Next
Else
ContadorGlobal = 0
For j = Int(1) + Int(TextBox1.Text) To (Int(TextBox1.Text) + Int(TextBox2.Text))
Dim x As New List(Of Decimal)
x = MedTuboFunCTCT()
For i = 0 To x.Count - 1
Dim lbl As New Label
lbl.Text = Math.Round(x(i), 2)
TableLayoutPanel1.Controls.Add(lbl, j, i)
Next
ContadorGlobal = ContadorGlobal + 1
Next
End If
End If
ContadorGlobal = 0
If TextBox3.Text <> 0 Then
Dim x As New List(Of Decimal)
x = MedTuboFuncPP()
For i = 0 To x.Count - 1
Dim lbl As New Label
lbl.Text = Math.Round(x(i), 2)
TableLayoutPanel1.Controls.Add(lbl, 1, i)
Next
End If
If Te180 > 0 Then
o.Text = "Medida del Tubo"
p.Text = "Espacio 1"
q.Text = "Espacio 2"
r.Text = "Espacio 3"
s.Text = "Espacio 4"
t.Text = "Espacio 5"
For i = 6 To 11
TableLayoutPanel1.Controls.Add(o, 0, i)
Next
End If
End Sub
So I'm trying to create a Sub and then each button call that sub, so I don't have repeating code in each button like I have now. The only change is here:
One button calls this function. x = MedTuboFuncPCT().
Another one calls x = MedTuboFuncPCTVid()
Another one calls x = MedTuboFuncPCTVidBB()
I don't know how to make a Sub in which I can make this difference. Hope I'm clear enough. Thanks in advance.
Create your function and send a value in it so you can change the x function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
VFunction = 1
RepeatedCode(VFunction)
End Sub
On Button2 VFunction = 2 and so on. Then create your function.
Public Sub RepeatedCode (ByVal VFunction as integer)
If VFunction = 1 Then
x = MedTuboFuncPCT()
ElseIf VFunction = 2 Then
x = MedTuboFuncPCTVid()
ElseIf VFunction = 3 Then
x = MedTuboFuncPCT()
End If
'The Rest of your code
I belive the If condition must be placed inside your If TextBox1.Text <> 0
Since it its the only place where I see you used one of the Functions you mentioned

Snakes and ladders Vb.net [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Form 2 is to enter ladder base and its off set value and for snakes where the snake head is and skakes off set value.
Not able to figure out why its not working . When the values are entered to show simulation it show's up error sandl is private and the other one is the validation one .
Public Class Form2
Dim sandl(99) As Integer
Dim snakeshead As TextBox()
Dim snakesoffset As TextBox()
Dim ladderfoot As TextBox()
Dim ladderoffset As TextBox()
Dim rnd As Random = New Random
Sub initialise()
For i = 0 To 99
sandl(i) = 0 ' reset data
Next
End Sub
Sub snake()
snakeshead = {txthead1, txthead2, txthead3, txthead4, txthead5, txthead6, txthead7, txthead8, txthead9, txthead10}
snakesoffset = {txtoffset1, txtoffset2, txtoffset3, txtoffset4, txtoffset5, txtoffset6, txtoffset7, txtoffset8, txtoffset9, txtoffset10}
' SnakeHead(i).Text = (i + 81).ToString
' SnakeOffset(i).Text = "10" '(i + 10).ToString
For i As Integer = 0 To 9
While True
Dim base = rnd.Next(90) + 11
If sandl(base - 1) <> 0 Then
Continue While
End If
Dim offset = rnd.Next(20) + 10
If base - offset < 1 Then
Continue While
End If
snakeshead(i).Text = base.ToString
snakesoffset(i).Text = offset.ToString
sandl(base - 1) = -offset
Exit While
End While
Next
End Sub
Sub ladders()
ladderfoot = {txtladder1, txtladder2, txtladder3, txtladder4, txtladder5, txtladder6, txtladder7, txtladder8, txtladder9, txtladder10}
ladderoffset = {txtladderoffset1, txtladderoffset2, txtladderoffset3, txtladderoffset4, txtladderoffset5, txtladderoffset6, txtladderoffset7, txtladderoffset8, txtladderoffset9, txtladderoffset10}
'For i As Integer = 0 To 9
' LadderFoot(i).Text = (i + 11).ToString
' LadderOffset(i).Text = "10"
For i As Integer = 0 To 99
sandl(i) = 0 'reset data
Next
For i As Integer = 0 To 9
While True
Dim base = rnd.Next(90) + 1
If sandl(base - 1) <> 0 Then
Continue While
End If
Dim offset = rnd.Next(20) + 10
If base + offset > 100 Then
Continue While
End If
ladderfoot(i).Text = base.ToString
ladderoffset(i).Text = offset.ToString
sandl(base - 1) = offset
Exit While
End While
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 99
sandl(i) = 0 'reset data
Next
Dim valid = Validate(ladderfoot, ladderoffset, +1, "Ladder")
If (valid) Then
valid = Validate(snakeshead, snakesoffset, -1, "Snake")
End If
If (valid) Then
'Form3 = New Form3
Form3.ShowDialog()
End If
End Sub
Private Function Validate(tbBase() As TextBox, tbOffset() As TextBox, delta As Integer, s As String) As Boolean
For i As Integer = 0 To 9
Dim base As Integer
If ((Not Integer.TryParse(tbBase(i).Text.Trim(), base)) OrElse (base < 1) OrElse (base > 100) OrElse (sandl(base - 1) <> 0)) Then
MessageBox.Show(s & (i + 1).ToString() & " base is invalid.")
tbBase(i).Select()
tbBase(i).SelectAll()
Return False
End If
base -= 1 'zero based
Dim offset As Integer
If ((Not Integer.TryParse(tbOffset(i).Text.Trim(), offset)) OrElse (offset < 10) OrElse (offset > 30) OrElse (base + offset * delta < 0) OrElse (base + offset * delta >= 100)) Then
MessageBox.Show(s & (i + 1).ToString() & " offset is invalid.")
tbOffset(i).Select()
tbOffset(i).SelectAll()
Return False
End If
sandl(base) = offset * delta 'write offset
Next
Return True
End Function
End Class
Public Class Form3
Enum EState
Dice
Move
Slide
Wait
Win
End Enum
Dim Fnt = New Font("Arial", 16)
Dim FntBig = New Font("Arial", 256)
Dim Frame As Integer = -1 'counter
Dim State = EState.Dice
Dim Rnd As Random = New Random
Dim Dice As Integer
Dim Pos As Point = New Point(32, 640 + 32)
Dim CurrentIndex As Integer = -1
Dim NextIndex As Integer
Dim TargetIndex As Integer
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dice = 0
Frame = -1
State = EState.Dice
Pos = New Point(32, 640 + 32)
CurrentIndex = -1
End Sub
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
DrawBackground(e.Graphics)
Frame += 1
Dim oldState = State
Select Case State
Case EState.Dice
If Frame = 0 Then
Dice = Rnd.Next(6) + 1 'roll dice
TargetIndex = CurrentIndex + Dice
NextIndex = CurrentIndex
ElseIf Frame >= 63 Then
If CurrentIndex + Dice < 100 Then
State = EState.Move 'valid dice
Else
State = EState.Wait 'invalid dice
End If
Dice = 0
End If
Case EState.Move
If Frame Mod 64 = 0 Then
CurrentIndex = NextIndex
If CurrentIndex = TargetIndex Then
If CurrentIndex < 99 Then 'not win
If Form2.sandl(CurrentIndex) <> 0 Then
State = EState.Slide 'snake or ladder
Else
State = EState.Dice 'empty tile
End If
TargetIndex = CurrentIndex + Form2.sandl(CurrentIndex)
Else
State = EState.Win 'win
End If
Else
NextIndex = CurrentIndex + 1 'move
End If
Else
Dim c = GetCoordinate(CurrentIndex)
Dim n = GetCoordinate(NextIndex)
Dim dx = (n.X - c.X)
Dim dy = (n.Y - c.Y)
Pos.X = c.X * 64 + (dx * (Frame Mod 64)) + 32
Pos.Y = c.Y * 64 + (dy * (Frame Mod 64)) + 32
End If
Case EState.Slide
If Frame >= 63 Then
CurrentIndex = TargetIndex
If CurrentIndex < 99 Then
State = EState.Dice 'not win
Else
State = EState.Win 'win
End If
Else
Dim c = GetCoordinate(CurrentIndex)
Dim n = GetCoordinate(TargetIndex)
Dim dx = (n.X - c.X)
Dim dy = (n.Y - c.Y)
Pos.X = c.X * 64 + (dx * (Frame Mod 64)) + 32
Pos.Y = c.Y * 64 + (dy * (Frame Mod 64)) + 32
End If
Case EState.Wait
If Frame >= 63 Then
State = EState.Dice
End If
End Select
e.Graphics.FillEllipse(Brushes.Blue, Pos.X - 16, Pos.Y - 16, 32, 32) 'draw player
If Dice > 0 Then
Dim size = e.Graphics.MeasureString(Dice.ToString, FntBig)
e.Graphics.DrawString(Dice.ToString, FntBig, Brushes.Black, 320 - size.Width / 2, 320 - size.Height / 2) 'print dice
End If
If State <> oldState Then
Frame = -1 'reset counter
End If
If State <> EState.Win Then
PictureBox1.Invalidate() 'schedule next paint
End If
End Sub
Private Sub DrawBackground(g As Graphics)
For y As Integer = 0 To 9
For x As Integer = 0 To 9
If (((x + y) Mod 2) = 0) Then
g.FillRectangle(Brushes.LightGray, x * 64, y * 64, 64, 64) 'dark rectangle
End If
Dim z = (9 - y) * 10 + x + 1
If y Mod 2 = 0 Then
z = (9 - y) * 10 + (9 - x) + 1
End If
g.DrawString(z.ToString, Fnt, Brushes.Black, x * 64, y * 64) 'number
Next
Next
For i As Integer = 0 To 99
If Form2.sandl(i) <> 0 Then
Dim base = GetCoordinate(i)
Dim offset = GetCoordinate(i + Form2.sandl(i))
If Form2.sandl(i) > 0 Then 'ladder
Dim delta = Math.Abs(base.X - offset.X) + 4
g.DrawLine(Pens.Green, base.X * 64 + 32 - delta, base.Y * 64 + 32, offset.X * 64 + 32 - delta, offset.Y * 64 + 32) 'left part
g.DrawLine(Pens.Green, base.X * 64 + 32 + delta, base.Y * 64 + 32, offset.X * 64 + 32 + delta, offset.Y * 64 + 32) 'right part
Else 'snake
g.DrawLine(Pens.Red, base.X * 64 + 32, base.Y * 64 + 32, offset.X * 64 + 32, offset.Y * 64 + 32) 'red line
End If
End If
Next
End Sub
Private Function GetCoordinate(i As Integer) As Point
Dim result As Point
result.Y = 9 - (i \ 10)
result.X = i Mod 10
If result.Y Mod 2 = 0 Then
result.X = 9 - result.X
End If
Return result
End Function
End Class
In Form2, change your declaration from
Dim sandl(99) As Integer
to
Public sandl(99) As Integer
This would allow Form3 to access your integer array
Rename your Validate method to something else, like ValidateTextBoxes, or if you intend to overload the base.Validate, then declare as
Private Overloads Function Validate