Incorrect values are written to the text file - vb.net

I want to write the values of a sine function to a text file. The function is
In my graphing calculator, I also have to add π if I want to plot the function in radians.
How do I have to write this in the source code? Wrong values come out every time, regardless of whether I insert or leave out π.
I would like to have a y-value of 0 for t = 0 to 14400, and also from t = 69060 onwards. In between, according to its formula, the sine function of y = 0 should rise, reach 8, and fall again (second zero as said at 69060).
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
Dim Path As String = ""
Using SFD As New CommonSaveFileDialog
SFD.Title = "Ordner, in dem die Textdatei gespeichert werden soll, auswählen"
SFD.Filters.Add(New CommonFileDialogFilter("Textdateien", ".txt"))
Dim di As New IO.DirectoryInfo(Application.StartupPath)
If di.Parent.Name = "bin" Then
di = di.Parent.Parent.Parent ' AnyCPU
ElseIf di.Parent.Parent.Name = "bin" Then
di = di.Parent.Parent.Parent.Parent ' x64, x86
End If
If System.IO.Directory.Exists(di.FullName) Then
SFD.InitialDirectory = di.FullName
Else
SFD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
End If
If SFD.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD.FileName & ".txt"
Else
Return
End If
End Using
ButtonStart.BackColor = Color.FromArgb(255, 255, 0)
Application.DoEvents()
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, False, System.Text.Encoding.UTF8)
textfile.WriteLine($"Time{Tab}V(OUT)")
For t As UInt32 = 0UI To 86400UI Step 1UI
If t < 14400UI OrElse (t >= 14400UI AndAlso t <= 69060UI) Then
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & 0.0.ToString(Eng))
Else
Dim Value As Double = 8.0 * Math.Sin(1.0 * Math.PI / 54660.0 * t + 2.0 * Math.PI - 0.2634467618)
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & Value.ToString(Eng))
End If
Next
textfile.Close()
End Using
ButtonStart.BackColor = Color.FromArgb(0, 255, 0)
End Sub

This should be your function
Function f(t As Double) As Double
Dim amplitude = 8
Dim period = 54660
Dim phaseDegrees = 177
Dim phaseRadians = phaseDegrees * Math.PI / 180
Dim vertical = 0
Dim a = amplitude
Dim b = 2 * Math.PI / period
Dim c = phaseRadians
Dim d = vertical
Return a * Math.Sin(b * (t + c)) + d
End Function
See image, from https://www.mathsisfun.com/algebra/amplitude-period-frequency-phase-shift.html

I found a solution. It has to be
Amplitude * sin(2πf*t + phase in rad) + offset
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, False, System.Text.Encoding.UTF8)
For t As UInt32 = 0UI To 86400UI Step 1UI
If t < 14400UI OrElse (t > 69060UI AndAlso t <= 86400UI) Then
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & 0.0.ToString(Eng))
Else
Dim Value As Double = 4.0 * Math.Sin(2 * Math.PI * 1.0 / 54660.0 * t + 177.0 * Math.PI / 180.0) + 4.0
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & Value.ToString(Eng))
End If
Next
textfile.Close()
End Using

Related

As population increases the SIR model graph should shift left. And the recovery & transmission rate trackbars don't work at all

I'm trying to simulate the spread of a virus using the SIR model in VB.net but my code doesn't work.
increase initial infections: should shift graph left (but mine doesn't)
increase Population: shifts graph left (but mine doesn't)
increase Susceptible: shifts graph left (but mine doesn't)
increase transmission rate (b): increases peak of 'infectives' curve (but my trackbar doesn't work at all - produces an overflow error)
increase recovery rate (a): 'infectives' peak decreases, while the other two lines go up
This is what the graph should do: https://faradars.org/ev/sir-simulator/?lang=en
These images demonstrate the errors in my code that I don't know how to fix:
Here's my code:
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'initail values
Dim N As Double = 10000
Dim S As Double = 8000
Dim R = 0.0
Dim I As Double = N - S - R
Dim t As Double = 0
Dim b As Double = 2 'contact rate
Dim a As Double = 0.5 'removal rate
Dim scale As Double = 0.1
setupForm(N, S, I, R, t, b, a, scale)
ProccessGraph()
End Sub
Sub setupForm(N, S, I, R, t, b, a, scale)
'Trackbars
Dim tbData(7) As Decimal
tbData(1) = N 'population N
tbData(2) = S 'Susceptibles S
tbData(3) = I 'infectives I
tbData(4) = R 'Recoveries R
tbData(5) = t 'time t
tbData(6) = b 'infection rate b
tbData(7) = a 'removal rate a
Dim y As Integer = 10
For I = 1 To 7
Dim Tbar As New TrackBar
With Tbar
.Location = New Point(20, y)
.Size = New Size(140, 30)
.BackColor = Color.White
.Minimum = 0
.Maximum = 10000
.SmallChange = 1
.Name = "Trackbar" & I
.Value = tbData(I)
End With
Me.Controls.Add(Tbar)
'labels (display value) ✓
Dim labvalue As New Label
With labvalue
.Location = New Point(180, y)
.Name = "label" & I
.Size = New Size(50, 15)
End With
Me.Controls.Add(labvalue)
'labels (tbar title) ✓
Dim labtitle_data(7) As String
labtitle_data(1) = "Population N"
labtitle_data(2) = "Susceptibles S"
labtitle_data(3) = "Infectives I"
labtitle_data(4) = "Recoveries R"
labtitle_data(5) = "time"
labtitle_data(6) = "infection rate"
labtitle_data(7) = "removal rate"
Dim labtitle As New Label
With labtitle
.Location = New Point(240, y)
.Name = "label" & I
.Size = New Size(60, 60)
.Text = labtitle_data(I)
End With
y += 60
Me.Controls.Add(labtitle)
'ComboBox (to list countries) ✓
Dim cb1 As New ComboBox
cb1.Items.Add("China")
cb1.Location = New Point(990, 50)
Me.Controls.Add(cb1)
'Form properties ✓
Me.Size = New Size(1200, 500)
Me.BackColor = Color.White
AddHandler Tbar.ValueChanged, AddressOf ProccessGraph 'every time the value changes, recreate the graph to match it
Next
End Sub
Sub ProccessGraph()
Dim tblist(7) As TrackBar 'array of trackbars
For tbar = 1 To 7
tblist(tbar) = Me.Controls("TrackBar" & tbar)
Me.Controls("label" & tbar).Text = tblist(tbar).Value 'adds value to label
Next
'reset NSIR values to match trackbar values
Dim N = tblist(1).Value
Dim S = tblist(2).Value
Dim I = tblist(3).Value
Dim R = tblist(4).Value
Dim t = tblist(5).Value
Dim b = tblist(6).Value
'Dim a = tblist(7).Value
Dim a As Double = 0.5
Dim scale As Double = 0.1
'b = tblist(6).Value
'a = tblist(7).Value
'chart lines ✓
Chart1.Series.Clear()
Chart1.Titles.Clear()
Dim serS As New Series
Dim serI As New Series
Dim serR As New Series
serS.Name = "S"
serS.ChartType = SeriesChartType.Line
serS.BorderWidth = 2
serI.Name = "I"
serI.ChartType = SeriesChartType.Line
serI.BorderWidth = 2
serR.Name = "R"
serR.ChartType = SeriesChartType.Line
serR.BorderWidth = 2
'chart calculations ✓
For ind = 0 To 99
serS.Points.AddXY(t, S)
serI.Points.AddXY(t, I)
serR.Points.AddXY(t, R)
Dim ds = (-b * S * I) / N
Dim Di = ((b * S * I) / N) - a * I
Dim Dr = a * I
Dim dt = 1
S = S + ds * scale
I = I + Di * scale
R = R + Dr * scale
t = t + dt * scale
Next
'chart properties ✓
Chart1.Series.Add(serS)
Chart1.Series.Add(serI)
Chart1.Series.Add(serR)
Chart1.ChartAreas("ChartArea1").AxisX.Title = "Days"
Chart1.ChartAreas("ChartArea1").AxisY.Title = "Population"
Chart1.ChartAreas("ChartArea1").AxisX.Interval = 10
Chart1.ChartAreas("ChartArea1").AxisY.Interval = 500
Chart1.Titles.Add("SIR Graph")
Chart1.Location = New Point(280, 30)
Chart1.Size = New Size(700, 400)
''trackbar colors which, remember, are only accessible via the array tbs
'tblist(1).BackColor = Color.LightGray
'tblist(2).BackColor = Color.Blue
'tblist(3).BackColor = Color.Yellow
'tblist(4).BackColor = Color.LightCoral
End Sub
End Class`
Existing SIR models:
https://faradars.org/ev/sir-simulator/?lang=en
Existing SIR models code:
https://www.google.com/amp/s/jamesmccaffrey.wordpress.com/2020/02/11/the-kermack-mckendrick-sir-disease-model-using-c/amp/
https://github.com/henrifroese/infectious_disease_modelling/blob/master/part_two.ipynb

VB .NET - Full text alignment title form at left

I have this code to align the form's title but I can not totally align with it, when I put a space for it to go totally left it works but it adds 3 points at the end, does anyone have any idea with fixing this?
Form FIXED SINGLE STYLE
Thank you all for the time
Private Sub ALINHAMENTO()
Dim g As Graphics = Me.CreateGraphics()
Dim startingPoint As Double = (Me.Width / 2) - (g.MeasureString(Me.Text.Trim, Me.Font).Width / 2)
Dim widthOfASpace As Double = g.MeasureString(" ", Me.Font).Width
Dim tmp As String = " "
Dim tmpWidth As Double = 0
Do
tmp += " "
tmpWidth += widthOfASpace
Loop While (tmpWidth + widthOfASpace) < startingPoint
Me.Text = Me.Text.Trim & tmp
End Sub
RUNNING
Solution based in idea of : Olivier Jacot-Descombes
Private Sub ALINHAMENTO()
Dim g As Graphics = Me.CreateGraphics()
Dim startingPoint As Double = (Me.Width / 1.3) - (g.MeasureString(Me.Text.Trim, Me.Font).Width / 1)
Dim widthOfASpace As Double = g.MeasureString(" ", Me.Font).Width
Dim tmp As String = " "
Dim tmpWidth As Double = 0
Do
tmp += " "
tmpWidth += widthOfASpace
Loop While (tmpWidth + widthOfASpace) < startingPoint
Me.Text = Me.Text.Trim & tmp
End Sub

Out of Memory Error when using graphics

I have been making a game for my games development class but due to the limitations in college we have to create a game using Visual Basic and no plugins, so I only have GDI+ to work with.
I have run into an error where it will run out of memory and the game stops running, the error is at line 312 - "_backBufferGr.DrawImage(_backbuffer, 0, 0, _resWidth, _resHeight)"
I think it may be due to the images that are being spawned aren't being cleared but I'm not sure as I have only been coding for about 3 months. If anyone can help that would be very appreciated. I have attached the code below - the classes are in separate files in my project.
Here is an image of my error:
https://imgur.com/WEAwSb4
and as text:
System.OutOfMemory: Out of memory.
at System.Drawing.Graphics.CheckErrorStatus(Int32 Status)
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 Width, Int32 height)
at SpaceInvaders.Spaceinvaders.DrawGraphics()
Imports System.Drawing.Imaging
Imports System.IO
Public Class Spaceinvaders
'Star Generation Variables
ReadOnly _random As New Random
Private ReadOnly _r As New Random
Private ReadOnly _stars As New List(Of Point)
'Sound Variabless
Public Shared Intsound As Integer = 0
Public Shared Snd As New Sounds
'Graphics varibles
Dim _backbuffer As Bitmap
Dim _backBufferGr As Graphics
Public Shared Gr As Graphics
Shared _sourceRec As Rectangle
'View Port Variables
Dim _resWidth As Int16 = 700
Dim _resHeight As Int16 = 650
Dim _paused As Boolean = False
Dim _pauseNum As Int16 = 0
Dim _pausedText As Int16 = 40
Dim _mouseX, _mouseY As Int16
'Key Detection
Public Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Int16) As Int16
Public Function GetKeyState(ByVal key1 As Int16) As Boolean
Dim s As Int16
s = GetAsyncKeyState(key1)
If s = 0 Then Return False
Return True
End Function
'Character Variables
Dim _bmpPlayer As Bitmap
Public Shared PlayerW, PlayerH As Int16
Public Shared XPos As Int16 = 0
Public Shared YPos As Int16 = 0
Dim _movementSpeed As Int16 = 8
Dim _moveDir As Int16 = 0
Dim _lastDir As Int16 = 0
'Fire Variables
Dim _fire As Boolean
Dim _bulletArray(100000) As Bullet
Dim _bulletNum As Int16 = 0
Dim _cooldown As Int16
Public Shared Points As Int32 = 0
Public Shared EnemiesKilled As Int16 = 0
Public Shared ExploArray(100000) As Explo
Public Shared ExploNum As Int16 = 0
'Enemy Variables
Dim _spawnNum As Int16
Public Shared EnemyArray(100000) As Enemies
Public Shared EnemyNum As Int16 = 0
Public Shared Lives As Int16 = 3
Dim SpawnSpd As Int16 = 30
'Other Variables
Dim _isRunning As Boolean = True
Public Shared CollitionDetc As New StreamWriter(Application.StartupPath() & "\" & "Detection" & ".Log")
Public Function FadeInImage(ByVal bmp As Bitmap, ByVal opacity As Single) As Bitmap
Dim bmp2 As New Bitmap(bmp.Width, bmp.Height, PixelFormat.Format32bppArgb)
opacity = Math.Max(0, Math.Min(opacity, 1.0F))
Using ia As New ImageAttributes
Dim cm As New ColorMatrix
cm.Matrix33 = opacity
ia.SetColorMatrix(cm)
Dim destpoints() As PointF = {New Point(0, 0), New Point(bmp.Width, 0), New Point(0, bmp.Height)}
Using g As Graphics = Graphics.FromImage(bmp2)
g.DrawImage(bmp, destpoints, New RectangleF(Point.Empty, bmp.Size), GraphicsUnit.Pixel, ia)
End Using
End Using
Return bmp2
End Function
'Form Events
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Show()
Focus()
'Create Stars - 300 is the Number of Stars
CreateStarField(300)
'Start Music
Intsound += 1
With Snd
.Name = "Sound" & Intsound
.PlaySound(1, True)
End With
'This creates the graphics and the backbuffer, along with drawing the player to the screen
Gr = CreateGraphics()
_backbuffer = New Bitmap(_resWidth, _resHeight)
_bmpPlayer = New Bitmap(My.Resources.Ship)
XPos = (Width / 2)
YPos = 500
Gr.DrawImage(_bmpPlayer, XPos, YPos, _sourceRec, GraphicsUnit.Pixel)
StartGameLoop()
End Sub
Private Sub Spaceinvaders_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Do Until Intsound = 0
Snd.Kill("Sound" & Intsound)
Intsound -= 1
Loop
Dispose()
End
End Sub
Private Sub Spaceinvaders_MouseMove(sender As Object, e As MouseEventArgs) Handles MyBase.MouseMove
_mouseX = e.X
_mouseY = e.Y
End Sub
Private Sub Spaceinvaders_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown
If (290 + 110 < _mouseX Or _mouseX < 290 Or 336 + 63 < _mouseY Or _mouseY < 336) Then
Else
_paused = False
End If
End Sub
'Starfield Background Generation
Private Sub CreateStarField(numStars As Integer)
_stars.Clear()
For i = 1 To numStars
_stars.Add(New Point(_r.Next(0, Width), _r.Next(0, Height)))
Next
End Sub
'Runs the actual game over and over again until it is stopped
Sub StartGameLoop()
Do While _isRunning = True
Application.DoEvents()
LivesCheck()
SetMoveDir()
MovePlayer(_moveDir)
'Start the drawing events & FPS Counter
DrawGraphics()
Loop
Do While _isRunning = False
Application.DoEvents()
Loop
End Sub
'Subs to do with player creation and movement
Private Sub GetPlayer(ByVal dir As Int16)
Select Case dir
Case 1 'Upfacing Direction
_bmpPlayer = New Bitmap(My.Resources.Ship)
_sourceRec = New Rectangle(0, 0, 85, 50)
PlayerH = 50
PlayerW = 85
Case 2 'Downfacing Direction
_bmpPlayer = New Bitmap(My.Resources.Ship)
_sourceRec = New Rectangle(0, 0, 85, 50)
PlayerH = 50
PlayerW = 85
Case 3 'Left Facing Direction
_bmpPlayer = New Bitmap(My.Resources.ShipLeft)
_sourceRec = New Rectangle(0, 0, 96, 76)
PlayerH = 76
PlayerW = 96
Case 4 'Right Facing Direction
_bmpPlayer = New Bitmap(My.Resources.ShipRight)
_sourceRec = New Rectangle(0, 0, 96, 76)
PlayerH = 76
PlayerW = 96
End Select
End Sub
Sub SetMoveDir()
If GetKeyState(Keys.W) = True Then _moveDir = 1
If GetKeyState(Keys.A) = True Then _moveDir = 3
If GetKeyState(Keys.S) = True Then _moveDir = 2
If GetKeyState(Keys.D) = True Then _moveDir = 4
If GetKeyState(Keys.Space) = True Then _fire = True
If GetKeyState(Keys.P) = True Then
If _pauseNum = 0 Then
_paused = True
_pauseNum = 1
ElseIf _pauseNum = 1 Then
_paused = False
_pauseNum = 0
End If
End If
If GetKeyState(Keys.W) = False And
GetKeyState(Keys.A) = False And
GetKeyState(Keys.S) = False And
GetKeyState(Keys.D) = False Then
_moveDir = 0
End If
If _moveDir <> 0 Then _lastDir = _moveDir
End Sub
Private Sub MovePlayer(ByVal dir As Int16)
Select Case dir
Case 1
If YPos <= 0 Then
Else
YPos -= _movementSpeed
End If
Case 2
If YPos >= 544 Then
Else
YPos += _movementSpeed
End If
Case 3
If XPos <= -2 Then
Else
XPos -= _movementSpeed
End If
Case 4
If XPos >= 606 Then
Else
XPos += _movementSpeed
End If
End Select
End Sub
'Draw the stuff to the screen
Sub DrawGraphics()
If _paused = True Then
Gr.DrawString("Paused", New Font("Verdana", _pausedText), New SolidBrush(Color.White), New Point(235, 256))
If (290 + 110 < _mouseX Or _mouseX < 290 Or 336 + 63 < _mouseY Or _mouseY < 336) Then
Gr.DrawString("Play", New Font("Verdana", 25), New SolidBrush(Color.White), New Point(290, 336))
Else
Gr.DrawString("Play", New Font("Verdana", 25), New SolidBrush(Color.Red), New Point(290, 336))
End If
'Copy BackBuffer To Graphics Object
Gr = Graphics.FromImage(_backbuffer)
'Draw BackBuffer to the screen
Try
_backBufferGr = CreateGraphics()
_backBufferGr.DrawImage(_backbuffer, 0, 0, _resWidth, _resHeight)
Catch ex As Exception
MsgBox(ex)
_isRunning = False
Exit Sub
End Try
Gr.Clear(Color.Black)
'Runs when the game is unpaused
ElseIf _paused = False Then
Gr.Clear(Color.Black)
'Draws Stars to the screen
DrawStars()
'Draws Enemies to the screen
EnemyDraw()
'Draws bullets to the screen
BulletDraw()
'Draws Explosions
Expslostion()
'Draw the player
DrawPlayer()
'Draws lives to the screen
DrawHUD()
'Copy BackBuffer To Graphics Object
Gr = Graphics.FromImage(_backbuffer)
'Draw BackBuffer to the screen
Try
_backBufferGr = CreateGraphics()
_backBufferGr.DrawImage(_backbuffer, 0, 0, _resWidth, _resHeight)
Catch ex As Exception
MsgBox("ERROR: " & vbCrLf & ex.ToString)
_isRunning = False
Exit Sub
End Try
Gr.Clear(Color.Black)
GC.Collect()
_fire = False
WriteLog()
End If
End Sub
Sub BulletDraw()
If _bulletNum = 0 Then
_bulletNum = 0
Else
For i = 1 To _bulletNum
_bulletArray(i).Move(i)
Next
End If
If _cooldown < 2 Then
_cooldown += 1
Else : If _fire = True Then
_bulletNum += 1
_bulletArray(_bulletNum) = New Bullet
_bulletArray(_bulletNum).Spawn(_bulletNum, 4)
_cooldown = 0
End If : End If
End Sub
Sub EnemyDraw()
If EnemyNum = 0 Then
EnemyNum = 0
Else
For i = 1 To EnemyNum
EnemyArray(i).Move()
Next
End If
If _spawnNum < SpawnSpd Then
_spawnNum += 1
Else
Points += 5
EnemyNum += 1
EnemyArray(EnemyNum) = New Enemies
EnemyArray(EnemyNum).Spawn()
_spawnNum = 0
End If
End Sub
Sub Expslostion()
If ExploNum = 0 Then
ExploNum = 0
Else
For i = 1 To ExploNum
ExploArray(i).Animation()
Next
End If
End Sub
Sub DrawStars()
For Each pt As Point In _stars 'Loops until all the stars are added to the form background
Dim num = _random.Next(1, 6) 'Randomly Picks a number
Dim numSize = _random.Next(1, 3)
If num = 1 Then 'Picks a colour based on the number picked
Gr.FillEllipse(Brushes.White, New Rectangle(pt, New Size(numSize, numSize)))
ElseIf num = 2 Then
Gr.FillEllipse(Brushes.Blue, New Rectangle(pt, New Size(numSize, numSize)))
ElseIf num = 3 Then
Gr.FillEllipse(Brushes.DimGray, New Rectangle(pt, New Size(numSize, numSize)))
ElseIf num = 4 Then
Gr.FillEllipse(Brushes.DarkOrange, New Rectangle(pt, New Size(numSize, numSize)))
ElseIf num = 5 Then
Gr.FillEllipse(Brushes.Red, New Rectangle(pt, New Size(numSize, numSize)))
End If
Next
End Sub
Sub DrawPlayer()
If _moveDir = 0 Then
_bmpPlayer = New Bitmap(My.Resources.Ship)
Else
GetPlayer(_lastDir)
End If
_bmpPlayer.MakeTransparent(Color.Fuchsia)
Gr.DrawImage(_bmpPlayer, XPos, YPos, _sourceRec, GraphicsUnit.Pixel)
End Sub
Sub DrawHUD()
Select Case Lives
Case 3
Gr.FillRectangle(Brushes.Red, 510, 5, 150, 10)
Case 2
Gr.FillRectangle(Brushes.Red, 510, 5, 100, 10)
Case 1
Gr.FillRectangle(Brushes.Red, 510, 5, 50, 10)
End Select
Gr.DrawString("Ships Destroyed: " & EnemiesKilled, New Font("Verdana", 10), New SolidBrush(Color.White), New Point(5, 5))
Gr.DrawString("Score: " & Points, New Font("Verdana", 10), New SolidBrush(Color.White), New Point(5, 20))
End Sub
Sub WriteLog()
Dim sw As New StreamWriter(Application.StartupPath() & "\" & "Variables" & ".Log")
sw.WriteLine("--------Variables Log--------")
sw.WriteLine("")
sw.WriteLine("Sounds Playing: " & Intsound)
sw.WriteLine("")
sw.WriteLine("Window Resolution: " & _resWidth & " " & _resHeight)
sw.WriteLine("Game Running: " & _isRunning)
sw.WriteLine("")
sw.WriteLine("Player Postion: " & XPos & " " & YPos)
sw.WriteLine("Player Size: " & PlayerW & " " & PlayerH)
sw.WriteLine("Player Movement Speed: " & _movementSpeed)
sw.WriteLine("PLayer Last Direction: " & _lastDir)
sw.WriteLine("")
sw.WriteLine("Bullets Being Fired?: " & _fire)
sw.WriteLine("Number Of bullets spawned: " & _bulletNum)
sw.WriteLine("")
sw.WriteLine("Number of enemies spawned: " & EnemyNum)
sw.WriteLine()
sw.WriteLine("--------Bullet Variables--------")
sw.WriteLine("Bullet Number X Y")
For i = 1 To _bulletNum
sw.WriteLine(i & " " & _bulletArray(i).X & " " & _bulletArray(i).Y)
Next
sw.WriteLine("--------Enemy Variables--------")
sw.WriteLine("Enemy Number X Y")
For i = 1 To EnemyNum
sw.WriteLine(i & " " & EnemyArray(i).X & " " & EnemyArray(i).Y)
Next
sw.Close()
sw.Dispose()
End Sub
Sub LivesCheck()
If Lives = 0 Then
_isRunning = False
Gameover.Show()
End If
End Sub
End Class
Public Class Bullet
Dim _bulletX, _bulletY As Int16
Dim _bmpBullet As Bitmap = My.Resources.bullet1
Dim _bulletRec As New Rectangle
Dim _bulletSpd As Int16 = 4
Dim _enemyNum As Int16
Dim _active As Boolean = True
Function X()
Return _bulletX
End Function
Function Y()
Return _bulletY
End Function
Sub Spawn(ByVal i As Int16, ByVal s As Int16)
Spaceinvaders.Intsound += 1
With Spaceinvaders.Snd
.Name = "Sound" & Spaceinvaders.Intsound
.PlaySound(2, False)
End With
_bulletSpd = s
_bulletX = Spaceinvaders.XPos + (Spaceinvaders.PlayerW / 2)
_bulletY = Spaceinvaders.YPos + (Spaceinvaders.PlayerH / 2)
_bmpBullet = My.Resources.bullet1
_bmpBullet.MakeTransparent(Color.Fuchsia)
Spaceinvaders.Gr.DrawImage(_bmpBullet, _bulletX, _bulletY, _bulletRec, GraphicsUnit.Pixel)
End Sub
Sub Move(ByVal bulletNum As Int16)
If _active = False Then
Me.Finalize()
Else
_enemyNum = Spaceinvaders.EnemyNum
For i = 1 To _enemyNum
Dim EnemyRect As Rectangle
EnemyRect = Spaceinvaders.EnemyArray(i).Rectangle
If (_bulletRec.IntersectsWith(EnemyRect)) Then
If Spaceinvaders.EnemyArray(i).Invc >= 40 Then
Spaceinvaders.EnemyArray(i).Kill(-10, -10)
_active = False
Spaceinvaders.Points += 500
Spaceinvaders.CollitionDetc.WriteLine("Enemy Num: " & i & " & " & "Bullet Num: " & bulletNum & " - HIT")
_bulletX = -100
_bulletY = -100
_bulletRec = New Rectangle(-100, 100, 1, 1)
Spaceinvaders.Intsound += 1
With Spaceinvaders.Snd
.Name = "Sound" & Spaceinvaders.Intsound
.PlaySound(3, False)
End With
Dim enemyX, enemyY As Int16
enemyX = Spaceinvaders.EnemyArray(i).X
enemyY = Spaceinvaders.EnemyArray(i).Y
Spaceinvaders.ExploNum += 1
Spaceinvaders.ExploArray(Spaceinvaders.ExploNum) = New Explo()
Spaceinvaders.ExploArray(Spaceinvaders.ExploNum).Spawn(enemyX, enemyY)
Me.Finalize()
End If
End If
Next
If _bulletY <= 0 Then
_bulletX = -100
_bulletY = -100
Else
_bulletY -= _bulletSpd
_bmpBullet.MakeTransparent(Color.Fuchsia)
Spaceinvaders.Gr.DrawImage(_bmpBullet, _bulletX, _bulletY)
_bulletRec = New Rectangle(_bulletX, _bulletY, 16, 16)
End If
End If
End Sub
End Class
Public Class Enemies
Dim _enemyX, _enemyY As Int16
Dim _bmpEnemy As Bitmap = My.Resources.InvaderSkullWhite
Dim _moveNum As Int16 = 0
Dim _active As Boolean = True
Dim _tempInvc As Int16 = 0
Dim EnemyRect As Rectangle
Function X()
Return _enemyX
End Function
Function Y()
Return _enemyY
End Function
Function Kill(ByVal x, ByVal y)
_enemyX = x
_enemyY = y
_active = False
EnemyRect = New Rectangle(x, y, 1, 1)
Me.Finalize()
End Function
Function Invc()
Return _tempInvc
End Function
Function Rectangle()
Return EnemyRect
End Function
Sub Spawn()
Dim rand As New Random
_enemyY = 3
_enemyX = rand.Next(10, 600)
Select Case rand.Next(1, 5)
Case 1
_bmpEnemy = My.Resources.InvaderSkullWhite
Case 2
_bmpEnemy = My.Resources.InvaderSkullRed
Case 3
_bmpEnemy = My.Resources.InvaderSkullGreen
Case 4
_bmpEnemy = My.Resources.InvaderSkullYellow
End Select
_bmpEnemy.MakeTransparent(Color.Fuchsia)
Spaceinvaders.Gr.DrawImage(_bmpEnemy, _enemyX, _enemyY)
Move()
End Sub
Sub Move()
If _active = False Then
Me.Finalize()
Else
If _tempInvc < 40 Then
_tempInvc += 1
End If
If _moveNum < 10 Then
_moveNum += 1
_bmpEnemy.MakeTransparent(Color.Fuchsia)
Spaceinvaders.Gr.DrawImage(_bmpEnemy, _enemyX, _enemyY)
Else
If _enemyY >= 700 Then
Spaceinvaders.Lives -= 1
_enemyX = -5
_enemyY = -5
Else
Dim randX As New Random
_enemyY += 5
Select Case _enemyX
Case _enemyX <= 5
_enemyX = _enemyX + randX.Next(1, 4)
Case _enemyX >= 600
_enemyX = _enemyX + randX.Next(-4, -1)
Case Else
_enemyX = _enemyX + randX.Next(-4, 4)
End Select
_bmpEnemy.MakeTransparent(Color.Fuchsia)
Spaceinvaders.Gr.DrawImage(_bmpEnemy, _enemyX, _enemyY)
EnemyRect = New Rectangle(_enemyX, _enemyY, 64, 64)
End If
_moveNum = 0
End If
End If
End Sub
End Class
Public Class Sounds
Public Declare Function MciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Dim _appPath As String = Application.StartupPath()
Private _oName As String = Nothing
Public Property Name As String
Set(value As String)
_oName = value
End Set
Get
Return _oName
End Get
End Property
Public Sub PlaySound(ByVal id As Integer, ByVal repeat As Boolean, Optional vol As Integer = 35)
If repeat = True Then
MciSendString("Open " & GetFile(id) & " alias " & _oName, 0, 0, 0)
MciSendString("Play " & _oName & " repeat", CStr(0), 0, 0)
Else
MciSendString("Open " & GetFile(id) & " alias " & _oName, CStr(0), 0, 0)
MciSendString("Play " & _oName, CStr(0), 0, 0)
End If
'Set Vol
MciSendString("Open " & GetFile(id) & " alias " & _oName, CStr(0), 0, 0)
MciSendString("setaudio " & _oName & " volume to " & vol, CStr(0), 0, 0)
End Sub
Private Function GetFile(ByVal id As Integer) As String
Dim path As String = ""
'Here is where you put the sound paths so that your game can play sounds
Select Case id
Case 0 'Menu Background Music
path = _appPath & "\Audio\Menu.mp3"
Case 1 'Ingame Background Music
path = _appPath & "\Audio\InGame.mp3"
Case 2 'Fire Spund
path = _appPath & "\Audio\Lazer.mp3"
Case 3 'Expolsion sound
path = _appPath & "\Audio\Expolsion.mp3"
End Select
path = Chr(34) & path & Chr(34)
Return path
End Function
Public Sub Kill(ByVal song As String)
MciSendString("close " & song, CStr(0), 0, 0)
_oName = Nothing
End Sub
End Class
Whenever you're done with an object that implements IDisposable in almost all cases you should probably call it (there are exceptions outside the scope of this answer). For note, A "using" statement always calls Dispose when it's done (so you're Graphics calls that are using a using are good on that front).
Where I see potential problems are the places you're using a class wide variable and resetting new Bitmap's onto it (I don't think the old one's get disposed and as a result I think they're hanging out there and slowly eating up your memory).
_bmpPlayer = New Bitmap(My.Resources.Ship)
See if something like this helps:
If _bmpPlayer IsNot Nothing Then
_bmpPlayer.Dispose()
End If
_bmpPlayer = new Bitmap(My.Resources.Ship)
That said, if you're using these same images over and over I would probably store them and re-use them as opposed to re-writing a new Bitmap from the resource every time.
Thanks to everyone trying to help me fix the problem. I fixed the out of memory error by changing this bit of code:
If _bulletNum = 0 Then
_bulletNum = 0
Else
For i = 1 To _bulletNum
_bulletArray(i).Move(i)
Next
End If
To this:
If _bulletNum = 0 Then
_bulletNum = 0
Else
Dim skipbullet As Int16
skipbullet = _bulletNum - 50
If skipbullet >= 1 Then
For i = skipbullet To _bulletNum
_bulletArray(i).Move(i)
Next
For i = 1 To skipbullet
_bulletArray(i).Kill()
Next
Else
For i = 1 To _bulletNum
_bulletArray(i).Move(i)
Next
End If
End If

Backgroundworker not starting copy

I am a novice at VB.NET and am working on an app the read the contents of a text file and use the paths therein for a file/folder copy. I am running the copy through a backgroundworker which does not seem to take the line string. To troubleshoot I have placed a MessageBox.Show(line) under the line reading logic to see if it is reading the path. It is not and jumps straight to my BackgroundWorker1_RunWorkerCompleted sub.
Can anyone see where I am going wrong?!
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As ComponentModel.DoWorkEventArgs, Optional ByVal Overwrite As Boolean = True) Handles BackgroundWorker1.DoWork
Dim deststring As String
' Open config.txt with the Using statement.
Using r As StreamReader = New StreamReader(Application.StartupPath + "\CONFIG.txt")
Dim line As String
' Read first line.
line = r.ReadLine
' Loop over each line in file, While list is Not Nothing.
Do While (Not line Is Nothing)
' Read line and filter based on logic
If line.StartsWith("*") Then
r.ReadLine()
ElseIf line.Contains(Destpath) Then
r.ReadLine()
ElseIf line.Equals("%USERPROFILE%\Desktop") Then
line = desktoppath
ElseIf line.Equals("%USERPROFILE%\Downloads") Then
line = downloadsPath
ElseIf line.Equals("%USERPROFILE%\Contacts") Then
line = contactspath
ElseIf line.Equals("%USERPROFILE%\Documents") Then
line = documentspath
ElseIf line.Equals("%USERPROFILE%\Favorites") Then
line = favoritespath
ElseIf line.Equals("%USERPROFILE%\Links") Then
line = linkspath
ElseIf line.Equals("%USERPROFILE%\Music") Then
line = Musicpath
ElseIf line.Equals("%USERPROFILE%\Pictures") Then
line = picturespath
ElseIf line.Equals("%USERPROFILE%\SavedGames") Then
line = savedgamespath
ElseIf line.Equals("%USERPROFILE%\SavedSearches") Then
line = savedsearchespath
ElseIf line.Equals("%USERPROFILE%\Videos") Then
line = videospath
ElseIf line.Contains("%USERNAME%") Then
line = line.Replace("%USERNAME%", Username)
Else
Console.Writeline(line)
'Read line and create a full path for the destination
Dim SubPath As String = line.Split("\").Last
Dim FullDestPath As String = Destpath & "\" & SubPath
Console.Writeline(FullDestPath)
If Not System.IO.Directory.Exists(FullDestPath) Then
System.IO.Directory.CreateDirectory(FullDestPath)
End If
'Get directory info's
Dim SourceDir As DirectoryInfo = New DirectoryInfo(line)
Dim DestDir As DirectoryInfo = New DirectoryInfo(FullDestPath)
Dim ChildFile As FileInfo
'Loop through each file in the SourceDir
For Each ChildFile In SourceDir.GetFiles()
'Display file being copied
SetLabelText_ThreadSafe(Me.lblStatus, "Copying: " & line & "\" & ChildFile.Name & "")
'Do the copy
ChildFile.CopyTo(Path.Combine(DestDir.FullName, ChildFile.Name), True)
deststring = DestDir.ToString & "\" & ChildFile.Name
Dim sourcedirstring As String
sourcedirstring = SourceDir.ToString & "\" & ChildFile.Name
'Open Stream
Dim CopyStream As New FileStream(sourcedirstring, FileMode.Open, FileAccess.Read)
Dim NewStream As New FileStream(deststring, FileMode.CreateNew)
Dim Buffer(100000) As Byte
Dim BytesRead As Integer
'Try loop for each file
Try
Do
BytesRead = CopyStream.Read(Buffer, 0, Buffer.Length)
NewStream.Write(Buffer, 0, BytesRead)
PercentComplete = (NewStream.Length / CopyStream.Length * 100)
PercentComplete = Decimal.Round((PercentComplete), 2)
If PercentComplete > 100 Then
PercentComplete = "0"
End If
'if the file count is only 1 file then make both progress bars the same so that the current file and total are the same
If filecount = 1 Then
percentage = ((NewStream.Length + filetotalsofarcopied) / Overallsize.ToString * 100)
percentage = Decimal.Round((percentage), 2)
If percentage > 100 Then
percentage = 0
End If
SetLabelText_ThreadSafe(Me.lblTotalProgress, "" & percentage & "%")
Else
Timer6.Start()
percentage2 = ((NewStream.Length + filetotalsofarcopied) / Overallsize.ToString * 100)
percentage2 = Decimal.Round((percentage2), 2)
If percentage2 > 100 Then
percentage2 = 0
End If
SetLabelText_ThreadSafe(Me.lblTotalProgress, "" & percentage2 & "%")
End If
SetLabelText_ThreadSafe(Me.lblCurrentFileProgress, "" & PercentComplete & "%")
Dim time As Long = Label22.Text
'Calculate copy speed
Dim kbps As Double = (NewStream.Length + filetotalsofarcopied) / (time * 1024)
If kbps < 1024 Then
SetLabelText_ThreadSafe(Me.lblCopy, String.Format("Copy Speed: {0:0.00} KB/s", kbps))
Else
SetLabelText_ThreadSafe(Me.lblCopy, String.Format("Copy Speed: {0:0.00} MB/s", kbps / 1024))
End If
Loop Until BytesRead = 0 And PercentComplete = 100
Catch ex As Exception
Finally
CopyStream.Dispose()
NewStream.Dispose()
End Try
'File counter
int3 = int3 + 1
'Calculate data being moved for eta to completion
Dim filetotalbytes As Double = ChildFile.Length
filetotalsofarcopied = filetotalbytes + filetotalsofarcopied
'Check for pending cancel
If BackgroundWorker1.CancellationPending = True Then
BackgroundWorker1.CancelAsync()
Exit Sub
End If
Next
'Loop through Sub directories of SourceDir
Dim SubDir As DirectoryInfo
For Each SubDir In SourceDir.GetDirectories()
CopyDirectory(SubDir.FullName, Path.Combine(DestDir.FullName, SubDir.Name), Overwrite)
Next
End If
' Read in the next line.
line = r.ReadLine
Loop
End Using
End Sub
UPDATE: Included .text file contents:
***DESTINATION***
D:\Test
***Sources***
%USERPROFILE%\Downloads
%USERPROFILE%\Favorites
D:\User Data\Adam\Documents\Test
You should remove the calls to ReadLine inside the first two Ifs and replace them with the Continue Do keyword.
In general it is better to have just one call to ReadLine in your code.
For example you could check for End of Stream using the StreamReader.Peek method.
Finally the If block should be closed after the %USERNAME% check
' removed
' line = r.ReadLine()
Dim line As String
Do While r.Peek <> -1
line = r.ReadLine()
Console.Writeline(line)
If line.StartsWith("*") Then
' Not significant, skip to the next line
Continue Do
ElseIf line.Contains(Destpath) Then
' Not significant, skip to the next line
Continue Do
ElseIf line.Equals("%USERPROFILE%\Desktop") Then
line = desktoppath
ElseIf line.Equals("%USERPROFILE%\Downloads") Then
line = downloadsPath
ElseIf line.Equals("%USERPROFILE%\Contacts") Then
line = contactspath
ElseIf line.Equals("%USERPROFILE%\Documents") Then
line = documentspath
ElseIf line.Equals("%USERPROFILE%\Favorites") Then
line = favoritespath
ElseIf line.Equals("%USERPROFILE%\Links") Then
line = linkspath
ElseIf line.Equals("%USERPROFILE%\Music") Then
line = Musicpath
ElseIf line.Equals("%USERPROFILE%\Pictures") Then
line = picturespath
ElseIf line.Equals("%USERPROFILE%\SavedGames") Then
line = savedgamespath
ElseIf line.Equals("%USERPROFILE%\SavedSearches") Then
line = savedsearchespath
ElseIf line.Equals("%USERPROFILE%\Videos") Then
line = videospath
ElseIf line.Contains("%USERNAME%") Then
line = line.Replace("%USERNAME%", Username)
End If
' Now your line variable should be always correct and
' you can execute your copying logic
......
line = r.ReadLine
Loop

vb PrintDocument not printing within specified margins

I am using the following code to print but every time I print to a laser printer, the right and bottom margins get cut off regardless of what I set my margins at. Could anyone shed some light on this situation? Note, I have tried using PrintDoc.OriginAtMargins = True/False but it doesn't appear to be working either.
/code/
Public MarginSize As Integer = 15
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'temp = Nothing
'With dgView
' For Each row In dgView.Rows
' temp += row.Cells(0).Value & " " & row.Cells(1).Value & " " & row.Cells(2).Value & " " & row.Cells(3).Value & vbNewLine
' Next
'End With
PrintDialog.PrinterSettings = PrintDoc.PrinterSettings
If PrintDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDoc.PrinterSettings = PrintDialog.PrinterSettings
Dim PageSetup As New PageSettings
With PageSetup
.Margins.Left = MarginSize
.Margins.Right = MarginSize
.Margins.Top = MarginSize
.Margins.Bottom = MarginSize
.Landscape = False
End With
PrintDoc.DefaultPageSettings = PageSetup
End If
' PrintDoc.OriginAtMargins = False
PrintPreviewDialog.Document = PrintDoc
PrintPreviewDialog.WindowState = FormWindowState.Maximized
PrintPreviewDialog.PrintPreviewControl.Zoom = 1
PrintPreviewDialog.ShowDialog()
End Sub
Private Sub PrintDoc_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDoc.PrintPage
Static intStart As Integer
Dim fntText As Font = txtDrawnBy.Font
Dim txtHeight As Integer
Dim LeftMargin As Integer = PrintDoc.DefaultPageSettings.Margins.Left
Dim RightMargin As Integer = PrintDoc.DefaultPageSettings.PaperSize.Width - MarginSize
Dim TopMargin As Integer = PrintDoc.DefaultPageSettings.Margins.Top
Dim BottomMargin As Integer = PrintDoc.DefaultPageSettings.PaperSize.Height - MarginSize
txtHeight = PrintDoc.DefaultPageSettings.PaperSize.Height - PrintDoc.DefaultPageSettings.Margins.Top - PrintDoc.DefaultPageSettings.Margins.Bottom
Dim LinesPerPage As Integer = CInt(Math.Round(txtHeight / (fntText.Height + 0.025)))
'Draw Rectangle for Margin
e.Graphics.DrawRectangle(Pens.Red, e.MarginBounds)
Dim y1 As Integer = e.PageBounds.Height.ToString / 3
Dim y2 As Integer = e.PageBounds.Height.ToString / 3 * 2
'Draw line 1/4 way down
e.Graphics.DrawLine(Pens.Orange, LeftMargin, y1, RightMargin, y1)
'Draw line 3/4 way down
e.Graphics.DrawLine(Pens.Orange, LeftMargin, y2, RightMargin, y2)
Dim intLineNumber As Integer
Dim sf As New StringFormat
Dim LineStep As Integer = 0
For intCounter = intStart To 66
'Print line numbers
e.Graphics.DrawString(intLineNumber.ToString & ": ", fntText, Brushes.Black, LeftMargin, fntText.Height * intLineNumber + TopMargin)
intLineNumber += 1
If intLineNumber > LinesPerPage Then
intStart = intCounter
e.HasMorePages = True
Exit For
End If
Next
End Sub
I have also attached an image of my results.
Image of print results