For school, I have to make a program which converts a binary number to a decimal number and backwards. I want to make it so it changes whenever you type something in the textboxes.
Whenever I type something, I get the error that I should click either of the textboxes triggered by the last 'Else'.
TextBox1 is the textbox containing the decimal number, and TextBox2 contains the binary number.
This is the code:
Public Sub DecBinConverter_Activate()
Dim x As Double
Dim i As Long
Dim Active As String
Active = "TextBox1"
End Sub
Private Sub TextBox1_Change()
Call ConvertDecBin
End Sub
Private Sub TextBox2_Change()
Call ConvertDecBin
End Sub
Public Sub TextBox1_Enter()
Active = "TextBox1"
End Sub
Public Sub TextBox2_Enter()
Active = "TextBox2"
End Sub
Public Sub ConvertDecBin()
If Active = "TextBox1" Then
If TextBox1.Text <> "" Then
If IsNumeric(TextBox1.Text) Then
x = Round(Val(TextBox1.Text), 0)
If x < 10000000000# Then
TextBox1.Text = x
TextBox2.Text = Trim(Str(x Mod 2))
If (x Mod 2) = 0 Then
x = x / 2
Else
x = (x - 1) / 2
End If
Do While x <> 0
TextBox2.Text = Trim(Str(x Mod 2)) & TextBox2.Text
If (x Mod 2) = 0 Then
x = x / 2
Else
x = (x - 1) / 2
End If
Loop
Else
TextBox2.Text = "ERROR: Overload (0-999999999)"
End If
Else
TextBox2.Text = "ERROR: You must fill in a decimal number"
End If
End If
ElseIf Active = "TextBox2" Then
If TextBox2.Text <> "" Then
If IsNumeric(TextBox2.Text) Then
If Len(Str(TextBox2.Text)) > 40 Then
TextBox1.Text = "ERROR: Fill in a number no longer than 40 characters!"
Else
If InStr(Str(TextBox2.Text), "2") Or InStr(Str(TextBox2.Text), "3") Or InStr(Str(TextBox2.Text), "4") Or InStr(Str(TextBox2.Text), "5") Or InStr(Str(TextBox2.Text), "6") Or InStr(Str(TextBox2.Text), "7") Or InStr(Str(TextBox2.Text), "8") Or InStr(Str(TextBox2.Text), "9") Then
TextBox1.Text = "ERROR: You must fill in a binary number!"
Else
x = Round(Val(TextBox2.Text), 0)
TextBox2.Text = x
TextBox1.Text = 0
For i = 1 To Len(Str(x))
If Mid(Str(x), i, 1) = "1" Then
TextBox1.Text = TextBox1.Text * 2 + 1
Else
TextBox1.Text = TextBox1.Text * 2
End If
Next i
End If
End If
Else
TextBox1.Text = "ERROR: You must fill in a binary number!"
End If
End If
Else
MsgBox "An unknown error occurred, please click either of the textboxes.", vbOKOnly, "ERROR"
End If
End Sub
A couple of comments on your code:
You don't need to have an "Active" field because your event routines
are assigned to a control.
Anytime you work on a textbox field, the "Change" event is executed.
You would have to handle that (I can't find a link for that).
I recommend using "Option Explicit ".
Everybody has their own style; I hope this helps you:
Option Explicit
' Textbox1 has decimal, textbox2 has binary
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim idec&, s1$
If KeyCode <> 13 Then Exit Sub ' Only act upon "Enter"
s1 = TextBox1.Value
If s1 = "" Then Exit Sub ' blank ok
If Not IsNumeric(s1) Then
MsgBox "Textbox1 is not numeric"
TextBox1.Value = ""
Exit Sub
End If
' -- decimal to binary
idec = Val(s1) ' have decimal number
s1 = "" ' start binary string
Do While idec > 0
If idec Mod 2 = 1 Then s1 = s1 & "1" Else s1 = s1 & "0"
idec = idec \ 2 ' integer divide
Loop
TextBox2.Value = s1
End Sub
Private Sub TextBox2_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim idec&, ibin&, ixch&, ch$, s1$
If KeyCode <> 13 Then exit Sub ' Only act upon "Enter"
s1 = TextBox2.Value
If s1 = "" Then Exit Sub ' blank ok
If Not IsNumeric(s1) Then
MsgBox "Textbox2 is not numeric"
TextBox2.Value = ""
Exit Sub
End If
idec = 0 ' start decimal number
For ixch = 1 To Len(s1) ' binary to decimal
ibin = Val(Mid$(s1, ixch, 1)) ' 0 or 1
If ibin < 0 Or ibin > 1 Then
MsgBox "Textbox2 is not binary"
TextBox2.Value = ""
Exit Sub
End If
idec = idec * 2 + ibin
Next ixch
TextBox1.Value = Str$(idec)
End Sub
Related
I have a ListBox on a user form that I want the user to be able to type numerical values into the 3rd column of. The first two columns will have some predefined values in, and I want the user to select the row they want to modify, then type the number into the 3rd column.
I made the following code:
Private Sub cardList_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim curSel As Single
curSel = cardList.ListIndex
Dim curString As String
Dim newString As String
If curSel = -1 Then Exit Sub
If IsNull(cardList.List(curSel, 2)) Then
curString = ""
Else
curString = cardList.List(curSel, 2)
End If
If KeyCode > 47 And KeyCode < 58 Then
newString = curString & Chr(KeyCode)
ElseIf KeyCode = 8 Then
If Not curString = "" Then
newString = Mid(curString, 1, Len(curString) - 1)
End If
End If
cardList.List(curSel, 2) = newString
End Sub
This code works fine, the only problem is that when I press backspace the last character of the string is deleted as it should, but the selection of the ListBox also jumps up to the first row for some reason. Is there any way to prevent this? Or is there a better way to have a listbox that the user can type into?
Thanks in advance
This is the default behavior of the Listbox. You can use KeyCode = 0 to cancel the Key and prevent this from happening.
Private Sub cardList_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim curSel As Single
curSel = cardList.ListIndex
Dim curString As String
Dim newString As String
If curSel = -1 Then Exit Sub
If IsNull(cardList.List(curSel, 2)) Then
curString = ""
Else
curString = cardList.List(curSel, 2)
End If
If KeyCode > 47 And KeyCode < 58 Then
newString = curString & Chr(KeyCode)
ElseIf KeyCode = 8 Then
If Not curString = "" Then
newString = Mid(curString, 1, Len(curString) - 1)
End If
KeyCode = 0
End If
cardList.List(curSel, 2) = newString
End Sub
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
Dears,
I'm looking for assistance in visual basic with respect to multiple choices questions (MCQ).
by using visual basic for Visual Studio 2015
apply the codes without using database:
1- how to Not make any duplications in the questions?(for memorizing purpose... what is wrong and what is right?) E.g. Assuming I open the program and the first question is the word “rich” ,and I chose the correct answer, which is “IT”, I don’t want to see “rich” again until I finish with the whole list. However, if I make the wrong choice for “rich” for anything else e.g. “HR”, I want the word “rich” to appear after a while until I get the question correct. The point here to make the person memorize “rich” is “IT”.
Please write the codes down in your comment (the point you answering)
sorry for asking long question
Thank you
Public Class Form1
Private Structure questionsNanswers
Public Q As String
Public A As String
Public QT As Integer
Public QC As Integer
End Structure
Private wstart As Integer = 0
Private adad As Integer = 10
Private QA(9999) As questionsNanswers
Private word(15) As String
Private aray(15) As Integer
Private Sub RandomizeArray(a As Integer, ByRef array() As Integer)
Dim i As Integer
Dim j As Integer
Dim tmp As Integer
Randomize()
For i = 0 To a - 1
j = Int((6 - i + 1) * Rnd() + i)
tmp = array(i)
array(i) = array(j)
array(j) = tmp
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
' next
CheckEntry()
wstart = wstart + 1
If wstart >= adad Then
wstart = 0
End If
WriteText()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
' previous
CheckEntry()
wstart = wstart - 1
If wstart < 0 Then
wstart = adad - 1
End If
WriteText()
End Sub
Private Sub CheckEntry()
RadioButton1.Visible = True
RadioButton2.Visible = True
RadioButton3.Visible = True
RadioButton4.Visible = True
RadioButton1.ForeColor = Color.Black
RadioButton2.ForeColor = Color.Black
RadioButton3.ForeColor = Color.Black
RadioButton4.ForeColor = Color.Black
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton3.Checked = False
RadioButton4.Checked = False
End Sub
Private Sub WriteText()
Dim out As Boolean = False
For kk = 0 To 6
aray(kk) = kk
Next
RandomizeArray(7, aray)
Do Until out
For j = 0 To 3
If out = False Then
If aray(j) = QA(wstart).QT Then
out = True
Exit Do
End If
End If
Next
For kkk = 0 To 6
aray(kkk) = kkk
Next
RandomizeArray(7, aray)
Loop
RadioButton1.Text = word(aray(0))
RadioButton2.Text = word(aray(1))
RadioButton3.Text = word(aray(2))
RadioButton4.Text = word(aray(3))
Label1.Text = CStr(wstart + 1) & ") " & QA(wstart).Q
' ==============================
Dim go As Boolean = False
If go Then
Dim msg As String
For ll = 0 To 6
msg = msg + CStr(aray(ll)) + "|"
Next
MsgBox(msg)
End If
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
word(0) = "TA"
word(1) = "GR"
word(2) = "HR"
word(3) = "FIN"
word(4) = "commercial"
word(5) = "Proc"
word(6) = "IT"
QA(0).Q = "rich"
QA(0).A = word(6)
QA(0).QT = 6
QA(0).QC = -1
QA(1).Q = "Tal"
QA(1).A = word(1)
QA(1).QT = 1
QA(1).QC = -1
QA(2).Q = "sau"
QA(2).A = word(2)
QA(2).QT = 2
QA(2).QC = -1
QA(3).Q = "pat"
QA(3).A = word(3)
QA(3).QT = 3
QA(3).QC = -1
QA(4).Q = "del"
QA(4).A = word(5)
QA(4).QT = 5
QA(4).QC = -1
WriteText()
End Sub
End Class
Procedures :
1•Store the questions in a database(E.g. MySql/MSSQL/EXCEL)
2•In the database, create a table of 6 columns(column 1 for questions,column 2 for mcq option1,column 3 for mcq option 2, column 4 for mcq option 3,column 5 for mcq option 4 and finally column 6 for mcq answer )
3•Add 1 label and 4 Radio buttons
Now all you have to do is follow this and use the code..
That'll do the work
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
I have been programming for just over half a year now, so sorry for how bad this code is. But i am making pong in vb console mode in 2008. I am doing it for a project at my 6th form that why its in 2008. But when the ball is moving along it i causing the whole thing to flicker. I am using a 2D array with a ticker to move the ball. The code is pretty long and in separate classes so i will put the bit which i think is causing the problem. There is a lot of subs below the last which just move the paddles down and up
Module Module1
Public arrfield(79, 11), readkey, secounds, key, score1, score2 As String
Public milliSecond As Integer = 0
Public secound As Integer = 0
Private Tick As New Timers.Timer(1)
Public h As Integer = 39
Public g As Integer = 6
<MTAThread()> _
Sub Main()
AddHandler Tick.Elapsed, AddressOf ticker
score1 = 0
score2 = 0
Console.WriteLine("Hello and welcome to Russell's pong program!")
Console.WriteLine("This is a two player game, one person on WSAD and the other person on the arrow keys")
Console.WriteLine("Press ENTER to start")
Console.ReadLine()
fireldsetup()
field()
ball1()
win_lose()
Paddle1_middle_Paddle2_middle()
End Sub
<MTAThread()> _
Sub ball1()
Dim run As New ballphysics()
Dim ballphysics As New Thread(AddressOf run.ball)
ballphysics.Name = "ballphysics"
ballphysics.IsBackground = True
ballphysics.Start()
End Sub
<MTAThread()> _
Sub win_lose()
Dim run As New win_lose()
Dim win_lose As New Thread(AddressOf run.win)
win_lose.Name = "win_lose"
win_lose.IsBackground = True
win_lose.Start()
End Sub
Sub fireldsetup()
For i = 0 To 79
For j = 0 To 11
arrfield(i, j) = " "
Next
Next
For i = 0 To 79
arrfield(i, 1) = "_"
Next
For i = 0 To 79
arrfield(i, 11) = "_"
Next
Tick.Enabled = True
End Sub
Sub field()
Console.Clear()
Console.WriteLine()
Console.WriteLine(" " & "Player1" & " " & "Player2")
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine(" " & score1 & " !PONG! " & score2)
Console.ForegroundColor = ConsoleColor.White
Console.WriteLine()
Console.WriteLine()
For i = 0 To 79
Console.Write(arrfield(i, 1))
Next
For i = 0 To 79
Console.Write(arrfield(i, 2))
Next
For i = 0 To 79
Console.Write(arrfield(i, 3))
Next
For i = 0 To 79
Console.Write(arrfield(i, 4))
Next
For i = 0 To 79
Console.Write(arrfield(i, 5))
Next
For i = 0 To 79
Console.Write(arrfield(i, 6))
Next
For i = 0 To 79
Console.Write(arrfield(i, 7))
Next
For i = 0 To 79
Console.Write(arrfield(i, 8))
Next
For i = 0 To 79
Console.Write(arrfield(i, 9))
Next
For i = 0 To 79
Console.Write(arrfield(i, 10))
Next
For i = 0 To 79
Console.Write(arrfield(i, 11))
Next
End Sub
Private Sub LookForKeyPress()
Dim k As ConsoleKeyInfo = Console.ReadKey()
readkey = k.Key.ToString
End Sub
Sub ticker()
milliSecond += 1
secound = milliSecond
End Sub
Sub Paddle1_middle_Paddle2_middle()
fireldsetup()
arrfield(2, 7) = "│"
arrfield(2, 6) = "│"
arrfield(2, 5) = "│"
arrfield(76, 7) = "│"
arrfield(76, 6) = "│"
arrfield(76, 5) = "│"
field()
LookForKeyPress()
If readkey = "S" Then
readkey = ""
Paddle1_up1_Paddle2_middle()
ElseIf readkey = "W" Then
readkey = ""
Paddle1_down1_Paddle2_middle()
ElseIf readkey = "DownArrow" Then
readkey = ""
Paddle1_middle_Paddle2_up1()
ElseIf readkey = "UpArrow" Then
readkey = ""
Paddle1_middle_Paddle2_down1()
Else
Paddle1_middle_Paddle2_middle()
End If
End Sub
Do not use Console.Clear() that is what is causing the flickering. Use Console.SetCursorPosition(0, 0) to set the cursor back at the corner and write over your text.
When you call clear, the user can see the screen being cleared. I also suggest you put a few spaces after you write scrore2 incase the new score is smaller than the old one.
Not sure if it helps but instead of writing everything with on the console from your code you should consider assembling a string and only use console.writeline once.
Dim yourStringBuilder As New StringBuilder
yourstringBuilder.Append("yourContent")
Console.WriteLine(yourStringBuilder.ToString())