Math Game - How to making 10 Question as a ROUND - vb.net

I am making a Math quiz game and I wondering why the question does not change to a NEW ONE when I get the right answer and HOW to make it to 10 and stop running then jump out a message box to ask the user want to PLAY AGAIN or not?
Public Class Multiplication
Dim TotalQuestion As Integer
Dim CorrectAnswer As Integer
Dim WrongAnswer As Integer
Dim R As New Random
Dim numOne As Integer = R.Next(0, 10)
Dim numTwo As Integer = R.Next(1, 10)
Dim Ans As Integer = 0
Dim Tries As Integer = 0
Private Sub Multiplication_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Generate()
End Sub
Sub Generate()
TotalQuestion = TotalQuestion + 1
Dim Show As String
Show = numOne & " x " & numTwo & " = "
lblQuestionMUL.Text = Show
End Sub
Private Function Multiply(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Return num1 * num2
Generate()
End Function
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Integer.TryParse(lblQuestionMUL.Text, numOne & numTwo)
Ans = Multiply(numOne, numTwo)
If Val(txtAnswer.Text) = Ans Then
CorrectAnswer = CorrectAnswer + 1
Else
WrongAnswer = WrongAnswer + 1
End If
lblCorrectAns.Text = CorrectAnswer
lblWrongAns.Text = WrongAnswer
txtAnswer.Clear()
txtAnswer.Focus()
Generate()
End Sub
End Class

In addition to previous comments you should set the numOne and numTwo variables to random numbers in Generate Sub (Keeping the declaration as Global Variables). Your code just set them in the beginning to random numbers only once. Check the code below:
Public Class Multiplication
Dim TotalQuestion As Integer = 0
Dim CorrectAnswer As Integer
Dim WrongAnswer As Integer
Dim R As New Random
Dim NumOne As Integer
Dim NumTwo As Integer
Dim QuizCompleted As Boolean = False
Dim Ans As Integer = 0
Dim Tries As Integer = 0
Private Sub Multiplication_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Generate()
End Sub
Sub Generate()
If TotalQuestion < 10 Then
NumOne = R.Next(0, 10)
NumTwo = R.Next(1, 10)
TotalQuestion = TotalQuestion + 1
Dim Show As String
Show = NumOne & " x " & NumTwo & " = "
lblQuestionMUL.Text = Show
Else
QuizCompleted = True
End If
End Sub
Private Function Multiply(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Generate()
Return num1 * num2
End Function
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Integer.TryParse(lblQuestionMUL.Text, NumOne & NumTwo)
Ans = Multiply(NumOne, NumTwo)
If Val(txtAnswer.Text) = Ans Then
CorrectAnswer = CorrectAnswer + 1
Else
WrongAnswer = WrongAnswer + 1
End If
lblCorrectAns.Text = CorrectAnswer
lblWrongAns.Text = WrongAnswer
txtAnswer.Clear()
txtAnswer.Focus()
If QuizCompleted Then
MsgBox("Quiz Completed")
End If
End Sub
End Class

Related

How to get selected items from checked list box and compute their total

Here's the image of my design interface:Design Interface
I want the user to make a selection and enter the quantity they wish to purchase then once they are done and press calculate, it gives the total of the items selected according to the quantity entered and inputs that total in the price textboxes.
Here's my code...
I am stuck...
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Public Sub frmDrinks_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim tMango As Integer
Dim tOrange As Integer
Dim tStrawberry As Integer
Dim tWatermelon As Integer
Dim tMinty As Integer
Dim tCoke As Integer
Dim tDiet As Integer
Dim tSprite As Integer
Dim tMineral As Integer
Dim tSpark As Integer
Dim tManSmooth As Integer
Dim tBanSmooth As Integer
Dim tTropSmooth As Integer
Dim tStrawSmooth As Integer
Dim tVanilla As Integer
Dim tCookie As Integer
Dim tManShake As Integer
Dim tBanShake As Integer
tMango = txtMango.Text
tOrange = txtOrange.Text
tStrawberry = txtStrawberry.Text
tWatermelon = txtWatermelon.Text
tMinty = txtMinty.Text
tCoke = txtCoke.Text
tDiet = txtDiet.Text
tSprite = txtSprite.Text
tMineral = txtMineral.Text
tSpark = txtSparkling.Text
tManSmooth = txtMansmooth.Text
tBanSmooth = txtBanana.Text
tTropSmooth = txtTropical.Text
tStrawSmooth = txtStrawSmooth.Text
tVanilla = txtVanilla.Text
tCookie = txtChipCookie.Text
tManShake = txtManShake.Text
tBanShake = txtBanShake.Text
Dim TotalSum As Double = 0
If Me.chkJuices.Items().ToString = "Mango" Then
TotalSum += (100 * tMango)
End If
If Me.chkJuices.Items().ToString = "Orange" Then
TotalSum += (100 * tOrange)
End If
If Me.chkJuices.Items().ToString = "Strawberry" Then
TotalSum += (100 * tStrawberry)
End If
If Me.chkJuices.Items().ToString = "Watermelonade" Then
TotalSum += (100 * tWatermelon)
End If
If Me.chkJuices.Items().ToString = "Minty Pineade" Then
TotalSum += (100 * tMinty)
End If
txtJuice.Text = TotalSum
End Sub
On the button click you will have to look after the checkboxes that are checked and then do the proper math
Private Sub Calculate() Handles Button.click
Dim TotalSum As Double = 0
For i = 0 To (CheckedListBox1.Items.Count - 1)
If CheckedListBox1.GetItemChecked(i) = True Then
If CheckedListBox1.Items(i).ToString = "Mango" Then
TotalSum += (100 * tMango)
End If
If CheckedListBox1.Items(i).ToString = "Orange" Then
TotalSum += (100 * tOrange)
End If
End If
Next
End Sub

Score not being calculated correctly

Hi I'm created a program for a project and I've now started running some tests and the score for the user isn't being calculated correctly and I believe that it can't compare the answer given to the correct answer. I'm very confused and need any help that can be given. My code looks like this, any confusing parts and I'll try and explain.
Imports System.IO
Public Class QuestionScreen
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Main.Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Main.Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i As Integer = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
If Ans_TxtBx.Text = answers(i) Then
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class
OK..... Try this, I have debugged your code trying to leave it pretty much as you had it, there were a number of problems, nothing major just a few lines of code in the wrong place....
Imports System.IO
Public Class Form1
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Try
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
' clear the list of questions and answers
answers.Clear()
questions.Clear()
'''''''''''''''''''''''''''''''''''''''''
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
Catch ex As Exception
End Try
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
Call ReadFile() ' move this to the bottom
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
count = count + 1
If Ans_TxtBx.Text = answers(i - 1) Then ' need to subtract 1 here
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
Call ReadFile() ' move this to the bottom
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class

Make specific randomly generated codes with timer

I would like to make randomly generated codes when a timer is finished.
But I would like to use this code ABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789
on this format XXXX-XXXX-XXXX (replace X with a randomly generated number/letter)
And I would like to insert the code in this
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Increment(3)
If ProgressBar1.Value = 100 Then
TextBox1.Text = "replace textbox by code"
Timer1.Stop()
End If
End Sub
Here's a solution using LINQ.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Increment(3)
If ProgressBar1.Value = 100 Then
Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim random = New Random()
Dim num1 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
Dim num2 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
Dim num3 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
Dim result = num1 & "-" & num2 & "-" & num3
TextBox1.Text = result
Timer1.Stop()
End If
End Sub
With this, you'd just change your TextBox1.Text = to point to the getNewRandomString() function.
Private Function getNewRandomString() As String
Dim sb As New StringBuilder
For i = 1 To 3
For j = 1 To 4
sb.Append(getNewRandomLetter())
Next
sb.Append("-")
Next
Return sb.ToString.Trim("-")
End Function
Private Function getNewRandomLetter() As Char
Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Return (chars(GetRandom(0, chars.Length - 1)))
End Function
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
Static Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max + 1)
End Function

I can't find the cause of this Stack Overflow Exception

Ever since I added the CheckForCollision_Enemy method, I've been getting a stack overflow exception every time I run my code.
Here is the CheckForCollision_Enemy method, in the Main class.
Public Sub CheckForCollision_Enemy()
Dim ship1 As New Enemy(Nothing, Nothing)
Dim ship2 As New Enemy(Nothing, Nothing)
Debug.Print("")
Dim ships = {acc_e, bs_e, sb_e, ds_e, pb_e}
For i As Integer = 0 To ships.Length - 1
ship1 = ships(i)
For j As Integer = 0 To ships.Length - 1
ship2 = ships(j)
If ship1.name <> ship2.name Then
For l As Integer = 0 To ship1.length - 1
For t As Integer = 0 To ship2.length - 1
If ship1.space_filled(l, 0) = ship2.space_filled(t, 0) And ship1.space_filled(l, 1) = ship2.space_filled(t, 1) Then
Debug.Print("Collision at {" & ship1.space_filled(l, 0) & ", " & ship1.space_filled(l, 1) & "} " & ship1.name & " VS " & ship2.name)
End If
Next
Next
End If
Next
Next
End Sub
Here is the Enemy class. This is the class where the error is shown. I marked exactly where as a comment.
Shared gen As New Random()
Dim x As Integer = 0
Dim y As Integer = 0
Public Sub New(ByVal namep As String, ByVal lengthp As Integer)
name = namep
length = lengthp
ReDim _start_point(2)
ReDim _space_filled(length, 2)
GenerateDirection()
If direction = "horizontal" Then
x = gen.Next(0, 11 - length)
y = gen.Next(0, 10)
ElseIf direction = "vertical" Then
x = gen.Next(0, 10)
y = gen.Next(0, 11 - length)
End If
GenerateStartPoint()
ExtendStartPoint()
DefineFilled()
ColorFilled()
Main.CheckForCollision_Enemy() 'If this is taken out, it will work fine.
End Sub
Public Sub GenerateStartPoint()
start_point = {x, y}
End Sub
Public Sub GenerateDirection()
If gen.Next(0, 2) = 0 Then
direction = "horizontal"
Else
direction = "vertical"
End If
End Sub
Public Sub ExtendStartPoint()
If direction = "horizontal" Then
For i As Integer = 0 To length - 1
space_filled(i, 0) = start_point(0) + i
space_filled(i, 1) = start_point(1)
Next
ElseIf direction = "vertical" Then
For i As Integer = 0 To length - 1
space_filled(i, 0) = start_point(0)
space_filled(i, 1) = start_point(1) + i
Next
End If
End Sub
Public Sub DefineFilled()
For i As Integer = 0 To length - 1
x = space_filled(i, 0)
y = space_filled(i, 1)
Try
generate = False
Main.TrackerBoard.box_list(x, y).full = True
Catch
End Try
Next
End Sub
Private Sub ColorFilled()
For y As Integer = 0 To 9
For x As Integer = 0 To 9
'Debug.Print(Main.PlayerBoard.box_list(x, y).full)
If Main.TrackerBoard.box_list(x, y).full = True Then 'New error: "InvalidOperationException"
Main.TrackerBoard.box_list(x, y).image.BackColor = System.Drawing.Color.Red
Else
Main.TrackerBoard.box_list(x, y).image.BackColor = System.Drawing.Color.Silver 'Most often, the error appears here.
End If
Next
Next
End Sub
Here is the ship class. I've taken out most of the methods to save space; if you want to see anything, I'll add it in for you.
Public Class Ship
Dim _name As String
Public Property name() As String ...
Dim WithEvents _image As PictureBox
Public Property image() As PictureBox ...
Dim _length As Integer
Public Property length() As Integer ...
Dim _direction As String
Public Property direction() As String ...
Dim _selected As Boolean
Public Property selected() As Boolean ...
Dim _placed As Boolean
Public Property placed() As Boolean ...
Dim _location() As Integer = {0, 0}
Public Property location() As Integer() ...
Dim _has_moved As Boolean
Public Property has_moved() As Boolean ...
Dim _space_filled(,) As Integer
Public Property space_filled() As Integer(,) ...
Public rect As System.Drawing.Rectangle
Dim mouse_up As Boolean = False
Dim tile_size As Integer = 25
Public Sub New(ByVal namep As String, ByVal imagep As PictureBox, ByVal lengthp As Integer, ByVal directionp As String, ByVal selectedp As Boolean, ByVal placedp As Boolean)
name = namep
image = imagep
length = lengthp
direction = directionp
selected = selectedp
placed = placedp
location(0) = 0
location(1) = 0
ReDim space_filled(length, 2)
rect = New System.Drawing.Rectangle(location(0), location(1), length * tile_size, 1 * tile_size)
End Sub
Private Sub Ship_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _image.MouseMove ...
Private Sub Ships_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _image.MouseClick ...
Private Sub Ship_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _image.MouseUp ...
Public Sub Update() ...
Public Sub SnapToBox() ...
Private Sub DefineSpaceFilled() ...
Private Sub ColorFilled() ...
End Class
Your CheckForCollision_Enemy calls New Enemy, and New Enemy calls CheckForCollision_Enemy. You are recursing until the stack overflows.

Visual Basic - Adding two binary numbers

Hi im new on here and in coding in general. I've been working on this code for adding two binary numbers together, individually the parts work but combined the don't. If anyone could help me with a solution for this I would be very grateful. Also if it could be shortened that would help as well, Thanks.
Class Form1
Dim intNum1 As Integer
Dim intNum2 As Integer
Dim intNum3 As Integer
Public Function BinaryToDecimalA(ByRef Binary As String) As Integer
Dim BinaryNumA As Integer
Dim BitCountA As Short
For BitCountA = 1 To Len(Binary)
BinaryNumA = BinaryNumA + (CDbl(Mid(Binary, Len(Binary) - BitCountA + 1, 1)) * (2 ^ (BitCountA - 1)))
Next BitCountA
BinaryToDecimalA = BinaryNumA
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum1 = (BinaryToDecimal((TextBox1.Text)))
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
TextBox1.MaxLength = 3
End Sub
Public Function BinaryToDecimal(ByRef Binary As String) As Integer
Dim BinaryNum As Integer
Dim BitCount As Short
For BitCount = 1 To Len(Binary)
BinaryNum = BinaryNum + (CDbl(Mid(Binary, Len(Binary) - BitCount + 1, 1)) * (2 ^ (BitCount - 1)))
Next BitCount
BinaryToDecimal = BinaryNum
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum2 = (BinaryToDecimal((TextBox2.Text)))
End Sub
Private Sub TextBox2_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
TextBox2.MaxLength = 3
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum1 = Integer.Parse(TextBox1.Text)
intNum2 = Integer.Parse(TextBox2.Text)
intNum3 = intNum1 + intNum2
End Sub
Private Sub intNum3_TextChanged(sender As Object, e As EventArgs) Handles TextBoxAns.TextChanged
Dim i As Long, x As Long, bin As String
Const maxpower = 7
TextBoxAns.Enabled = False
bin = ""
x = Val(intNum3)
If x > 2 ^ maxpower Then
MsgBox("Number must be no longer than " & Str$(2 ^ maxpower))
TextBoxAns.Text = ""
End If
If x < 0 Then bin = bin + "1" Else bin = bin + "0"
For i = maxpower To 0 Step -1
If x And (2 ^ i) Then
bin = bin + "1"
Else
bin = bin + "0"
End If
Next
TextBoxAns.Text = bin
End Sub
End Class
This should work -
Not my code (reference http://www.bigresource.com/VB-Converting-a-number-to-its-binary-number-uDbSei3kPM.html) but it works !
Public Function BinaryAddition(ByVal A As String, ByVal B As String) As String
Dim curA As Currency
Dim curB As Currency
Dim curResult As Currency
curA = BinToDec(A)
curB = BinToDec(B)
curResult = (curA + curB) ' Mod (2 ^ 32)
BinaryAddition = DecToBin(curResult)
End Function
Private Function DecToBin(curDec As Currency) As String
Dim strTemp As String
Dim i As Integer
i = 31
Do While i >= 0
If curDec >= (2 ^ i) Then
strTemp = strTemp & "1"
curDec = curDec - (2 ^ i)
Else
strTemp = strTemp & "0"
End If
i = i - 1
Loop
DecToBin = strTemp
End Function
Module Module1
Sub Main()
Console.WriteLine("Enter the first binary number, then enter the second binary number")
Dim num As Integer = Convert.ToInt32(Console.ReadLine, 2)
Console.WriteLine(Convert.ToString(num + Convert.ToInt32(Console.ReadLine, 2), 2))
Console.ReadLine()
End Sub
End Module