If statements not working correctly in vb.net - vb.net

I'm making a space invaders game in vb.net however for my high score system it doesn't seem to be working correctly. Whenever I try to get a lower score than my current high score, the input box for when I actually do get a higher score than my current high score still pops up
Best design name is the label responsible for showing who has the best high score
If Val(Lives.Text) = 0 Then`your text`
MsgBox("You Lose!")
If Val(score.Text) > Val(Highscore.Text) Then
Highscore.Text = score.Text
Highscore.Text = "high Score: " & Highscore.Text
Best.Text = InputBox("Enter your name")
Best.Text = "best Player: " & Best.Text
filenum = FreeFile()
FileOpen(filenum, "score.txt", OpenMode.Output)
PrintLine(filenum, Best.Text)
PrintLine(filenum, Highscore.Text)
FileClose(filenum)
Close()
Else
Close()
End If
End If
I tried switching around the if statements but nothing happened

You should keep your score values separatet from text.
if you say Val(Highscore.text) you will get zero if the Highscore.text is "High score: 12345"

If Val(Lives.Text) = 0 Then
MsgBox("You Lose!")
If Val(score.Text) > Val(Highscore.Text) Then
Highscore.Text = score.Text
Highscore.Text = "high Score: " & Highscore.Text
Best.Text = InputBox("Enter your name")
Best.Text = "best Player: " & Best.Text
filenum = FreeFile()
FileOpen(filenum, "score.txt", OpenMode.Output)
PrintLine(filenum, Best.Text)
PrintLine(filenum, Highscore.Text)
FileClose(filenum)
End If
Close()
End If

Related

Stop msgbox OK closing text input

Stressed out manager trying to fix a problem in our organisational CRM.
We have a macro set up to send 'ad hoc' text messages to clients. The character limit for the text input is 160, and if you exceed that, a msgbox pops up to tell you to reduce your text by x characters.
When you hit OK, it then kills the entire input box (so you have to re-type a new shorter version of your original message).
How can I set it up so that if you exceed the character limit, it tells you and then gives you the opportunity to go back and delete a few characters?
This is the portion of code I think is relevant:
set msgEntryDlg = CreateDialog("Adhoc SMS")
set msgTxtCtl = msgEntryDlg.AddControl("SMS Message: ",2, "")
if NOT msgEntryDlg.Execute then
Msgbox "Message cancelled!"
Exit sub
end if
mail_message = msgTxtCtl.Text
mail_message = " " + mail_message
If Len(mail_message) < 1 Then
MsgBox "Message was empty, please enter a message!"
Exit Sub
End If
If Len(mail_message) > 160 Then
MsgBox "Message is too long, please reduce by " & (len(mail_message) - 160) & " characters.",4112
Exit Sub
End If
I think it's something to do with a loop ... but I am clueless!
Thanks in advance.
Untested, but I believe you're looking for something like this:
Dim success As Boolean
Do
Set msgEntryDlg = CreateDialog("Adhoc SMS")
Set msgTxtCtl = msgEntryDlg.AddControl("SMS Message: ", 2, "")
If Not msgEntryDlg.Execute Then
MsgBox "Message cancelled!"
Exit Do
End If
mail_message = msgTxtCtl.Text
mail_message = " " + mail_message
If Len(mail_message) < 1 Then
MsgBox "Message was empty, please enter a message!"
End If
If Len(mail_message) > 160 Then
MsgBox "Message is too long, please reduce by " & (Len(mail_message) - 160) & " characters.", 4112
End If
success = True
Loop Until success
If you need to repeat an action until a condition is met, check for the condition at the end of each loop. Note that the cancellation exits the Do, not the Sub.

Case Statement true and False?

I'm working on an AutoCAD VBA program that creates a drawing.
But i have a slight problem. If "Case 1" is True Then "Case 2" must be false. Here is my code :
Sub Pumps()
'Option for type of pump piping
ans = InputBox("1 = STD Piping" & vbCrLf & _
"2 = Omit Pump", "Pump Piping")
Select Case ans
Case "1":
: Set layerObj = ThisDrawing.Layers.Add("PUMP-PIPING STD -" & Size)
layerObj.LayerOn = True
Case "2":
: Set layerObj = ThisDrawing.Layers.Add("OMIT PUMP -" & Size)
layerObj.LayerOn = True
Case Else: MsgBox "Wrong Input Dude.", vbCritical, MSG: Exit Sub
End Select
End Sub
Please Assist
So I'm not sure what the end goal was, but hopefully this gets you started.
What I've done I've isolated the "decision making" to the switch block, and that sets the toggle variable which is needed for the "work" to be done later. (and I would consider moving that "work" of actually setting the layerObj out to another Sub
Sub Pumps()
Dim ans As String
'Option for type of pump piping
ans = InputBox("1 = STD Piping" & vbCrLf & _
"2 = Omit Pump", "Pump Piping")
Dim toggle As Boolean
Select Case ans
Case "1": toggle = True
Case "2": toggle = False
Case Else: MsgBox "Wrong Input Dude.", vbCritical, MSG: Exit Sub
End Select
Set layerObj = ThisDrawing.Layers.Add("PUMP-PIPING STD -" & Size)
layerObj.LayerOn = toggle
Set layerObj = ThisDrawing.Layers.Add("OMIT PUMP -" & Size)
layerObj.LayerOn = Not (toggle)
End Sub
Remove the : from your code all over. Every single one of them.
It makes plenty of problems, especially with Conditions. You really cannot follow what is happening.
In general, the : means that you want the next line to stay on the similar line. It is useful only when you want to assign values to a newly declared variable like this: Dim k as long: k = 5 and its idea is to save space.
Take a look at this topic, you would understand what I mean:
VBA - How the colon `:` works in VBA code with condition

Why wont my code go back to the main menu?

I'm creating a guess the number game in VB.Net. I've got to the point where I'm asking the player if they would like to play again after they have won. When I try and send them back to the main menu if they select that they would like to play again it just exits out of the program.
Sub MainMenu()
Console.WriteLine("Main Menu")
Console.WriteLine("1) Play Game")
Console.WriteLine("2) Instructions")
Console.WriteLine("3) View Score")
Console.WriteLine("4) Exit")
Console.WriteLine()
End Sub
If UserGuess = CorrectNumber Then
PlayerScore = PlayerScore + 1
Console.WriteLine("...CORRECT!!! You win!")
Console.WriteLine("You took " & NOfGuesses & " guesses!")
Console.WriteLine("Press Enter to Continue")
Console.ReadLine()
Console.Clear()
PlayAgainSub()
End If
Sub PlayAgainSub()
Dim PlayAgain As Char
Console.Clear()
Console.WriteLine("Would you like to play again? (Y/N)")
PlayAgain = Console.ReadLine.ToUpper
If PlayAgain = "Y" Then
MainMenu()
ElseIf PlayAgain = "N" Then
Quit()
Else
Console.WriteLine("Option not valid!")
REM Next line waits for 0.5 seconds so the user has time to see the error message.
Threading.Thread.Sleep(500)
Console.Clear()
PlayAgainSub()
End If
End Sub
This isn't all of the code, just what I considered relevant, if you need the rest of it I will update the post.
set a variable for recursion example
Dim recur As Char
then use Do .. loop while

How to vbs Ok, Cancel and X to work correctly in a .vbs script?

Hello everyone i put together this neat little script that quiz's the knowledge of the user on there Star Trek knowledge the script executes perfectly, but when hitting either OK, Cancel or X the questions are still answered as correct. I do know i need a vbCancel set in there somewhere but not sure about how to add it to the script.
'***********************************************************************
'Script Name: StarTrekQuiz.vbs
'Author: CharlesP
'Created: 03/31/15
'Description: This script creates a Star Trek Quiz game.
'***********************************************************************
'Perform script initialization activities
Option Explicit
Dim intPlayGame, strSplashImage, intNumberCorrect, strFederationRank
Dim objFsoObject, objQuestionDict, strAnswer, strQuestion
Const cTitlebarMsg = "The Star Trek Quiz Game"
Set objQuestionDict = CreateObject("Scripting.Dictionary")
objQuestionDict.Add "What was the Science Officer's name in the original Star Trek series?", "spock"
objQuestionDict.Add "What Star Trek villain appeared in both the original series and a Star Trek movie?", "khan"
objQuestionDict.Add "What was the numeric designation of Voyager's on-board Borg?", "7"
objQuestionDict.Add "Name the only Star Trek character to regularly appear on two series and at least two Star Trek movies?",
"worf"
objQuestionDict.Add "What is the last name of your favorite Captain?", "kirk picard sisco janeway archer"
objQuestionDict.Add "Who directed the first Star Trek movie?", "Robert Wise"
objQuestionDict.Add "In what Star Trek TOS episode did the tribbles FIRST appear?", "The Trouble With Tribbles"
objQuestionDict.Add "In what episode of Star Trek TNG did the Enterprise transport samples of Plasma Plague for medical
research?", "The Child"
objQuestionDict.Add "Who voices the computer in TNG?", "Majel Barrett"
objQuestionDict.Add "In TOS ~The Ultimate Computer~ who was the captain of the U.S.S. Excalibur?", "Captain Harris"
'Start the user's score at zero
intNumberCorrect = 0
'Display the splash screen and ask the user if he or she wants to play
strSplashImage = space(11) & "********" & vbCrLf & _
" ******************" & space(20) & "**************************" & _
space(15) & vbCrLf & "*" & space(30) & "*" & space(18) & _
"**" & space(39) & "*" & vbCrLf & " ******************" & _
space(20) & "*************************" & vbCrLf & space(31) & _
"******" & space(26) & "***" & vbCrLf & _
space(34) & "******" & space(22) & "***" & vbCrLf & _
space(37) & "******" & space(17) & "***" & vbCrLf & _
space(26) & " ****************************" & vbCrLf & _
space(26) & "*******************************" & vbCrLf & _
space(26) & "******************************" & vbCrLf & _
space(26) & " ****************************" & vbCrLf & vbCrLf & vbCrLf & _
"Would you like to boldly go where no one has gone before?"
'Ask the user to play
intPlayGame = MsgBox(strSplashImage, 36, cTitlebarMsg)
If intPlayGame = vbYes Then 'User elected to play the game
For Each strQuestion In objQuestionDict
strAnswer = InputBox(strQuestion, cTitlebarMsg)
If Trim(strAnswer) <> "" Then
If Instr(strAnswer, objQuestionDict(strQuestion)) Or Instr(objQuestionDict(strQuestion), strAnswer) Then
MsgBox "Correct"
intNumberCorrect = intNumberCorrect + 1
Else
MsgBox "Nice try. The answer I was looking for was " & objQuestionDict(strQuestion)
End If
End If
Next
Select Case intNumberCorrect
'User got 10 of 10 answers right
Case 10 : strFederationRank = "Fleet Admiral"
'User got 9 of 10 answers right
Case 9 : strFederationRank = "Admiral"
'User got 8 of 9 answers right
Case 8 : strFederationRank = "Vice Admiral"
'User got 7 of 8 answers right
Case 7 : strFederationRank = "Rear Admiral-Upper Hall"
'User got 6 of 7 answers right
Case 6 : strFederationRank = "Rear Admiral-Lower Hall"
'User got 5 of 5 answers right
Case 5 : strFederationRank = "Captain"
'User got 4 of 5 answers right
Case 4 : strFederationRank = "Commander"
'User got 3 of 5 answers right
Case 3 : strFederationRank = "Lieutenant-Commander"
'User got 2 of 5 answers right
Case 2 : strFederationRank = "Lieutenant"
'User got 1 of 5 answers right
Case 1 : strFederationRank = "Lieutenant Junior Grade"
'User did not get any answers right
Case 0 : strFederationRank = "Ensign"
End Select
MsgBox "You answered " & intNumberCorrect & " out of 10 correct." & _
vbCrLf & vbCrLf & "Your Star Fleet rank is : " & _
strFederationRank, , cTitlebarMsg
Else 'User doesn't want to play
MsgBox "Thank you for taking the Star Trek Quiz" & _
vbCrLf & vbCrLf & "Live long and prosper!", , cTitlebarMsg
WScript.Quit()
End If
Any help would be much appreciated thank you all in advance.
Unlike MsgBox function or Popup method, InputBox function has no vbCancel option.
If the user clicks OK or presses ENTER, the
InputBox function returns whatever is in the text box. If the user
clicks Cancel or ×, the function returns a
zero-length string ("").
Strictly speaking, above MSDN quotation is not right. If the user
clicks Cancel or × button or presses Esc key, the function returns Empty value (the same as if a variable is uninitialized.
Next code snippet could help.
' Ask the user to play
intPlayGame = MsgBox(strSplashImage, vbYesNo + vbQuestion, cTitlebarMsg)
Dim WshShell 'prepare for POPUP method
Set WshShell = WScript.CreateObject("WScript.Shell")
If intPlayGame = vbYes Then 'User elected to play the game
For Each strQuestion In objQuestionDict
strAnswer = InputBox(strQuestion, cTitlebarMsg)
If VarType( strAnswer)=0 Then
intPlayGame = WshShell.Popup( _
"Cancel pressed or window closed. Continue?", 7, _
cTitlebarMsg, vbYesNo + vbQuestion)
If not intPlayGame = vbYes Then Wscript.Quit
strAnswer=""
End If
if strAnswer="" Then strAnswer="???"
If Instr(1, strAnswer, objQuestionDict(strQuestion), vbTextCompare) _
Or Instr(1, objQuestionDict(strQuestion), strAnswer, vbTextCompare) Then
MsgBox "Correct"
intNumberCorrect = intNumberCorrect + 1
Else
MsgBox strAnswer & " Nice try. The answer I was looking for was " & objQuestionDict(strQuestion)
End If
Next
Select Case intNumberCorrect
Predefined MsgBox / Popup Constants
' Button Type
' vbOKOnly 0 Display OK button only.
' vbOKCancel 1 Display OK and Cancel buttons.
' vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
' vbYesNoCancel 3 Display Yes, No, and Cancel buttons.
' vbYesNo 4 Display Yes and No buttons.
' vbRetryCancel 5 Display Retry and Cancel buttons.
' Icon Type
' vbCritical 16 Display Critical Message icon.
' vbQuestion 32 Display Warning Query icon.
' vbExclamation 48 Display Warning Message icon.
' vbInformation 64 Display Information Message icon.
' Default Button: MsgBox Function only
' vbDefaultButton1 0 First button is the default.
' vbDefaultButton2 256 Second button is the default.
' vbDefaultButton3 512 Third button is the default.
' vbDefaultButton4 768 Fourth button is the default.
' Modality of the box: MsgBox Function only
' vbApplicationModal 0 Application modal. The user must respond to the message box before continuing work in the current application.
' vbSystemModal 4096 System modal. On Win16 systems, all applications are suspended until the user responds to the message box. On Win32 systems, this constant provides an application modal message box that always remains on top of any other programs you may have running.
' Return Value
' vbOK 1 OK
' vbCancel 2 Cancel
' vbAbort 3 Abort
' vbRetry 4 Retry
' vbIgnore 5 Ignore
' vbYes 6 Yes
' vbNo 7 No
' vbTrue -1 nSecondsToWait elapsed, the user did not click a button before
'
Edit:
#Ekkehard.Horner is right as CStr(VarType(strAnswer)) & TypeName(strAnswer) returns 0Empty if clicked Cancel or × in response to an InputBox. My resource: MSDN VBScript language reference.
But it's a faultfinder's quibble only here because by the same MSDN: how expressions are compared: if one expression is Empty and the other is a string, then perform a string comparison, using a zero-length string ("") as the Empty expression.
Thus, If strAnswer = "" ... comparison gives the same result regardless of strAnswer variable
is an empty string "", or
is uninitialized, or is explicitly set to Empty.
However, we could test VarType(strAnswer) and allow a user to correctly terminate the quiz uncomplete (see update in code snippet, used Popup method).
Clicking on cancel returns empty string in Inputbox.
So, check if the answer is "".
For Each strQuestion In objQuestionDict
strAnswer = InputBox(strQuestion, cTitlebarMsg)
If Trim(strAnswer) <> "" Then
If Instr(strAnswer, objQuestionDict(strQuestion)) Or Instr(objQuestionDict(strQuestion), strAnswer) Then
MsgBox "Correct"
intNumberCorrect = intNumberCorrect + 1
Else
MsgBox "Nice try. The answer I was looking for was " & objQuestionDict(strQuestion)
End If
End If
Next

Random number guessing game VB

OBJECTIVE:
This is a guessing game. The program is to generate a random number between 1 and 500. The user is to guess the number.
The form should include a START button, a listbox to hold all valid guesses, and a label displaying the answer.
Upon clicking the START button, the user will enter a number in response to an InputBox().
If the user’s guess is invalid (not numeric, not a whole number, out of range), display an appropriate message.
If the guess is valid but is not the correct number (high or low), display an appropriate message.
image high quess dialog boximage low quess dialog box
Every time the user guesses a valid numeric guess within range, add the guess to the listbox on the form. Allow the guesses to be shown in multiple columns in the listbox.
If the user successfully guesses the number, display an appropriate message. Include how many guesses they took. Count only valid (in range, integral) numeric guesses as a guess.
Allow the user to quit the game by entering Quit in response to the input box. If the user gives up, tell them the correct number
Important: Display the random number in a label immediately after generating it so that I (and you) know what the number is while I am (and you are) testing it. You can obviously take it out if you really want to play the game.
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
'Declare Variables
Dim strGuess As String
Dim random As New Random
Dim answer As Integer
'Start with empty Boxes
lstGuesses.Items.Clear()
answer = random.Next(1, 500)
lblAnswer.Text = CStr(answer)
Do
Try
strGuess = InputBox("Enter a numeric integer between 1 and 500. , Enter 'quit' to Quit.", "Guessing Game")
lstGuesses.Items.Add(strGuess)
If strGuess = CStr("quit") Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
Exit Do
End If
If CInt(strGuess) < CInt(1) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) > CInt(500) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) = CInt(answer) Then
MessageBox.Show("Got it! You guessed " & lstGuesses.Items.Add(strGuess) & " times!")
End If
If CInt(strGuess) > CInt(answer) And CInt(strGuess) <= CInt(500) Then
MessageBox.Show("Guess is High")
End If
If CInt(strGuess) < CInt(answer) And CInt(strGuess) >= CInt(1) Then
MessageBox.Show("Guess is Low")
End If
If lstGuesses.Items.Contains("quit") = True Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
End If
Catch ex As InvalidCastException
'Make user guess
MessageBox.Show("Invlid Guess. Enter a numeric integer between 1 and 500!")
End Try
Loop While CInt(strGuess) <> answer
End Sub
MY PROBLEM:
I have been trying everything and this is the best i have made yet. This homework is due in 4 hours so any help will be appreciated.
I am suppose to type the word "quit" to end the game. But also give an error message when something other than letters are typed. Every time I type a letter and press enter, it gives the warning that i set but then it crashes. It is not supposed to crash. It says the crash is from:
Loop While CInt(strGuess) <> answer
and the problem is because of an InvalidCastException and says convertion from string to type integer is not valid. I tried doing TRYPARSE but still the same problem. Can anyone tell me how to let me type the word "quit" into the box so that it quits the game, but doesn't make it crash.
Maybe this is not the best way but i think it will help.
What you need to do is Make a new if statement at the top just after the user entered something in the inputbox.
If IsNumeric(strGuess) Or strGuess = CStr("quit") Then
Else
MessageBox.Show("Only Numbers")
GoTo Line1
End If
And here you check "If IsNumeric(strGuess) Or strGuess = CStr("quit") Then"
if yes do nothing
If No show a msgbox and use a goto "GoTo Line1" "so above your do you add Line1:"
If somebody types something like "a" he will go to line1 "so start the do" and the user needs to enter something new in the inputbox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Declare Variables
Dim strGuess As String
Dim random As New Random
Dim answer As Integer
'Start with empty Boxes
lstGuesses.Items.Clear()
answer = random.Next(1, 500)
lblAnswer.Text = CStr(answer)
Line1:
Do
Try
strGuess = InputBox("Enter a numeric integer between 1 and 500. , Enter 'quit' to Quit.", "Guessing Game")
lstGuesses.Items.Add(strGuess)
If IsNumeric(strGuess) Or strGuess = CStr("quit") Then
Else
MessageBox.Show("Only Numbers")
GoTo Line1
End If
If strGuess = CStr("quit") Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
Exit Do
End If
If CInt(strGuess) < CInt(1) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) > CInt(500) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) = CInt(answer) Then
MessageBox.Show("Got it! You guessed " & lstGuesses.Items.Add(strGuess) & " times!")
End If
If CInt(strGuess) > CInt(answer) And CInt(strGuess) <= CInt(500) Then
MessageBox.Show("Guess is High")
End If
If CInt(strGuess) < CInt(answer) And CInt(strGuess) >= CInt(1) Then
MessageBox.Show("Guess is Low")
End If
If lstGuesses.Items.Contains("quit") = True Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
End If
Catch ex As InvalidCastException
'Make user guess
MessageBox.Show("Invlid Guess. Enter a numeric integer between 1 and 500!")
End Try
Loop While CInt(strGuess) <> answer
End Sub