I am new with this encryption stuff and also i am looking into a pervious engineers code. The encrypt works find but i would like a decryptor, i am not sure what or how to start
There is a PasswordEncryption class which looks as below
Public Class PasswordEncryption
Public Shared arrBase64EncMap(64) As String
Public Shared arrBase64DecMap(127) As Integer
Const BASE_64_MAP_INIT As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Public Shared Function EncryptionPassword() As String
Return "F2oWrB4sA3feEh1tz"
End Function
Public Shared Function simpleXor(ByVal strIn As String, ByVal strKey As String) As String
Dim iInIndex As Integer
Dim iKeyIndex As Integer
Dim strReturn As String
If Len(strIn) = 0 Or Len(strKey) = 0 Then
simpleXor = ""
Exit Function
End If
iInIndex = 1
iKeyIndex = 1
strReturn = ""
'** Step through the plain text source XORing the character at each point with the next character in the key **
'** Loop through the key characters as necessary **
Do While iInIndex <= Len(strIn)
strReturn = strReturn & Chr(Asc(Mid(strIn, iInIndex, 1)) Xor Asc(Mid(strKey, iKeyIndex, 1)))
iInIndex = iInIndex + 1
If iKeyIndex = Len(strKey) Then iKeyIndex = 0
iKeyIndex = iKeyIndex + 1
Loop
simpleXor = strReturn
End Function
Public Shared Function base64Encode(ByVal strPlain As String) As String
Dim iLoop As Integer
Dim iBy3 As Integer
Dim strReturn As String
Dim iIndex As Integer
Dim iFirst As Integer
Dim iSecond As Integer
Dim iiThird As Integer
If strPlain.Length = 0 Then
base64Encode = ""
Exit Function
End If
'** Set up Base64 Encoding and Decoding Maps for when we need them **
For iLoop = 0 To Len(BASE_64_MAP_INIT) - 1
arrBase64EncMap(iLoop) = Mid(BASE_64_MAP_INIT, iLoop + 1, 1)
Next
For iLoop = 0 To Len(BASE_64_MAP_INIT) - 1
arrBase64DecMap(Asc(arrBase64EncMap(iLoop))) = iLoop
Next
'** Work out rounded down multiple of 3 bytes length for the unencoded text **
iBy3 = (strPlain.Length \ 3) * 3
strReturn = ""
'** For each 3x8 byte chars, covert them to 4x6 byte representations in the Base64 map **
iIndex = 1
Do While iIndex <= iBy3
iFirst = Asc(Mid(strPlain, iIndex + 0, 1))
iSecond = Asc(Mid(strPlain, iIndex + 1, 1))
iiThird = Asc(Mid(strPlain, iIndex + 2, 1))
strReturn = strReturn & arrBase64EncMap((iFirst \ 4) And 63)
strReturn = strReturn & arrBase64EncMap(((iFirst * 16) And 48) + ((iSecond \ 16) And 15))
strReturn = strReturn & arrBase64EncMap(((iSecond * 4) And 60) + ((iiThird \ 64) And 3))
strReturn = strReturn & arrBase64EncMap(iiThird And 63)
iIndex = iIndex + 3
Loop
'** Handle any trailing characters not in groups of 3 **
'** Extend to multiple of 3 characters using = signs as per RFC **
If iBy3 < strPlain.Length Then
iFirst = Asc(Mid(strPlain, iIndex + 0, 1))
strReturn = strReturn & arrBase64EncMap((iFirst \ 4) And 63)
If (strPlain.Length Mod 3) = 2 Then
iSecond = Asc(Mid(strPlain, iIndex + 1, 1))
strReturn = strReturn & arrBase64EncMap(((iFirst * 16) And 48) + ((iSecond \ 16) And 15))
strReturn = strReturn & arrBase64EncMap((iSecond * 4) And 60)
Else
strReturn = strReturn & arrBase64EncMap((iFirst * 16) And 48)
strReturn = strReturn & "="
End If
strReturn = strReturn & "="
End If
'** Return the encoded result string **
base64Encode = strReturn
End Function
End Class
I have a simple form which has two buttons Encrypt and Decrypt and couple of textboxes.
The click event of the encrypt button does the following
Private Sub btnEncrypt_Click(sender As Object, e As EventArgs) Handles btnEncrypt.Click
If tbxPassword.Text IsNot Nothing Then
Dim PasswordEncryption As PasswordEncryption = New PasswordEncryption()
Dim strXOR As String = PasswordEncryption.simpleXor(Strings.Left(tbxPassword.Text.ToString().Trim, 20), PasswordEncryption.EncryptionPassword)
Dim encryptedPassword = PasswordEncryption.base64Encode(strXOR)
tbxResult.Text = encryptedPassword
Else
MessageBox.Show("No action can be performed")
End If
End Sub
I have the following code in the decrypt button but it does not bring my original string back
Private Sub btnDecrypt_Click(sender As Object, e As EventArgs) Handles btnDecrypt.Click
If tbxPassword.Text IsNot Nothing Then
Dim PasswordEncryption As PasswordEncryption = New PasswordEncryption()
Dim strXOR As String = PasswordEncryption.simpleXor(Strings.Left(tbxPassword.Text.ToString().Trim, 20), PasswordEncryption.EncryptionPassword)
Dim decryptedPassword = PasswordEncryption.base64Encode(strXOR)
tbxResult.Text = decryptedPassword
Else
MessageBox.Show("No action can be performed")
End If
What is that i need to implement to get the original string back. Thank you guys!
Ok guys i have figured it out from the following link
https://www.codingforums.com/archive/index.php/t-28425.html
I have included the decode method and as per comment from MarkL I have first Base64Decoded the string and then performed simpleXOR and i got the original string back.
My decrypt method looks like this
Private Sub btnDecrypt_Click(sender As Object, e As EventArgs) Handles btnDecrypt.Click
If tbxPassword.Text IsNot Nothing Then
Dim PasswordEncryption As PasswordEncryption = New PasswordEncryption()
' Dim strXOR As String = PasswordEncryption.simpleXor(Strings.Left(tbxPassword.Text.ToString().Trim, 20), PasswordEncryption.EncryptionPassword)
Dim base64DecodedValue = PasswordEncryption.base64Decode(tbxPassword.Text)
tbxResult.Text = PasswordEncryption.simpleXor(Strings.Left(base64DecodedValue.Trim, 20), PasswordEncryption.EncryptionPassword)
Else
MessageBox.Show("No action can be performed")
End If
End Sub
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
Public Class Form1
Dim area As Integer
Dim gauge As String
Dim cost As Decimal
Dim Length, Width, Depth, CostNo As Decimal
Dim CostNa, combo As String
Dim ErrorFlag As Boolean
Dim D1 As String
Private Sub Area2_Click(sender As Object, e As EventArgs) Handles Area2.Click
Length = txtLength.Text
Width = txtWidth.Text
Depth = txtDepth.Text
CostNo = CostumerNo.Text
CostNa = CostumerName.Text
ErrorFlag = ErrorLook(Width, Length, Depth)
If ErrorFlag = False Then
MsgBox("Invalid")
Reset()
txtDepth.Text = ""
txtLength.Text = ""
txtWidth.Text = ""
CostumerName.Text = ""
CostumerNo.Text = ""
Result.Text = ""
output.Text = ""
A2.Text = ""
G1.Text = ""
C1.Text = ""
ElseIf ErrorFlag = True Then
MsgBox("u Good")
End If
Length = L(Width)
Width = W(Length)
A2.Text = a(Width, Length)
G1.Text = g(gauge)
C1.Text = c(cost)
FileOpen(1, "Info1.txt", OpenMode.Append)
PrintLine(1, Result.Text & " " & CostumerName.Text & " " & CostumerNo.Text & " " & A2.Text & " " & G1.Text & " " & C1.Text)
FileClose(1)
FileOpen(1, "Info1.Text", OpenMode.Input)
While Not EOF(1)
Result.Text = LineInput(1)
End While
End Sub
Function combo1() As String
End Function
Const Cost1 As Decimal = 1.12
Const Cost2 As Decimal = 1.76
Public Function c(ByVal cost As Decimal) As String
If G1.Text = "Gauge1" Then
Return A2.Text * Cost1
Else
Return A2.Text * Cost2
End If
End Function
Public Function g(ByVal gauge As String) As String
If A2.Text <= 100 Then
Return "Gauge1"
Else
Return "Gauge2"
End If
End Function
'sets the boundaries for the input values
Public Function ErrorLook(ByVal w As Decimal, ByVal l As Decimal, ByVal d As Decimal) As Boolean
If l < 1 Or l > 10 Then
Return False
Else
Return True
End If
If w < 1 Or w > 10 Then
Return False
Else
Return True
End If
If d < 1 Or d > 10 Then
Return False
Else
Return True
End If
End Function
'calculates the width
Public Function L(ByVal W As Decimal) As Decimal
Width = txtWidth.Text + (2 * txtDepth.Text)
Return Width
End Function
'calculates the length
Public Function W(ByVal L As Decimal) As Decimal
Length = txtLength.Text + (2 * txtDepth.Text)
Return Length
End Function
'calculates the area
Public Function a(ByVal w As Decimal, ByVal l As Decimal) As Decimal
Dim area2 As Decimal
area2 = w * l
Return area2
End Function
'displays the date and time of the system it is eing run from
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
lbTime.Text = Now()
End Sub
'the clear button for clearing all of the fields
Private Sub CA_Click(sender As Object, e As EventArgs) Handles CA.Click
Reset()
txtDepth.Text = ""
txtLength.Text = ""
txtWidth.Text = ""
CostumerName.Text = ""
CostumerNo.Text = ""
Result.Text = ""
A2.Text = ""
G1.Text = ""
C1.Text = ""
End Sub
End Class
Look at the 'ErrorLook' function. The first thing it does is a boolean test where it will return true or false. Why have you got "If w < 1" e.t.c or "If d < 1" e.t.c, it will never get to them..... I could go on.....
You're obtaining strings into decimals without checking... You're doing calculations on strings without knowing if they are numbers...
Think what it is you are trying to do. First thing, stop using VB6 code and try and understand the logic, maybe you need to start from scratch.
I am writing an IDE an while working on syntax highlighting, i've encountered a very annoying issue.
When I type something, the text flickers...
Here is my code:
Dim KeyWords As List(Of String) = New List(Of String)(New String() {"void", "int", "long", "char", "short", "unsigned", "signed", "#include", "#define", "return"})
Dim KeyWordsColors As List(Of Color) = New List(Of Color)(New Color() {Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Olive, Color.Olive, Color.Blue})
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim words As IEnumerable(Of String) = RichTextBox1.Text.Split(New Char() {" "c, ".", ",", "?", "!", "(", Chr(13), Chr(10), " "})
Dim index As Integer = 0
Dim rtb As RichTextBox = sender 'to give normal color according to the base fore color
For Each word As String In words
'If the list contains the word, then color it specially. Else, color it normally
'Edit: Trim() is added such that it may guarantee the empty space after word does not cause error
coloringRTB(sender, index, word.Length, If(KeyWords.Contains(word.ToLower().Trim()) Or KeyWords.Contains("<"), KeyWordsColors(KeyWords.IndexOf(word.ToLower().Trim())), rtb.ForeColor))
index = index + word.Length + 1 '1 is for the whitespace, though Trimmed, original word.Length is still used to advance
Next
Dim strings() As String = RichTextBox1.Text.Split(Chr(34))
Dim count As Integer = 0
Dim cpart As Integer = 0
For Each part In strings
cpart = cpart + 1
If cpart Mod 2 = 0 Then
coloringRTB(RichTextBox1, count - 1, part.Length + 2, Color.Olive)
End If
count = count + part.Length + 1
Next
Dim strings2() As String = RichTextBox1.Text.Split(New Char() {"<", ">"})
count = 0
cpart = 0
For Each part In strings2
cpart = cpart + 1
If cpart Mod 2 = 0 Then
coloringRTB(RichTextBox1, count - 1, part.Length + 2, Color.Olive)
End If
count = count + part.Length + 1
Next
End Sub
Private Sub coloringRTB(rtb As RichTextBox, index As Integer, length As Integer, color As Color)
Dim selectionStartSave As Integer = rtb.SelectionStart 'to return this back to its original position
rtb.SelectionStart = index
rtb.SelectionLength = length
rtb.SelectionColor = color
rtb.SelectionLength = 0
rtb.SelectionStart = selectionStartSave
rtb.SelectionColor = rtb.ForeColor 'return back to the original color
End Sub
Private Sub RichTextBox1_KeyUp(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If e.KeyChar = "{"c Then
RichTextBox1.SelectedText = "{}"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("{") + 1
e.Handled = True
End If
If e.KeyChar = "("c Then
RichTextBox1.SelectedText = "()"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("(") + 1
e.Handled = True
End If
If e.KeyChar = "["c Then
RichTextBox1.SelectedText = "[]"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("[") + 1
e.Handled = True
End If
If e.KeyChar = "'"c Then
RichTextBox1.SelectedText = "''"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("'")
e.Handled = True
End If
Dim currentLength = RichTextBox1.Text.Length
End Sub
hope someone can help Thanks ^_^
RichTextBox1 is the richtextbox
First part of the code is to retrieve data from the web. It takes only a part of the second to complete the request. Second part of the code is to split data so that parts of data can be shown in different labels and it takes around 5-6 second to complete this operation?
Why is that? Can it be done faster?
First part of the code (textbox1 key down event)
If e.KeyCode = Keys.Enter Then
TextBox1.Text = UCase(TextBox1.Text)
If TextBox1.Text = "" Then
GoTo exx
Else
Dim strURL As String
Dim strSymbol As String = TextBox1.Text
strURL = " http://quote.yahoo.com/d/quotes.csv?" & _
"s=" & strSymbol & _
"&d=t" & _
"&f=snl1pmwvj1l1"
MessageBox.Show(RequestWebData(strURL))
Second part of the code and functions :
Label24.Text = (GetName2(RequestWebData(strURL), 3))
Dim myText = Label24.Text
Dim dIndex = myText.IndexOf("Inc.")
If (dIndex > -1) Then
Label24.Text = (Strings.Left(Label24.Text, dIndex + 4))
Else
Label24.Text = (Label24.Text)
End If
Dim myText2 = Label24.Text
Dim dIndex2 = myText2.IndexOf("Common")
If (dIndex2 > -1) Then
Label24.Text = (Label24.Text.Replace("Common", ""))
Else
Label24.Text = (Label24.Text)
End If
Label6.Text = (GetName(RequestWebData(strURL), 4))
Label6.Text = (GetName3(Label6.Text, 1))
Label6.Text = FormatNumber(Label6.Text, 2)
Label17.Text = (GetName(RequestWebData(strURL), 5))
Label21.Text = (GetName(RequestWebData(strURL), 7))
Dim x As String = GetName(RequestWebData(strURL), 8)
Label30.Text = GetName3(x, 1)
Label30.Text = FormatNumber(Label30.Text, 0)
Label32.Text = GetName3(x, 2)
TextBox2.Focus()
Function GetName(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split(""",")(i)
End Function
Function GetName2(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split("""")(i)
End Function
Function GetName3(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split(",")(i)
End Function
Maybe it is so slow because of these three functions that I am using to split data?