About above picture I set the first variable in machine with word "hello"
(SerialPort.Write())
02 "0A" 14 "01hello" 03
Image *
Then I request the first variable in machine (SerialPort.ReadExisting())
02 "0B01" 03
Image *
The output is
૯୫1A૯୫01hello૯୫૯୫2A૯୫01hello૯୫ ૯୫3A૯୫01hello૯୫ ....
If I click the button request, number before A, always change and sequence until the number 9
How to get string desired result is just hello?
* I cannot post the picture because I need at least 10 reputation to post image.
Some code I use
Private Sub readMemoryButton_Click(sender As Object, e As EventArgs) Handles readMemoryButton.Click
'copy
'Received.AppendText("TX" & vbCrLf) ' Switch to a new line after every transmission
'SpaceCount = 0
Dim TextString As String
Dim TXArray(2047) As Byte
Dim I As Integer
Dim J As Integer = 0
Dim Ascii As Boolean = False
Dim Quote As Boolean = False
Dim Temp As Boolean
Dim Second As Boolean = False
Dim TXByte As Byte = 0
Dim CharByte As Byte
If COMPort.IsOpen Then
TextString = Received.Text
For I = 0 To TextString.Length - 1
CharByte = Asc(TextString.Chars(I))
If CharByte = 34 Then ' If " Then
Temp = Ascii
Ascii = Ascii Or Quote
Quote = Not (Temp And Quote)
Else
Ascii = Ascii Xor Quote
Quote = False
End If
If Not Quote Then
If Ascii Then
TXArray(J) = CharByte
J = J + 1
Else
If (CharByte <> 32) And (CharByte <> 10) And (CharByte <> 13) Then ' Skip spaces, LF and CR
CharByte = (CharByte - 48) And 31 ' And 31 makes it case insensitive
If CharByte > 16 Then
CharByte = CharByte - 7
End If
If Second Then
TXArray(J) = TXByte + CharByte
Second = False
J = J + 1
Else
TXByte = CharByte << 4
Second = True
End If
End If
End If
End If
Next
Try
COMPort.Write(TXArray, 0, J)
Dim vLabelMemory As String = COMPort.ReadExisting()
labelMemory.Text = vLabelMemory
Catch ex As Exception
MsgBox(ex.Message & " Check CTS signal or set Flow Control to None.")
End Try
Else
MsgBox("COM port is closed. Please select a COM port")
End If
End Sub
Related
Hello I'm having quite some trouble with this task that was given to me.
I need to find a Sequence of 8 consecutive numbers in a Text file and Put that Line into a MsgBox.
So far I've only found
For Each i As Char In fileLocation
If IsNumeric(i) Then
result += i
End If
Next`
MsgBox(result)
But that won't help me I guess
Edit:
an example Line woudl look like this:
! MK 90 GRAD ALU L 10793013 144 63.00 90 1 3745 !
In this case I would need the 10793013 as an output
Edit 2:
this is the code I currently managed to create
Dim objReader As New System.IO.StreamReader(fileLocation)
Do While objReader.Peek() <> -1
concounter = 0
zeileInhalt = objReader.ReadLine()
ListBox1.Items.Add(zeileInhalt)
For Each zeichen As Char In zeileInhalt
If IsNumeric(zeichen) Then
concounter += 1
vorhanden = True
If vorhanden = False Then
ListBox1.Items.Add(zeileInhalt)
End If
ElseIf IsNumeric(zeichen) = False And concounter = 8 Then
concounter = 0
ElseIf IsNumeric(zeichen) = False And concounter < 8 Then
concounter = 0
ListBox1.Items.Remove(zeileInhalt)
ElseIf concounter > 8 Then
concounter = 0
ListBox1.Items.Remove(zeileInhalt)
vorhanden = False
End If
Next
Loop
'For i As Integer = 0 To fileLocation.Length <> -1
objReader.Close()
The counter itself appears to work however for some reason no entries end up in my listbox.
am I missing a case where the entries are getting removed?
PS: I hope you don't mind the german variable names. If you do
zeileInhalt = content of the row
zeichen = character
vorhanden = existing
Here's another approach to try out:
Dim values() As String
Using objReader As New System.IO.StreamReader(fileLocation)
Do While Not objReader.EndOfStream
values = objReader.ReadLine().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
For Each value As String In values
value = value.Trim()
If value.Length = 8 AndAlso value.All(Function(c) Char.IsDigit(c)) Then
ListBox1.Items.Add(value)
Exit For
End If
Next
Loop
End Using
try to introduce a counter to check the consecutivity in your if clause and reset it and result string to zero once it's not numeric!
Dim result As String = ""
Dim conCounter As Integer = 0
For Each i As Char In fileLocation
If Char.IsDigit(i) Then
conCounter = (conCounter + 1)
result = (result + i)
Else
conCounter = 0
If (result.Length < 8) Then
result = ""
End If
End If
Next
MsgBox(result)
for each word in fileLocation
Dim noExp As New Regex("([0-9]{8,11})")
Dim m As Match = noExp.Match(word)
If Not m.Success Then Throw New Exception("No sequence number found")
Dim c = m.Groups(1).Captures(0)
Msgbox(c.value)
next
how about this ?
I am writing a VBA code to add +2 to any string of numbers that are put in the function.
It works fine, until it reaches 6 and 7, then it breaks. I really have no clue why that is.
If you are wondering why I am doing this, this is part of an encryption algorithm and it is specifically looking to encrypt digits in a string.
My code is:
Sub AddNumbers()
Dim Nos As String
Dim AddNo As String
Dim Found As Boolean
Dim Split()
Nos = "0-1-2-3-4-5-6-7-8-9-10"
Sheets("Sheet1").Range("U2").Value = Nos
Length = Len(Nos)
ReDim Split(Length)
For i = 1 To Length
Found = False
Split(i) = Mid(Nos, i, 1)
For O = 48 To 55
If Split(i) = Chr(O) Then
Split(i) = Chr(O + 2)
Found = True
Exit For
End If
Next O
If Split(i) = Chr(56) Then
Split(i) = Chr(48)
ElseIf Split(i) = Chr(57) Then
Split(i) = Chr(49)
End If
Next i
AddNo = Join(Split, "")
Sheets("Sheet1").Range("U3").Value = AddNo
End Sub
I would really appreciate an insight to why it is breaking at 6 and 7.
Take me a moment, but you are double adding.
Look at your loop. When you encounter 6 (Char(54)) you add 2 and have 8 (Char(56)).
But then, after your loop you are testing again for same Split(i). Char for 6 and 7 are now accordingly 56 and 57 - so you add another 2 to them.
If Split(i) = Chr(56) And Found = False Then
Split(i) = Chr(48)
ElseIf Split(i) = Chr(57) And Found = False Then
Split(i) = Chr(49)
End If
Use the actual function Split:
Sub AddNumbers()
Dim Nos As String
Dim AddNo As String
Dim Found As Boolean
Dim SplitStr() As String
Nos = "0-1-2-3-4-5-6-7-8-9-10"
Sheets("Sheet1").Range("U2").Value = Nos
SplitStr = Split(Nos, "-")
Dim i As Long
For i = LBound(SplitStr) To UBound(SplitStr)
Dim vlue As String
vlue = StrConv(SplitStr(i), vbUnicode)
Dim substr() As String
substr = Split(Left(vlue, Len(vlue) - 1), vbNullChar)
Dim j As Long
For j = LBound(substr) To UBound(substr)
Select Case substr(j)
Case 8
substr(j) = 0
Case 9
substr(j) = 1
Case Else
substr(j) = substr(j) + 2
End Select
Next j
SplitStr(i) = Join(substr, "")
Next i
AddNo = Join(SplitStr, "-")
Sheets("Sheet1").Range("U3").Value = AddNo
End Sub
The overall problem is that you are using the Chr codes for numbers and not actual numbers. This method only returns 1 digit because a Chr() refers to a list of single characters.
You are going to need to use Split (mySplit = Split(Nos,"-")) to return each number and work with those.
The lines
If Split(i) = Chr(56) Then
Split(i) = Chr(48)
ElseIf Split(i) = Chr(57) Then
Split(i) = Chr(49)
End If
has me confused. You are saying if the value is "8" change to "0" and if it is "9" change to "1"
This is another way to do it:
Sub AddNumbers()
Dim Nos As String, Nos2 As String
Dim NumSplit As Variant
Dim Num As Variant
Dim tmp As String
Dim i As Long
Nos = "0-1-2-3-4-5-6-7-8-9-10"
Sheets("Sheet1").Range("U2").Value = Nos
NumSplit = Split(Nos, "-")
For Each Num In NumSplit
For i = 1 To Len(Num)
tmp = tmp & Mid(Num, i, 1) + 2
Next i
Nos2 = Nos2 & tmp & "-"
tmp = ""
Next Num
Nos2 = Left(Nos2, Len(Nos2) - 1)
Sheets("Sheet1").Range("U3").Value = Nos2
End Sub
It's a bit messy, but shows the basic idea of splitting the original array into the separate numbers.
The For....Next loop inside the For...Each loop takes care of any numbers with more than one digit (giving the 32).
My programm gets a high-speed data from serialport, and timer reads it , after timer gets value , timer is disabled and code does sting operations where add value which accepted earlier from com to listview. THe problem is that UI thread is not completely freezing but it seems laggy when i drag the form also, That code which add +1 every time on the subitem.text - is not smooth.
founditem.SubItems(4).Text = founditem.SubItems(4).Text + 1
Why is that as knows timer creats its own thread, and it shouldnot freeze an UI( i cant get rid of timer, becsouse its neccesary to accept correct data from serial)
Any tips? i tried invoke,begininvoke and background_worker, maybe not correctly.
Also can i call background worker from timer event? I'm not good at asyc tasks. My code is:
Private Sub spOpen()
Try
spClose()
spObj.PortName = "COM4"
spObj.BaudRate = 230400
spObj.Parity = IO.Ports.Parity.None
spObj.DataBits = 8
spObj.StopBits = IO.Ports.StopBits.One
spObj.Handshake = IO.Ports.Handshake.None
spObj.DtrEnable = False 'imp
spObj.RtsEnable = False 'imp
spObj.NewLine = vbCr
spObj.ReadTimeout = 0
spObj.WriteTimeout = 250
spObj.ReceivedBytesThreshold = 1
spObj.Open()
Catch ex As Exception
'catch
End Try
End Sub
Private Sub spClose()
Try
If spObj.IsOpen Then
spObj.Close()
spObj.Dispose()
End If
Catch ex As Exception
'handle the way you want
End Try
End Sub
Function ReverseString(ByVal sText As String) As String
Dim lenText As Long, lPos As Long
If Len(sText) = 0 Then Exit Function
lenText = Len(sText)
ReverseString = Space(lenText)
For lPos = lenText To 1 Step -2
If lPos > 0 Then Mid(ReverseString, lenText - lPos + 1, 2) = Mid(sText, lPos - 1, 2)
If lPos = 0 Then Mid(ReverseString, lenText - lPos + 1, 2) = Mid(sText, lPos, 2)
Next lPos
'Return
End Function
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'stop the timer (stops this function being called while it is still working
Timer1.Enabled = False
' get any new data and add the the global variable receivedData
receivedData = ReceiveSerialData()
'If receivedData contains a "<" and a ">" then we have data
If ((receivedData.Contains("<") And receivedData.Contains(">"))) Then
'parseData()
first_msg = 1
parseData()
End If
' restart the timer
Timer1.Enabled = True
End Sub
Function ReceiveSerialData() As String
Dim Incoming As String
Try
Incoming = spObj.ReadExisting()
If Incoming Is Nothing Then
Return "nothing" & vbCrLf
Else
Return Incoming
End If
Catch ex As TimeoutException
Return "Error: Serial Port read timed out."
End Try
End Function
Function parseData()
' uses the global variable receivedData
Dim pos1 As Integer
Dim pos2 As Integer
Dim length As Integer
Dim newCommand As String
Dim done As Boolean = False
Dim count As Integer = 0
While (Not done)
pos1 = receivedData.IndexOf("<") + 1
pos2 = receivedData.IndexOf(">") + 1
'occasionally we may not get complete data and the end marker will be in front of the start marker
' for exampe "55><T0056><"
' if pos2 < pos1 then remove the first part of the string from receivedData
If (pos2 < pos1) Then
receivedData = Microsoft.VisualBasic.Mid(receivedData, pos2 + 1)
pos1 = receivedData.IndexOf("<") + 1
pos2 = receivedData.IndexOf(">") + 1
End If
If (pos1 = 0 Or pos2 = 0) Then
' we do not have both start and end markers and we are done
done = True
Else
' we have both start and end markers
length = pos2 - pos1 + 1
If (length > 0) Then
'remove the start and end markers from the command
newCommand = Mid(receivedData, pos1 + 1, length - 2)
' show the command in the text box
RichTextBox1.Text = ""
RichTextBox1.AppendText(newCommand & vbCrLf)
'remove the command from receivedData
receivedData = Mid(receivedData, pos2 + 1)
'RichTextBox1.Text &= receivedData
uart_in = RichTextBox1.Text
data = ""
'RichTextBox2.Text = Mid(RichTextBox1.Text, 6, 3)
'If RichTextBox1.TextLength = 26 Then
can_id = Mid(uart_in, 6, 3) 'extracting and id
dlc = Mid(uart_in, 10, 1)
data = uart_in.Substring(26 - (dlc * 2))
hex2ascii(data)
data = data.InsertEveryNthChar(" ", 2)
' data = ReverseString(data)
Dim articlecheck As String = can_id
Dim founditem As ListViewItem = ListView1.FindItemWithText(articlecheck)
If Not (founditem Is Nothing) Then
founditem.SubItems(0).Text = can_id
founditem.SubItems(1).Text = dlc
' If founditem.SubItems(2).Text <> data Then
' founditem.SubItems(2).ForeColor = Color.LightYellow
founditem.SubItems(2).Text = data
' End If
founditem.SubItems(3).Text = timer_count - founditem.SubItems(3).Text
founditem.SubItems(4).Text = founditem.SubItems(4).Text + 1
founditem.SubItems(5).Text = asciival
' timer_count = 1
first_msg = 0
Else
Dim lvi As New ListViewItem(can_id)
lvi.SubItems.Add(dlc)
lvi.SubItems.Add(data)
lvi.SubItems.Add(timer_count)
lvi.SubItems.Add(count)
lvi.SubItems.Add(asciival)
ListView1.Items.Add(lvi)
End If
End If ' (length > 0)
End If '(pos1 = 0 Or pos2 = 0)
End While
End Function
Function hex2ascii(ByVal hextext As String) As String
Dim a As Integer
Dim y As Integer
Dim value As String
Dim num As String
For y = 1 To Len(hextext) Step 2
num = Mid(hextext, y, 2)
a = Val("&h" & num)
If a = 160 Or a = 0 Or a = 9 Or a = 32 Or a = 11 Then a = 46
value = value & Chr(a)
Next
asciival = value
End Function
Dim System.Threading.Thread yourthread As New System.Threading.Thread(AddressOf yourfunction())
yourthread.Priority = System.Threading.Priority.Highest
yourthread.Start();
you can create a loop in your function and add System.Threading.Thread.Sleep(1000) in the end of the loop to make it work like a timer. You can call all your existing functions through this thread, even the timer.
Be careful while accessing your controls through the thread.
Invoke(Sub() yourcontrol.property = someproperty)
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 am trying to write an encryption program. The problem I am facing is that I am converting the text to ascii and then adding on the offset. However when it goes past the letter 'z' I want it to warp back to 'a' and go from there.
Sub enc()
Text = TextBox1.Text
finalmessage = ""
letters = Text.ToCharArray
offset = ComboBox1.SelectedItem
For x = LBound(letters) To UBound(letters)
finalmessage = finalmessage + Chr(Asc(letters(x)) + offset)
Next
TextBox2.Text = finalmessage
End Sub
I guess to make it easy to decode afterwards, you should to it somewhat in the line of base64 encoding, first encoding everything to a normalized binary string, then encode in the range you want (since using binary, it has to be something that fits with 2^X).
To match your range, i used a baseset of 32, and a simple encoding decoding example (a bit more verbose that it should be, perhaps)
Module Module1
Dim encodeChars As String = "abcdefghijklmnopqrstuvwxyzABCDEF" ' use 32 as a base
Function Encode(text As String) As String
Dim bitEncoded As String = ""
Dim outputMessage As String = ""
For Each ch As Char In text.ToCharArray()
Dim i As Integer = Convert.ToByte(ch)
bitEncoded &= Convert.ToString(i, 2).PadLeft(8, "0"c)
Next
While bitEncoded.Length Mod 5 <> 0
bitEncoded &= "0"
End While
For position As Integer = 0 To bitEncoded.Length - 1 Step 5
Dim range As String = bitEncoded.Substring(position, 5)
Dim index As Integer = Convert.ToInt32(range, 2)
outputMessage &= encodeChars(index).ToString()
Next
Return outputMessage
End Function
Function Decode(encodedText As String) As String
Dim bitEncoded As String = ""
Dim outputMessage As String = ""
For Each ch In encodedText
Dim index As Integer = encodeChars.IndexOf(ch)
If index < 0 Then
Throw New FormatException("Invalid character in encodedText!")
End If
bitEncoded &= Convert.ToString(index, 2).PadLeft(5, "0"c)
Next
' strip the extra 0's
While bitEncoded.Length Mod 8 <> 0
bitEncoded = bitEncoded.Substring(0, bitEncoded.Length - 1)
End While
For position As Integer = 0 To bitEncoded.Length - 1 Step 8
Dim range As String = bitEncoded.Substring(position, 8)
Dim index As Integer = Convert.ToInt32(range, 2)
outputMessage &= Chr(index).ToString()
Next
Return outputMessage
End Function
Sub Main()
Dim textToEncode As String = "This is a small test, with some special characters! Just testing..."
Dim encodedText As String = Encode(textToEncode)
Dim decodedText As String = Decode(encodedText)
Console.WriteLine(textToEncode)
Console.WriteLine(encodedText)
Console.WriteLine(decodedText)
If Not String.Equals(decodedText, textToEncode) Then
Console.WriteLine("Encoding / decoding failed!")
Else
Console.WriteLine("Encoding / decoding completed succesfully!")
End If
Console.ReadLine()
End Sub
End Module
this then gives the following output?
This is a small test, with some special characters! Just testing...
krugsCzanfzsayjaonwwcBdmebAgkCBufqqhoAlunaqhgBBnmuqhgCdfmnuwcBbamnugcCtbmnAgkCtteeqeuDltoqqhizltoruwCzzofyxa
This is a small test, with some special characters! Just testing...
Encoding / decoding completed succesfully!