VB.Net guess user's number from 1 to 1000 - vb.net

I am trying to create a guessing game that guesses the user's number from 1 to 1000. The user inputs if the number is higher or lower than the computer's guess. Based on the user's input, the computer each time halves the amount of the guess (e.g. first guess is 500, second is 250, third 125, etc, etc)
However I have encountered a problem when I am running this program. After pressing 'higher' or 'lower' for a few times, I am unable to change the output any further. I suppose this is to do with amount = amount / 2 reaching a limit where it can barely be added or subtracted into intGuess. I have tried doing amount = (amount / 2) + 1, but that sometimes doesn't allow me to get to a number.
How would I counteract this problem?
Here is my code:
Dim intGuess As Integer = 500
Dim amount As Integer = 500
Dim count As Integer = 0
Private Sub btnLower_Click(sender As Object, e As EventArgs) Handles btnLower.Click
amount = amount / 2
intGuess = intGuess - amount
lblGuess.Text = $"Is your number {intGuess} ?"
count = count + 1
End Sub
Private Sub btnHigher_Click(sender As Object, e As EventArgs) Handles btnHigher.Click
amount = amount / 2
intGuess = intGuess + amount
lblGuess.Text = $"Is your number {intGuess} ?"
count = count + 1
End Sub
Just thought I should add this, but the first guess is 500.

I play this game verbally with my young son. I tell him to guess a number from 1 to 1000 and guarantee I can guess it in 10 or fewer guesses. It is a simple binary search. You can research binary search to come up with an algorithm. It's pretty simple and I've split it up into buttons like you have. Here is my form
The code to make it work is
Private guess As Integer
Private max As Integer
Private min As Integer
Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
If Integer.TryParse(MaxTextBox.Text, max) AndAlso
Integer.TryParse(MinTextBox.Text, min) AndAlso
max > min Then
makeGuess()
Else
MessageBox.Show("Error in max or min, cannot continue! Fix max and min and try again.")
End If
End Sub
Private Sub HigherButton_Click(sender As Object, e As EventArgs) Handles HigherButton.Click
min = guess
makeGuess()
End Sub
Private Sub LowerButton_Click(sender As Object, e As EventArgs) Handles LowerButton.Click
max = guess
makeGuess()
End Sub
Private Sub JustRightButton_Click(sender As Object, e As EventArgs) Handles JustRightButton.Click
MessageBox.Show($"That's right, I found your number, it is {guess}!")
End Sub
Private Sub makeGuess()
guess = CInt((max - min) / 2 + min)
GuessLabel.Text = guess.ToString()
End Sub

Related

Calculate the amount to pay based on time difference in 2 textboxes VB.Net

enter image description here
I want to get the amount to pay based on time difference of the time in and time out.
example. Time In is : 7:00:00
Time Out is : 13:00:00
The difference is 6 hrs
and lets say that the per hour rate is 10.00, so the amount should be 60.00
thanks! im using vb.net
what im trying to do is like this.
Private Const Format As String = "HH:mm:ss"
'this is the code i used to get the time in
Private Sub btnTimeIn_Click(sender As Object, e As EventArgs) Handles btnTimeIn.Click
TextboxTimeIn.Text = DateTime.Now.ToString(Format)
End Sub
'this is the time out
Private Sub btnTimeOut_Click(sender As Object, e As EventArgs) Handles btnTimeOut.Click
TextboxTimeOut.Text = DateTime.Now.ToString(Format)
'this is what is use to get the time difference
txtAmount.Text = Convert.ToDateTime(TextboxTimeOut.Text).Subtract(Convert.ToDateTime(TextboxTimeIn.Text)).ToString()
End Sub
but instead of showing the time difference, i want to show the amount in the txtAmount. example
if timeDifference <= 60mins , then
txtAmount = 10
else timeDifference > 60mins , then
txtAmount = 20
You want to know 3 things:
How much time passed between checkin and checkout
How many hours is that
Hom much will this cost
These points could be calculated in only one line, but for the sake of clarity we'll clear them one by one:
'let's use some more variables to make this easier
Private Const Format As String = "HH:mm:ss"
Private checkin As DateTime
Private checkout As DateTime
Private rate As Integer = 10
'now with variables!
Private Sub btnTimeIn_Click(sender As Object, e As EventArgs) Handles btnTimeIn.Click
checkin = Now
TextboxTimeIn.Text = checkin.ToString(Format)
End Sub
Private Sub btnTimeOut_Click(sender As Object, e As EventArgs) Handles btnTimeOut.Click
checkout = Now
TextboxTimeOut.Text = checkout.ToString(Format)
'First we check for an amount of hours, then we add one if they overstayed
Dim timeStayed As Integer = checkout.Hour - checkin.Hour
If TimeStayed.Minute > 0 Then timeStayed += 1
'Notice the use of a variable so you can tweak your rates easily
txtAmount.Text = (timeStayed * rate).ToString
End Sub
What you need to remember here is:
Make things easier on you. Don't convert everything all the time.
Follow your own pseudocode. You already knew what to do. Do it.
I used Integers for money... this is bad! You should change this as soon as possible, so your numbers can have decimals! (also you should format the txtAmount as money)
Have fun!

Making a Quiz In visual basic that requires a highscore feature which isnt working correctly

I'm making a quiz and it requires a highscore function as said before. When I run the program everything is fine except that the highest score won't always be the highest score.
If I retake it, a lower score will still replace the highest. scores aren't showing in the 2nd and 3rd highest brackets either which I assume is with the same problem..
Here's the code-- (With each question answered correctly there is score += 1, then calling score update at the end of last question. )
Public score As Integer = 0
'best score
Dim highest As Integer
'second best
Dim scoreuno As Integer
'third best
Dim scoredos As Integer
Private Sub Form7_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub scoreupdate()
highScore.Text = highest.ToString
score2.Text = scoreuno.ToString
score3.Text = scoredos.ToString
End Sub
Public Sub highscores()
If score > highest Then
scoredos = scoreuno
scoreuno = highest
highest = score
ElseIf score > scoreuno Then
scoredos = scoreuno
scoreuno = score
ElseIf score > scoredos Then
scoredos = score
End If
scoreupdate()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
score = 0
Form1.Show()
Me.Close()
End Sub
You could simplify your code a little by using a list of integers like this
Dim HighScores As New List(Of Integer)
Then, instead of using your current HighScores sub using the sub below, just add a score to the list which is sorted in to highest value first, and then the lowest value is removed from the end of the list.
This way, if you decide to have more than 3 high scores, it should work just fine. just change the maxHighscores variable instead of having to edit your If statement and add increasing amounts of code. Then just add code into your update sub to show the additional scores.
Private Sub AddScoreIfHighEnough(score As Integer, maxScoresCount As Integer)
'Adds score to list
HighScores.Add(score)
'Sorts list into ascending order and reverses the order
HighScores.Sort()
HighScores.Reverse()
'if the number of scores is greater than the maximum allowed
'number remove the extra scores
While maxScoresCount < HighScores.Count
HighScores.RemoveAt(HighScores.Count - 1)
End While
End Sub
To use it just add replace each time you use
highScores()
with
AddScoreIfHighEnough(score,3)
Finally to assign your scores, just use
Private Sub scoreupdate()
highScore.Text = HighScores(0).ToString
score2.Text = HighScores(1).ToString
score3.Text = HighScores(2).ToString
End Sub

Formatting and Computing Numbers in Textbox VB.Net

Hello Everyone Good Afternoon.
I Hope Someone Helps me with my Problem.
I have 3 Textboxes and they are:
GrandTotal.Text
VatAmount.Text
TotalAmount.Text
and 1 NumericUpdown1.Value
Here is the Scenario, As the system goes, there is a code that will trigger and Will put a Number value in GrandTotal.Text and after that, The User will press NumericUpdown1.Value. Every time the user press it A computation will be triggered and a Number value will be Displayed in TotalAmount.Text and VatAmount.Text
To Make it more specific it is like a computation form that will include VAT. For Example.
Grandtotal.text = 2000
and if I press the NumericUpDown to + 1
VatAmount.Text = 20 and TotalAmount.Text = 2020
I hope you get what I mean
and Here is my code for It:
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged
VatAmount.Text = Val(Grandtotal.text) * NumericUpDown1.Value * 0.01
End Sub
Private Sub VatAmount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VatAmount.TextChanged
TotalAmount.Text = Val(VatAmount.Text) + Val(TextBox14.Text)
End Sub
Now I`m done Explaining it here is My Question.
How to put Commas on that Textboxes and Compute It? My Prof. asked that He wants to put commas on the numbers that will bi inputted? No need to literally put Commas. Put it Automatically when value is greater that 3 Digits
How can I put commas in Textboxes and Compute it using the NumericUpdown?
TYSM
This is roughly what you need:
Private Sub GrandTotal_TextChanged(sender As Object, e As EventArgs) Handles GrandTotal.TextChanged
Dim input As Double = Double.Parse(GrandTotal.Text)
Dim inputStringWithCommas As String = input.ToString("N0", CultureInfo.InvariantCulture)
GrandTotal.Text = inputStringWithCommas
Dim vat As Double = Double.Parse(GrandTotal.Text) * NumericUpDown1.Value * 0.01
VatAmount.Text = vat.ToString()
TotalAmount.Text = (Double.Parse(GrandTotal.Text) + vat).ToString("N0", CultureInfo.InvariantCulture)
End Sub
It is similar to what you have, so you should be able to make it work for the NumericUpDown event as well.

vb.net code reads lables wrong

Okay, so I am making a game, like cookie clicker, or in my case - http://www.silvergames.com/poop-clicker (don't ask...), so that when you click on the icon in the center, it changes the total value by adding 1. On the side, you have a picture which you click to increase the amount it generates automatically every second.
At the moment I have it like this:
The timer tics every second. If the total amount > the cost of upgrade then it shows the picture of the thing you click to upgrade.
When you click that picture -
The cost is taken away from the total amount.
It changes the amount of times you have used that upgrade by +1.
The automatic upgrades per second is changed by +1.
The Cost is increased by 10.
What is happening is that I click the icon in the middle say 5 times (very quickly) and it only comes up with a total of 3. That in itself is a problem, but the even worse problem is that it shows the picture to click, when i told it to only show when the total value was > 10 (the cost of the upgrade).
I am really confused, and any help will be much appreciated.
Thanks
SkySpear
PS. Here's the Code -
Public Class Form1
Private Sub picPoop_Click(sender As Object, e As EventArgs) Handles picPoop.Click
lblPoops.Text = lblPoops.Text + 1
End Sub
Private Sub picCursor_Click(sender As Object, e As EventArgs) Handles picCursor.Click
lblPoops.Text = lblPoops.Text - lblCursorCost.Text
lblCursorAmmount.Text = lblCursorAmmount.Text + 1
lblPoopsPerSec.Text = lblPoopsPerSec.Text + 1
lblCursorCost.Text = lblCursorCost.Text + 10
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblCursorAmmount.Text = 0
lblCursorCost.Text = 10
lblBabyAmmount.Text = 0
lblBabyCost.Text = 100
lblBowlAmmount.Text = 0
picCursor.Hide()
tmrSec.Start()
End Sub
Private Sub tmrSec_Tick(sender As Object, e As EventArgs) Handles tmrSec.Tick
If lblPoops.Text > lblCursorCost.Text Then picCursor.Show()
End Sub
End Class
Again, don't ask where this ridiculous idea came from, I can assure you it wasn't mine.
Your main problem with this is that in your Timer sub, you are comparing text to text. In this case, a value of "3" > "21", since text comparisons work on a char by char basis. When this happens, your pictureBox is being shown. As others suggested, you can use any of the string to numeric conversion functions in your timer event to make this work better.
A slightly better approach would be to declare some class level numeric variables that hold each individual value and displays them when needed. As an example
numPoops += 1
lblPoops.Text = numPoops
This will make sure that all math will work correctly.
You are dealing with the Value of the textboxes, not the Text in it.
You should enclose each textbox with VAL() to get its exact value as a number.
Private Sub picPoop_Click(sender As Object, e As EventArgs) Handles picPoop.Click
lblPoops.Text = VAL(lblPoops.Text) + 1
End Sub
Private Sub picCursor_Click(sender As Object, e As EventArgs) Handles picCursor.Click
lblPoops.Text = VAL(lblPoops.Text) - VAL(lblCursorCost.Text)
lblCursorAmmount.Text = VAL(lblCursorAmmount.Text) + 1
lblPoopsPerSec.Text = VAL(lblPoopsPerSec.Text) + 1
lblCursorCost.Text = VAL(lblCursorCost.Text) + 10
End Sub
Private Sub tmrSec_Tick(sender As Object, e As EventArgs) Handles tmrSec.Tick
If VAL(lblPoops.Text) > VAL(lblCursorCost.Text) Then picCursor.Show()
End Sub

multiple inputs in text box not totaling

I got another super basic question, im trying to total the subtotals of every entry in the txtPrice.Text the user enters, and then refresh the other lables with the updated tax, shipping, and grand total. Its not totaling the subTotal, everything else works fine. Whats up with that?
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim sglSub As Single
Dim sglTotal As Single
Dim sglSalesTax As Single
Const TAX_RATE As Single = 0.02
Dim bytShippingCharge As SByte = 10
Dim sglCompTotal As Single
Single.TryParse(txtPrice.Text, sglSub)
sglTotal += sglSub
lblSubTotal.Text = sglTotal.ToString("C2")
sglSalesTax = (sglTotal * TAX_RATE)
lblTax.Text = sglSalesTax.ToString("C2")
If sglTotal >= 100 Then
bytShippingCharge = 0
End If
lblShipping.Text = bytShippingCharge.ToString("C2")
sglCompTotal = (sglTotal + sglSalesTax + bytShippingCharge)
lblTotal.Text = sglCompTotal.ToString("C2")
End Sub
Tips
In this line:
sglTotal += sglSub
-Every time you work with a total initialize it to zero before adding a value to it. If not it can leads to undesired result.
-When working with currency is better to use a decimal type instead.
If you want a variable keeps its value declare it shared.
This a little example of how you can use a shared field
Public Class Form1
Shared total As Decimal = 0D
Shared Sub calc()
total += 2
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calc()
Label1.Text = total.ToString
End Sub
End Class