#Region "Variables"
Private movingObjects As New List(Of MovingObject)()
Private movingObjectsTimer As Timer
code
Private CollectedCoins As Integer = 0
Private playerX As Integer
Private playerY As Integer
Private hasKey As Boolean = False
Private justWarped As Boolean = False
Public Property RoomFilePath As String
Private SelectedMusic As String
Private Const INDENT As Integer = 20
Private Const WALL_THICKNESS As Integer = 10
Private SQCOUNTX As Integer
Private SQCOUNTY As Integer
Private SQSizeX As Integer
Private SQSizeY As Integer
Private wallsHatchStyle As HatchStyle
Private wallsColor1 As Color
Private wallsColor2 As Color
Private floorsHatchStyle As HatchStyle
Private floorsColor1 As Color
Private floorsColor2 As Color
Private verticalWalls()() As Boolean
Private horizontalWalls()() As Boolean
Private placedItems()() As String
Private verticalWallItems()() As String
Private horizontalWallItems()() As String
Private floorsUseEdgeStyle()() As Boolean
Private imageDictionary As New Dictionary(Of String, Image)
Private animatedImages As New List(Of Image)
Private animationTimer As Timer
Private isRoomDataLoaded As Boolean = False
Private ReadOnly projectDir As String = GetProjectDirectory()
Private ReadOnly ImagesFolder As String = Path.Combine(projectDir, "Data", "Images")
Private ReadOnly musicFolder As String = Path.Combine(projectDir, "Data", "Music")
Private ReadOnly SFXFolder As String = Path.Combine(projectDir, "Data", "Sound Effects")
Private musicManager As New MusicManager()
Private sfxManager As New SFXManager(SFXFolder)
Private Class MovingObject
Public Property X As Integer
Public Property Y As Integer
Public Property DeltaX As Integer
Public Property DeltaY As Integer
Public Property IsBall As Boolean
Public Property IsBlock As Boolean
Public Property MoveInterval As Integer
Public Property NextMoveTime As DateTime
End Class
Assistant
User
Can you list all frmGame with the new system?
Assistant
User
OK. My bad.
We actually have 2 kep images
Key.gif (this is the collectable key)
key.png (This will be the jigsaw)
Assistant
User
System.ArgumentNullException
HResult=0x80004003
Message=Value cannot be null. Arg_ParamName_Name
Source=System.Linq
StackTrace:
at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
at System.Linq.Enumerable.Sum[TSource,TResult,TAccumulator](IEnumerable1 source, Func2 selector)
at Enigma.frmGame.InitializeKeyImage() in D:\01 - Grags\Visual Studio\Enigma\Enigma\frmGame.vb:line 137
at Enigma.frmGame.frmGame_Load(Object sender, EventArgs e) in D:\01 - Grags\Visual Studio\Enigma\Enigma\frmGame.vb:line 84
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Control.CreateControl(Boolean ignoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(HWND hWnd, MessageId msg, WPARAM wparam, LPARAM lparam)
Assistant
#End Region
#Region "Initialization"
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages()
InitializeSoundEffects()
LoadRoomData()
StartAnimationTimer()
FindPlayerStartPosition()
AddObjectsOnFlippersToMovingObjects()
PlaySelectedMusic()
picTest.Invalidate()
Me.KeyPreview = True
Me.Focus()
End Sub
code
Private Sub InitializeImages()
Try
imageDictionary("picBlock1") = Image.FromFile(Path.Combine(ImagesFolder, "Block.png"))
imageDictionary("picBall") = Image.FromFile(Path.Combine(ImagesFolder, "Ball.gif"))
imageDictionary("picCoin") = Image.FromFile(Path.Combine(ImagesFolder, "Coin.gif"))
imageDictionary("picFinish") = Image.FromFile(Path.Combine(ImagesFolder, "Finish.gif"))
imageDictionary("picFlipper1") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper1.gif"))
imageDictionary("picFlipper2") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper2.gif"))
imageDictionary("picFlipper3") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper3.gif"))
imageDictionary("picFlipper4") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper4.gif"))
imageDictionary("picGate") = Image.FromFile(Path.Combine(ImagesFolder, "Gate.gif"))
imageDictionary("picKey") = Image.FromFile(Path.Combine(ImagesFolder, "Key.gif"))
imageDictionary("picLazer1") = Image.FromFile(Path.Combine(ImagesFolder, "Lazer1.gif"))
imageDictionary("picLazer2") = Image.FromFile(Path.Combine(ImagesFolder, "Lazer2.gif"))
imageDictionary("picWarp") = Image.FromFile(Path.Combine(ImagesFolder, "Warp.gif"))
imageDictionary("picWarp2") = Image.FromFile(Path.Combine(ImagesFolder, "Warp2.gif"))
imageDictionary("picStart") = Image.FromFile(Path.Combine(ImagesFolder, "Guy.gif"))
imageDictionary("picBlockStopper1") = Image.FromFile(Path.Combine(ImagesFolder, "Debris1.png"))
Dim animatedImageKeys As String() = {
"picLazer1", "picLazer2", "picFlipper1", "picFlipper2",
"picFlipper3", "picFlipper4", "picCoin", "picGate",
"picKey", "picFinish", "picBall", "picWarp", "picWarp2", "picStart"
}
For Each imgKey In animatedImageKeys
If imageDictionary.ContainsKey(imgKey) Then
Dim img As Image = imageDictionary(imgKey)
animatedImages.Add(img)
ImageAnimator.Animate(img, AddressOf OnFrameChanged)
End If
Next
Catch ex As Exception
MessageBox.Show("Error loading images: " & ex.Message)
End Try
End Sub
Private Sub InitializeSoundEffects()
sfxManager = New SFXManager(SFXFolder)
End Sub
Private Sub LoadRoomData()
If Not String.IsNullOrEmpty(RoomFilePath) AndAlso File.Exists(RoomFilePath) Then
LoadRoomFromFile(RoomFilePath)
Else
MessageBox.Show("Room file not found.")
Me.Close()
End If
End Sub
Private Sub StartAnimationTimer()
animationTimer = New Timer() With {.Interval = 100}
AddHandler animationTimer.Tick, AddressOf OnAnimationTick
animationTimer.Start()
End Sub
Private Sub FindPlayerStartPosition()
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
Dim imageKey As String = placedItems(x)(y)
If imageKey = "picStart" Then
playerX = x
playerY = y
placedItems(x)(y) = Nothing
Exit Sub
End If
Next
End If
Next
End Sub
Private Sub AddObjectsOnFlippersToMovingObjects()
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
Dim item As String = placedItems(x)(y)
If item = "picBlock1" OrElse item = "picBall" Then
Dim movingObject As New MovingObject With {
.X = x,
.Y = y,
.IsBlock = (item = "picBlock1"),
.IsBall = (item = "picBall"),
.DeltaX = 0,
.DeltaY = 0
}
CheckForFlipper(movingObject)
If movingObject.DeltaX <> 0 OrElse movingObject.DeltaY <> 0 Then
placedItems(x)(y) = Nothing
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
movingObjects.Add(movingObject)
End If
End If
Next
Next
If movingObjects.Count > 0 AndAlso movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
End Sub
Private Sub PlaySelectedMusic()
If Not String.IsNullOrEmpty(SelectedMusic) Then
Dim musicDetails As String() = SelectedMusic.Split(", ")
Dim musicFileName As String = musicDetails(0)
Dim volumeLevel As Single = Integer.Parse(musicDetails(1).Split(":")(1)) / 100.0F
Dim gainLevel As Single = Integer.Parse(musicDetails(2).Split(":")(1)) / 10.0F
Dim musicFilePath As String = Path.Combine(musicFolder, musicFileName)
musicManager.PlaySelectedMusic(musicFilePath, volumeLevel, gainLevel)
End If
End Sub
#End Region
#Region "Movement"
Private Sub frmGame_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Dim moved As Boolean = False
Select Case e.KeyCode
Case Keys.Up, Keys.P
moved = AttemptMove("Up")
Case Keys.Down, Keys.L
moved = AttemptMove("Down")
Case Keys.Left, Keys.Z
moved = AttemptMove("Left")
Case Keys.Right, Keys.X
moved = AttemptMove("Right")
End Select
If moved Then
picTest.Invalidate()
End If
End Sub
code
Private Function AttemptMove(direction As String) As Boolean
Dim deltaX As Integer = 0
Dim deltaY As Integer = 0
Select Case direction
Case "Up"
deltaY = -1
Case "Down"
deltaY = 1
Case "Left"
deltaX = -1
Case "Right"
deltaX = 1
End Select
Dim newX As Integer = playerX + deltaX
Dim newY As Integer = playerY + deltaY
If newX < 0 OrElse newX >= SQCOUNTX OrElse newY < 0 OrElse newY >= SQCOUNTY Then
Return False
End If
If Not CanMoveTo(newX, newY, deltaX, deltaY) Then
Return False
End If
Dim targetItem As String = placedItems(newX)(newY)
If String.IsNullOrEmpty(targetItem) Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picBlock1" Then
Dim blockMoved As Boolean = AttemptPushBlock(newX, newY, deltaX, deltaY)
If blockMoved Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picBlockStopper1" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picBall" Then
Dim ballMoved As Boolean = AttemptPushBall(newX, newY, deltaX, deltaY)
If ballMoved Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picCoin" Then
CollectedCoins += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Coin")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picKey" Then
hasKey = True
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picGate" Then
If hasKey Then
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Door Open")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picFinish" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
GameWon()
Return True
ElseIf targetItem = "picWarp" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
HandleWarp("picWarp")
Return True
ElseIf targetItem = "picWarp2" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
HandleWarp("picWarp2")
Return True
Else
Return False
End If
End Function
Private Sub CheckForWarp()
Dim currentItem As String = placedItems(playerX)(playerY)
If currentItem = "picWarp" AndAlso Not justWarped Then
HandleWarp("picWarp")
ElseIf currentItem = "picWarp2" AndAlso Not justWarped Then
HandleWarp("picWarp2")
ElseIf currentItem <> "picWarp" AndAlso currentItem <> "picWarp2" Then
justWarped = False
End If
End Sub
Private Sub HandleWarp(warpType As String)
If Not justWarped Then
Dim warpPositions As New List(Of Point)
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
If placedItems(x)(y) = warpType Then
warpPositions.Add(New Point(x, y))
End If
Next
End If
Next
warpPositions.Remove(New Point(playerX, playerY))
If warpPositions.Count = 1 Then
justWarped = True
sfxManager.PlaySoundEffect("Warp")
playerX = warpPositions(0).X
playerY = warpPositions(0).Y
CheckForWarp()
End If
End If
End Sub
Private Function AttemptPushBall(ballX As Integer, ballY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim nextX As Integer = ballX + deltaX
Dim nextY As Integer = ballY + deltaY
If nextX < 0 OrElse nextX >= SQCOUNTX OrElse nextY < 0 OrElse nextY >= SQCOUNTY Then
Return False
End If
If Not CanBallMoveTo(ballX, ballY, deltaX, deltaY) Then
Return False
End If
Dim targetItem As String = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = (nextX = playerX AndAlso nextY = playerY)
If String.IsNullOrEmpty(targetItem) AndAlso Not playerAtNextPos Then
placedItems(ballX)(ballY) = Nothing
Dim newBall As New MovingObject With {
.X = ballX,
.Y = ballY,
.DeltaX = deltaX,
.DeltaY = deltaY,
.IsBall = True,
.IsBlock = False,
.MoveInterval = 100,
.NextMoveTime = DateTime.Now.AddMilliseconds(100)
}
movingObjects.Add(newBall)
If movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
sfxManager.PlaySoundEffect("Push Ball")
Return True
Else
Return False
End If
End Function
Private Sub OnMovingObjectsTimerTick(sender As Object, e As EventArgs)
Dim currentTime As DateTime = DateTime.Now
For i As Integer = movingObjects.Count - 1 To 0 Step -1
Dim movingObject = movingObjects(i)
If movingObject.NextMoveTime > currentTime Then
Continue For
End If
Dim deltaX As Integer = movingObject.DeltaX
Dim deltaY As Integer = movingObject.DeltaY
Dim currentX As Integer = movingObject.X
Dim currentY As Integer = movingObject.Y
Dim objectStopped As Boolean = False
Dim nextX As Integer = currentX + deltaX
Dim nextY As Integer = currentY + deltaY
If nextX < 0 OrElse nextX >= SQCOUNTX OrElse nextY < 0 OrElse nextY >= SQCOUNTY Then
objectStopped = True
Else
If Not CanObjectMoveTo(movingObject, currentX, currentY, deltaX, deltaY) Then
objectStopped = True
Else
Dim targetItem As String = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = (nextX = playerX AndAlso nextY = playerY)
Dim objectAtNextPos As Boolean = movingObjects.Any(Function(o) o.X = nextX AndAlso o.Y = nextY AndAlso o IsNot movingObject)
If String.IsNullOrEmpty(targetItem) AndAlso Not playerAtNextPos AndAlso Not objectAtNextPos Then
movingObject.X = nextX
movingObject.Y = nextY
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
Else
objectStopped = True
End If
End If
End If
If objectStopped Then
If IsObjectOnFlipper(movingObject) Then
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
Else
If movingObject.IsBall Then
placedItems(movingObject.X)(movingObject.Y) = "picBall"
ElseIf movingObject.IsBlock Then
placedItems(movingObject.X)(movingObject.Y) = "picBlock1"
End If
sfxManager.PlaySoundEffect("Block Stop")
movingObjects.RemoveAt(i)
End If
End If
Next
picTest.Invalidate()
End Sub
Private Function IsObjectOnFlipper(movingObject As MovingObject) As Boolean
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
If x < verticalWallItems.Length - 1 AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
Return True
End If
End If
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Return True
End If
End If
If y < horizontalWallItems(x).Length - 1 AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
Return True
End If
End If
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Return True
End If
End If
Return False
End Function
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
If x < verticalWallItems.Length - 1 AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If y < horizontalWallItems(x).Length - 1 AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Private Function CanObjectMoveTo(movingObject As MovingObject, currentX As Integer, currentY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim wallExists As Boolean = False
Dim laserExists As Boolean = False
Dim laserX As Integer = -1
Dim laserY As Integer = -1
Dim laserType As String = ""
If deltaX = 1 Then
wallExists = verticalWalls(currentX + 1)(currentY)
If verticalWallItems(currentX + 1)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX + 1
laserY = currentY
laserType = verticalWallItems(laserX)(laserY)
End If
ElseIf deltaX = -1 Then
wallExists = verticalWalls(currentX)(currentY)
If verticalWallItems(currentX)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY
laserType = verticalWallItems(laserX)(laserY)
End If
ElseIf deltaY = 1 Then
wallExists = horizontalWalls(currentX)(currentY + 1)
If horizontalWallItems(currentX)(currentY + 1) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY + 1
laserType = horizontalWallItems(laserX)(laserY)
End If
ElseIf deltaY = -1 Then
wallExists = horizontalWalls(currentX)(currentY)
If horizontalWallItems(currentX)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY
laserType = horizontalWallItems(laserX)(laserY)
End If
End If
If wallExists Then
Return False
End If
If laserExists Then
Dim laserCanBeDestroyed As Boolean = False
If (deltaX <> 0 AndAlso laserType = "picLazer1") Then
laserCanBeDestroyed = True
ElseIf (deltaY <> 0 AndAlso laserType = "picLazer2") Then
laserCanBeDestroyed = True
End If
If laserCanBeDestroyed Then
If deltaX <> 0 Then
verticalWallItems(laserX)(laserY) = Nothing
ElseIf deltaY <> 0 Then
horizontalWallItems(laserX)(laserY) = Nothing
End If
sfxManager.PlaySoundEffect("Break Lazer")
Else
Return False
End If
End If
Return True
End Function
Private Function CanBallMoveTo(currentX As Integer, currentY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBall = True}, currentX, currentY, deltaX, deltaY)
End Function
Private Function IsLaserOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
Return item = "picLazer1" OrElse item = "picLazer2"
End If
Return False
End Function
Private Function IsLaserOnHorizontalWall(x As Integer, y As Integer) As Boolean
If horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
Return item = "picLazer1" OrElse item = "picLazer2"
End If
Return False
End Function
Private Function AttemptPushBlock(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim blockNewX As Integer = blockX + deltaX
Dim blockNewY As Integer = blockY + deltaY
If blockNewX < 0 OrElse blockNewX >= SQCOUNTX OrElse blockNewY < 0 OrElse blockNewY >= SQCOUNTY Then
Return False
End If
If Not CanBlockMoveTo(blockX, blockY, deltaX, deltaY) Then
Return False
End If
Dim blockTargetItem As String = placedItems(blockNewX)(blockNewY)
Dim playerAtNextPos As Boolean = (blockNewX = playerX AndAlso blockNewY = playerY)
If String.IsNullOrEmpty(blockTargetItem) AndAlso Not playerAtNextPos Then
placedItems(blockX)(blockY) = Nothing
placedItems(blockNewX)(blockNewY) = "picBlock1"
sfxManager.PlaySoundEffect("Push Block")
Dim newBlock As New MovingObject With {
.X = blockNewX,
.Y = blockNewY,
.IsBlock = True,
.IsBall = False,
.DeltaX = 0,
.DeltaY = 0
}
CheckForFlipper(newBlock)
If newBlock.DeltaX <> 0 OrElse newBlock.DeltaY <> 0 Then
placedItems(blockNewX)(blockNewY) = Nothing
newBlock.MoveInterval = 50
newBlock.NextMoveTime = DateTime.Now.AddMilliseconds(50)
movingObjects.Add(newBlock)
If movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
End If
Return True
Else
Return False
End If
End Function
Private Function CanBlockMoveTo(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBlock = True}, blockX, blockY, deltaX, deltaY)
End Function
Private Function IsFlipperOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
Return item = "picFlipper1" OrElse item = "picFlipper2"
End If
Return False
End Function
Private Function IsFlipperOnHorizontalWall(x As Integer, y As Integer) As Boolean
If horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
Return item = "picFlipper3" OrElse item = "picFlipper4"
End If
Return False
End Function
Private Function CanMoveTo(newX As Integer, newY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
If deltaX = 1 Then
If verticalWalls(playerX + 1)(playerY) Then Return False
If IsLaserOnVerticalWall(playerX + 1, playerY) Then Return False
If IsFlipperOnVerticalWall(playerX + 1, playerY) Then Return False
ElseIf deltaX = -1 Then
If verticalWalls(playerX)(playerY) Then Return False
If IsLaserOnVerticalWall(playerX, playerY) Then Return False
If IsFlipperOnVerticalWall(playerX, playerY) Then Return False
ElseIf deltaY = 1 Then
If horizontalWalls(playerX)(playerY + 1) Then Return False
If IsLaserOnHorizontalWall(playerX, playerY + 1) Then Return False
If IsFlipperOnHorizontalWall(playerX, playerY + 1) Then Return False
ElseIf deltaY = -1 Then
If horizontalWalls(playerX)(playerY) Then Return False
If IsLaserOnHorizontalWall(playerX, playerY) Then Return False
If IsFlipperOnHorizontalWall(playerX, playerY) Then Return False
End If
If movingObjects.Any(Function(b) b.X = newX AndAlso b.Y = newY) Then
Return False
End If
Return True
End Function
Private Sub GameWon()
sfxManager.PlaySoundEffect("Finish")
MessageBox.Show($"Congratulations! You have completed the level.{Environment.NewLine}Coins Collected: {CollectedCoins}")
Me.Close()
End Sub
#End Region
#Region "Drawing"
Private Sub OnAnimationTick(sender As Object, e As EventArgs)
For Each img In animatedImages
ImageAnimator.UpdateFrames(img)
Next
picTest.Invalidate()
End Sub
code
Private Sub OnFrameChanged(o As Object, e As EventArgs)
' Required but can be left empty
End Sub
Private Sub picTest_Paint(sender As Object, e As PaintEventArgs) Handles picTest.Paint
If Not isRoomDataLoaded Then
Return
End If
Using backgroundBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
e.Graphics.FillRectangle(backgroundBrush, picTest.ClientRectangle)
End Using
CalculateSquareSizes(picTest.ClientSize.Width, picTest.ClientSize.Height)
e.Graphics.SmoothingMode = SmoothingMode.None
DrawGrid(e.Graphics)
End Sub
Private Sub CalculateSquareSizes(clientWidth As Integer, clientHeight As Integer)
SQSizeX = (clientWidth - 2 * INDENT - (SQCOUNTX + 1) * WALL_THICKNESS) \ SQCOUNTX
SQSizeY = (clientHeight - 2 * INDENT - (SQCOUNTY + 1) * WALL_THICKNESS) \ SQCOUNTY
End Sub
Private Sub DrawGrid(g As Graphics)
Dim xOrigin As Integer = INDENT
Dim yOrigin As Integer = INDENT
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
Dim floorRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
SQSizeX,
SQSizeY
)
If floorsUseEdgeStyle IsNot Nothing AndAlso floorsUseEdgeStyle.Length > x AndAlso
floorsUseEdgeStyle(x) IsNot Nothing AndAlso floorsUseEdgeStyle(x).Length > y AndAlso
floorsUseEdgeStyle(x)(y) Then
Using floorBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(floorBrush, floorRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, floorRect)
End Using
End If
Next
Next
For x As Integer = 0 To SQCOUNTX
For y As Integer = 0 To SQCOUNTY
Dim intersectionRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) - WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) - WALL_THICKNESS \ 2,
WALL_THICKNESS,
WALL_THICKNESS
)
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, intersectionRect)
End Using
Next
Next
For x As Integer = 0 To SQCOUNTX
For y As Integer = 0 To SQCOUNTY - 1
Dim wallRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) - WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
WALL_THICKNESS,
SQSizeY
)
If x >= 0 AndAlso x < verticalWalls.Length AndAlso
verticalWalls(x) IsNot Nothing AndAlso
y >= 0 AndAlso y < verticalWalls(x).Length Then
If verticalWalls(x)(y) Then
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY
Dim wallRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) - WALL_THICKNESS \ 2,
SQSizeX,
WALL_THICKNESS
)
If x >= 0 AndAlso x < horizontalWalls.Length AndAlso
horizontalWalls(x) IsNot Nothing AndAlso
y >= 0 AndAlso y < horizontalWalls(x).Length Then
If horizontalWalls(x)(y) Then
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
DrawItems(g)
DrawWallItems(g)
End Sub
Private Sub DrawItems(g As Graphics)
If placedItems Is Nothing Then Return
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
Dim imageKey As String = placedItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
If imageKey = "picStart" Then
Continue For
End If
Dim img As Image = imageDictionary(imageKey)
Dim xPos As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End If
Next
End If
Next
For Each movingObject In movingObjects
Dim img As Image = Nothing
If movingObject.IsBall Then
img = imageDictionary("picBall")
ElseIf movingObject.IsBlock Then
img = imageDictionary("picBlock1")
End If
If img IsNot Nothing Then
Dim xPos As Integer = INDENT + movingObject.X * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + movingObject.Y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End If
Next
DrawPlayer(g)
End Sub
Private Sub DrawPlayer(g As Graphics)
Dim img As Image = imageDictionary("picStart")
Dim xPos As Integer = INDENT + playerX * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + playerY * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End Sub
Private Sub DrawWallItems(g As Graphics)
If verticalWallItems IsNot Nothing Then
For x As Integer = 0 To verticalWallItems.Length - 1
If verticalWallItems(x) IsNot Nothing Then
For y As Integer = 0 To verticalWallItems(x).Length - 1
Dim imageKey As String = verticalWallItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
Dim img As Image = imageDictionary(imageKey)
ImageAnimator.UpdateFrames(img)
Dim wallX As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) - (WALL_THICKNESS \ 2)
Dim wallY As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) + (WALL_THICKNESS \ 2)
Dim wallWidth As Integer = WALL_THICKNESS
Dim wallHeight As Integer = SQSizeY
Dim newWidth As Integer = img.Width
Dim newHeight As Integer = wallHeight
Dim centeredX As Integer = wallX + (wallWidth - newWidth) \ 2
Dim drawRect As New Rectangle(centeredX, wallY, newWidth, newHeight)
g.DrawImage(img, drawRect)
End If
Next
End If
Next
End If
If horizontalWallItems IsNot Nothing Then
For x As Integer = 0 To horizontalWallItems.Length - 1
If horizontalWallItems(x) IsNot Nothing Then
For y As Integer = 0 To horizontalWallItems(x).Length - 1
Dim imageKey As String = horizontalWallItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
Dim img As Image = imageDictionary(imageKey)
ImageAnimator.UpdateFrames(img)
Dim wallX As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) + (WALL_THICKNESS \ 2)
Dim wallY As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) - (WALL_THICKNESS \ 2)
Dim wallWidth As Integer = SQSizeX
Dim wallHeight As Integer = WALL_THICKNESS
Dim newWidth As Integer = wallWidth
Dim newHeight As Integer = img.Height
Dim centeredY As Integer = wallY + (wallHeight - newHeight) \ 2
Dim drawRect As New Rectangle(wallX, centeredY, newWidth, newHeight)
g.DrawImage(img, drawRect)
End If
Next
End If
Next
End If
End Sub
#End Region
#Region "Closing"
Private Sub frmGame_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
StopAndDisposeAnimationTimer()
StopAndDisposeMovingObjectsTimer()
ClearMovingObjectsList()
StopMusicPlayback()
StopSoundEffects()
End Sub
code
Private Sub StopAndDisposeAnimationTimer()
If animationTimer IsNot Nothing Then
animationTimer.Stop()
animationTimer.Dispose()
animationTimer = Nothing
End If
End Sub
Private Sub StopAndDisposeMovingObjectsTimer()
If movingObjectsTimer IsNot Nothing Then
movingObjectsTimer.Stop()
movingObjectsTimer.Dispose()
movingObjectsTimer = Nothing
End If
End Sub
Private Sub ClearMovingObjectsList()
movingObjects.Clear()
End Sub
Private Sub StopMusicPlayback()
musicManager.StopMusic()
End Sub
Private Sub StopSoundEffects()
sfxManager.StopSoundEffects()
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
#End Region
#Region "Utility Methods"
Private Function GetProjectDirectory() As String
Dim dir As DirectoryInfo = New DirectoryInfo(Application.StartupPath)
For i As Integer = 1 To 4
If dir.Parent IsNot Nothing Then
dir = dir.Parent
End If
Next
Return dir.FullName
End Function
code
Private Sub LoadRoomFromFile(filePath As String)
Try
Dim options As New JsonSerializerOptions With {
.IncludeFields = True,
.PropertyNameCaseInsensitive = True
}
Dim jsonString As String = File.ReadAllText(filePath)
Dim roomData As RoomData = JsonSerializer.Deserialize(Of RoomData)(jsonString, options)
If roomData Is Nothing Then
MessageBox.Show("Error: Failed to deserialize room data.")
Return
End If
RestoreRoomData(roomData)
Catch ex As Exception
MessageBox.Show("Error loading room: " & ex.ToString())
End Try
End Sub
Private Sub RestoreRoomData(roomData As RoomData)
Try
SQCOUNTX = roomData.GridSizeX
SQCOUNTY = roomData.GridSizeY
wallsHatchStyle = CType(roomData.wallsHatchStyleValue, HatchStyle)
wallsColor1 = Color.FromArgb(roomData.wallsColor1Argb)
wallsColor2 = Color.FromArgb(roomData.wallsColor2Argb)
floorsHatchStyle = CType(roomData.floorsHatchStyleValue, HatchStyle)
floorsColor1 = Color.FromArgb(roomData.floorsColor1Argb)
floorsColor2 = Color.FromArgb(roomData.floorsColor2Argb)
verticalWalls = roomData.verticalWalls
horizontalWalls = roomData.horizontalWalls
floorsUseEdgeStyle = roomData.floorsUseEdgeStyle
placedItems = RestorePlacedItems(roomData.placedItems)
verticalWallItems = RestorePlacedItems(roomData.verticalWallItems)
horizontalWallItems = RestorePlacedItems(roomData.horizontalWallItems)
SelectedMusic = roomData.SelectedMusic
lblName.Text = roomData.LevelName
PlaySelectedMusic()
isRoomDataLoaded = True
picTest.Invalidate()
Catch ex As Exception
MessageBox.Show("Error restoring room data: " & ex.ToString())
End Try
End Sub
Private Function RestorePlacedItems(data As PlacedItemData()()) As String()()
If data Is Nothing Then
Return Nothing
End If
Dim lengthOuter As Integer = data.Length
Dim restoredItems As String()() = New String(lengthOuter - 1)() {}
For x As Integer = 0 To lengthOuter - 1
If data(x) IsNot Nothing Then
Dim lengthInner As Integer = data(x).Length
restoredItems(x) = New String(lengthInner - 1) {}
For y As Integer = 0 To lengthInner - 1
If data(x)(y) IsNot Nothing Then
restoredItems(x)(y) = data(x)(y).ImageKey
Else
restoredItems(x)(y) = Nothing
End If
Next
Else
restoredItems(x) = Nothing
End If
Next
Return restoredItems
End Function
#End Region
End Class
What I want you to do.
Count the total number of keys in the grid. Using the image Key.png, divide it into jigsaw pieces corresponding to the number of keys in the grid. Each key will be needed to unlock the door.
A new PictureBox named picKey has been added to the top of the game (this has already been set up in the designer). When a player collects a key, picKey will update to display a part of the jigsaw puzzle. Once all keys are collected, picKey will reveal the complete image of the key.
The key will be placed in the same location as all other images.
Implementing the jigsaw puzzle key system in your game involves several steps. Here’s a high-level approach you can follow, keeping everything coherent within your existing game code.
Step 1: Load the Key Image and Prepare Jigsaw Pieces
First, you need to add logic to load the key image and divide it into pieces according to the total number of keys in the grid. For this scenario, let's assume that your key image is supposed to be divided evenly.
1. Declare Variables
vb
Private keyImage As Image
Private keyPieces As List(Of Image)
Private totalKeys As Integer = 0
Private collectedKeys As Integer = 0
Private pieceWidth As Integer
Private pieceHeight As Integer
2. Modify frmGame_Load to Load and Prepare the Key Image
Add the logic to load the key image and divide it into pieces:
vb
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages()
InitializeKeyImage()
' Existing initialization code...
End Sub
Private Sub InitializeKeyImage()
keyImage = Image.FromFile(Path.Combine(ImagesFolder, "Key.png"))
' Count total keys by scanning the placedItems grid
totalKeys = placedItems.Sum(Function(row) row.Count(Function(i) i = "picKey"))
If totalKeys > 0 Then
pieceWidth = keyImage.Width / totalKeys
pieceHeight = keyImage.Height ' Assuming we work with a single row.
keyPieces = New List(Of Image)()
For i As Integer = 0 To totalKeys - 1
Dim rect As New Rectangle(i * pieceWidth, 0, pieceWidth, pieceHeight)
Dim piece As Image = New Bitmap(pieceWidth, pieceHeight)
Using g As Graphics = Graphics.FromImage(piece)
g.DrawImage(keyImage, New Rectangle(0, 0, pieceWidth, pieceHeight), rect, GraphicsUnit.Pixel)
End Using
keyPieces.Add(piece)
Next
End If
End Sub
Step 2: Update the AttemptMove Function
You need to modify the existing AttemptMove function to handle the collection of keys and update the picKey PictureBox.
This method will handle the display of jigsaw pieces as the player collects keys.
vb
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Set the image in picKey to the corresponding key piece
picKey.Image = keyPieces(collectedKeys)
collectedKeys += 1
End If
' If all keys collected, display the full image
If collectedKeys >= totalKeys Then
picKey.Image = keyImage
MessageBox.Show("All keys collected! The door is now unlocked.")
End If
End Sub
Final Step: Ensure Everything Works Together
Make sure that the new logic integrates smoothly with the existing game:
Game Initialization: Ensure the images and sound effects are loaded at the start.
Key Collection Logic: Modify the AttemptMove logic to handle key collection perfectly.
User Feedback: Consider how you want to inform the user when they have completed the jigsaw (e.g., with a message box).
Conclusion
This solution outlines how to implement a jigsaw key system in your game. The steps include loading the key image, dividing it into pieces based on the number of keys, listening for key collection events through movement logic, and updating the picKey PictureBox accordingly. You can expand upon this basic logic as needed for your game's specific requirements. Adjust image paths, logic, and other specifics according to what you've set up in your project.
Sure! Below is the complete code for your frmGame class, incorporating the new key jigsaw puzzle system based on the specific requirements you've provided. This code includes all necessary additions and modifications based on your previous implementation.
vb
Imports System.IO
Imports System.Text.Json
Imports System.Text.Json.Serialization
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.ComponentModel
Public Class frmGame
#Region "Variables"
Private movingObjects As New List(Of MovingObject)()
Private movingObjectsTimer As Timer
Private CollectedCoins As Integer = 0
Private playerX As Integer
Private playerY As Integer
Private hasKey As Boolean = False
Private justWarped As Boolean = False
Public Property RoomFilePath As String
Private SelectedMusic As String
' New variables for the key system
Private keyImage As Image
Private keyPieces As List(Of Image)
Private totalKeys As Integer = 0
Private collectedKeys As Integer = 0
Private pieceWidth As Integer
Private pieceHeight As Integer
Private Const INDENT As Integer = 20
Private Const WALL_THICKNESS As Integer = 10
Private SQCOUNTX As Integer
Private SQCOUNTY As Integer
Private SQSizeX As Integer
Private SQSizeY As Integer
Private wallsHatchStyle As HatchStyle
Private wallsColor1 As Color
Private wallsColor2 As Color
Private floorsHatchStyle As HatchStyle
Private floorsColor1 As Color
Private floorsColor2 As Color
Private verticalWalls()() As Boolean
Private horizontalWalls()() As Boolean
Private placedItems()() As String
Private verticalWallItems()() As String
Private horizontalWallItems()() As String
Private floorsUseEdgeStyle()() As Boolean
Private imageDictionary As New Dictionary(Of String, Image)
Private animatedImages As New List(Of Image)
Private animationTimer As Timer
Private isRoomDataLoaded As Boolean = False
Private ReadOnly projectDir As String = GetProjectDirectory()
Private ReadOnly ImagesFolder As String = Path.Combine(projectDir, "Data", "Images")
Private ReadOnly musicFolder As String = Path.Combine(projectDir, "Data", "Music")
Private ReadOnly SFXFolder As String = Path.Combine(projectDir, "Data", "Sound Effects")
Private musicManager As New MusicManager()
Private sfxManager As New SFXManager(SFXFolder)
Private Class MovingObject
Public Property X As Integer
Public Property Y As Integer
Public Property DeltaX As Integer
Public Property DeltaY As Integer
Public Property IsBall As Boolean
Public Property IsBlock As Boolean
Public Property MoveInterval As Integer
Public Property NextMoveTime As DateTime
End Class
#End Region
#Region "Initialization"
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages()
InitializeKeyImage()
InitializeSoundEffects()
LoadRoomData()
StartAnimationTimer()
FindPlayerStartPosition()
AddObjectsOnFlippersToMovingObjects()
PlaySelectedMusic()
picTest.Invalidate()
Me.KeyPreview = True
Me.Focus()
End Sub
Private Sub InitializeImages()
Try
imageDictionary("picBlock1") = Image.FromFile(Path.Combine(ImagesFolder, "Block.png"))
imageDictionary("picBall") = Image.FromFile(Path.Combine(ImagesFolder, "Ball.gif"))
imageDictionary("picCoin") = Image.FromFile(Path.Combine(ImagesFolder, "Coin.gif"))
imageDictionary("picFinish") = Image.FromFile(Path.Combine(ImagesFolder, "Finish.gif"))
imageDictionary("picFlipper1") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper1.gif"))
imageDictionary("picFlipper2") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper2.gif"))
imageDictionary("picFlipper3") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper3.gif"))
imageDictionary("picFlipper4") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper4.gif"))
imageDictionary("picGate") = Image.FromFile(Path.Combine(ImagesFolder, "Gate.gif"))
imageDictionary("picKey") = Image.FromFile(Path.Combine(ImagesFolder, "Key.gif"))
imageDictionary("picLazer1") = Image.FromFile(Path.Combine(ImagesFolder, "Lazer1.gif"))
imageDictionary("picLazer2") = Image.FromFile(Path.Combine(ImagesFolder, "Lazer2.gif"))
imageDictionary("picWarp") = Image.FromFile(Path.Combine(ImagesFolder, "Warp.gif"))
imageDictionary("picWarp2") = Image.FromFile(Path.Combine(ImagesFolder, "Warp2.gif"))
imageDictionary("picStart") = Image.FromFile(Path.Combine(ImagesFolder, "Guy.gif"))
imageDictionary("picBlockStopper1") = Image.FromFile(Path.Combine(ImagesFolder, "Debris1.png"))
Dim animatedImageKeys As String() = {
"picLazer1", "picLazer2", "picFlipper1", "picFlipper2",
"picFlipper3", "picFlipper4", "picCoin", "picGate",
"picKey", "picFinish", "picBall", "picWarp", "picWarp2", "picStart"
}
For Each imgKey In animatedImageKeys
If imageDictionary.ContainsKey(imgKey) Then
Dim img As Image = imageDictionary(imgKey)
animatedImages.Add(img)
ImageAnimator.Animate(img, AddressOf OnFrameChanged)
End If
Next
Catch ex As Exception
MessageBox.Show("Error loading images: " & ex.Message)
End Try
End Sub
Private Sub InitializeKeyImage()
keyImage = Image.FromFile(Path.Combine(ImagesFolder, "Key.png"))
' Count total keys by scanning the placedItems grid
totalKeys = placedItems.Sum(Function(row) row.Count(Function(i) i = "picKey"))
If totalKeys > 0 Then
pieceWidth = keyImage.Width / totalKeys
pieceHeight = keyImage.Height ' Assuming we work with a single row.
keyPieces = New List(Of Image)()
For i As Integer = 0 To totalKeys - 1
Dim rect As New Rectangle(i * pieceWidth, 0, pieceWidth, pieceHeight)
Dim piece As Image = New Bitmap(pieceWidth, pieceHeight)
Using g As Graphics = Graphics.FromImage(piece)
g.DrawImage(keyImage, New Rectangle(0, 0, pieceWidth, pieceHeight), rect, GraphicsUnit.Pixel)
End Using
keyPieces.Add(piece)
Next
End If
End Sub
Private Sub InitializeSoundEffects()
sfxManager = New SFXManager(SFXFolder)
End Sub
Private Sub LoadRoomData()
If Not String.IsNullOrEmpty(RoomFilePath) AndAlso File.Exists(RoomFilePath) Then
LoadRoomFromFile(RoomFilePath)
Else
MessageBox.Show("Room file not found.")
Me.Close()
End If
End Sub
Private Sub StartAnimationTimer()
animationTimer = New Timer() With {.Interval = 100}
AddHandler animationTimer.Tick, AddressOf OnAnimationTick
animationTimer.Start()
End Sub
Private Sub FindPlayerStartPosition()
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
Dim imageKey As String = placedItems(x)(y)
If imageKey = "picStart" Then
playerX = x
playerY = y
placedItems(x)(y) = Nothing
Exit Sub
End If
Next
End If
Next
End Sub
Private Sub AddObjectsOnFlippersToMovingObjects()
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
Dim item As String = placedItems(x)(y)
If item = "picBlock1" OrElse item = "picBall" Then
Dim movingObject As New MovingObject With {
.X = x,
.Y = y,
.IsBlock = (item = "picBlock1"),
.IsBall = (item = "picBall"),
.DeltaX = 0,
.DeltaY = 0
}
CheckForFlipper(movingObject)
If movingObject.DeltaX <> 0 OrElse movingObject.DeltaY <> 0 Then
placedItems(x)(y) = Nothing
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
movingObjects.Add(movingObject)
End If
End If
Next
Next
If movingObjects.Count > 0 AndAlso movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
End Sub
Private Sub PlaySelectedMusic()
If Not String.IsNullOrEmpty(SelectedMusic) Then
Dim musicDetails As String() = SelectedMusic.Split(", ")
Dim musicFileName As String = musicDetails(0)
Dim volumeLevel As Single = Integer.Parse(musicDetails(1).Split(":")(1)) / 100.0F
Dim gainLevel As Single = Integer.Parse(musicDetails(2).Split(":")(1)) / 10.0F
Dim musicFilePath As String = Path.Combine(musicFolder, musicFileName)
musicManager.PlaySelectedMusic(musicFilePath, volumeLevel, gainLevel)
End If
End Sub
#End Region
#Region "Movement"
Private Sub frmGame_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Dim moved As Boolean = False
Select Case e.KeyCode
Case Keys.Up, Keys.P
moved = AttemptMove("Up")
Case Keys.Down, Keys.L
moved = AttemptMove("Down")
Case Keys.Left, Keys.Z
moved = AttemptMove("Left")
Case Keys.Right, Keys.X
moved = AttemptMove("Right")
End Select
If moved Then
picTest.Invalidate()
End If
End Sub
Private Function AttemptMove(direction As String) As Boolean
Dim deltaX As Integer = 0
Dim deltaY As Integer = 0
Select Case direction
Case "Up"
deltaY = -1
Case "Down"
deltaY = 1
Case "Left"
deltaX = -1
Case "Right"
deltaX = 1
End Select
Dim newX As Integer = playerX + deltaX
Dim newY As Integer = playerY + deltaY
If newX < 0 OrElse newX >= SQCOUNTX OrElse newY < 0 OrElse newY >= SQCOUNTY Then
Return False
End If
If Not CanMoveTo(newX, newY, deltaX, deltaY) Then
Return False
End If
Dim targetItem As String = placedItems(newX)(newY)
If String.IsNullOrEmpty(targetItem) Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picBlock1" Then
Dim blockMoved As Boolean = AttemptPushBlock(newX, newY, deltaX, deltaY)
If blockMoved Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picBlockStopper1" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picBall" Then
Dim ballMoved As Boolean = AttemptPushBall(newX, newY, deltaX, deltaY)
If ballMoved Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picCoin" Then
CollectedCoins += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Coin")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picKey" Then
hasKey = True
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key")
sfxManager.PlaySoundEffect("Move")
' Update the key puzzle image
UpdateKeyPictureBox()
Return True
ElseIf targetItem = "picGate" Then
If hasKey Then
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Door Open")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picFinish" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
GameWon()
Return True
ElseIf targetItem = "picWarp" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
HandleWarp("picWarp")
Return True
ElseIf targetItem = "picWarp2" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
HandleWarp("picWarp2")
Return True
Else
Return False
End If
End Function
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Set the image in picKey to the corresponding key piece
picKey.Image = keyPieces(collectedKeys)
collectedKeys += 1
End If
' If all keys collected, display the full image
If collectedKeys >= totalKeys Then
picKey.Image = keyImage
MessageBox.Show("All keys collected! The door is now unlocked.")
End If
End Sub
Private Sub CheckForWarp()
Dim currentItem As String = placedItems(playerX)(playerY)
If currentItem = "picWarp" AndAlso Not justWarped Then
HandleWarp("picWarp")
ElseIf currentItem = "picWarp2" AndAlso Not justWarped Then
HandleWarp("picWarp2")
ElseIf currentItem <> "picWarp" AndAlso currentItem <> "picWarp2" Then
justWarped = False
End If
End Sub
Private Sub HandleWarp(warpType As String)
If Not justWarped Then
Dim warpPositions As New List(Of Point)
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
If placedItems(x)(y) = warpType Then
warpPositions.Add(New Point(x, y))
End If
Next
End If
Next
warpPositions.Remove(New Point(playerX, playerY))
If warpPositions.Count = 1 Then
justWarped = True
sfxManager.PlaySoundEffect("Warp")
playerX = warpPositions(0).X
playerY = warpPositions(0).Y
CheckForWarp()
End If
End If
End Sub
Private Function AttemptPushBall(ballX As Integer, ballY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim nextX As Integer = ballX + deltaX
Dim nextY As Integer = ballY + deltaY
If nextX < 0 OrElse nextX >= SQCOUNTX OrElse nextY < 0 OrElse nextY >= SQCOUNTY Then
Return False
End If
If Not CanBallMoveTo(ballX, ballY, deltaX, deltaY) Then
Return False
End If
Dim targetItem As String = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = (nextX = playerX AndAlso nextY = playerY)
If String.IsNullOrEmpty(targetItem) AndAlso Not playerAtNextPos Then
placedItems(ballX)(ballY) = Nothing
Dim newBall As New MovingObject With {
.X = ballX,
.Y = ballY,
.DeltaX = deltaX,
.DeltaY = deltaY,
.IsBall = True,
.IsBlock = False,
.MoveInterval = 100,
.NextMoveTime = DateTime.Now.AddMilliseconds(100)
}
movingObjects.Add(newBall)
If movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
sfxManager.PlaySoundEffect("Push Ball")
Return True
Else
Return False
End If
End Function
Private Sub OnMovingObjectsTimerTick(sender As Object, e As EventArgs)
Dim currentTime As DateTime = DateTime.Now
For i As Integer = movingObjects.Count - 1 To 0 Step -1
Dim movingObject = movingObjects(i)
If movingObject.NextMoveTime > currentTime Then
Continue For
End If
Dim deltaX As Integer = movingObject.DeltaX
Dim deltaY As Integer = movingObject.DeltaY
Dim currentX As Integer = movingObject.X
Dim currentY As Integer = movingObject.Y
Dim objectStopped As Boolean = False
Dim nextX As Integer = currentX + deltaX
Dim nextY As Integer = currentY + deltaY
If nextX < 0 OrElse nextX >= SQCOUNTX OrElse nextY < 0 OrElse nextY >= SQCOUNTY Then
objectStopped = True
Else
If Not CanObjectMoveTo(movingObject, currentX, currentY, deltaX, deltaY) Then
objectStopped = True
Else
Dim targetItem As String = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = (nextX = playerX AndAlso nextY = playerY)
Dim objectAtNextPos As Boolean = movingObjects.Any(Function(o) o.X = nextX AndAlso o.Y = nextY AndAlso o IsNot movingObject)
If String.IsNullOrEmpty(targetItem) AndAlso Not playerAtNextPos AndAlso Not objectAtNextPos Then
movingObject.X = nextX
movingObject.Y = nextY
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
Else
objectStopped = True
End If
End If
End If
If objectStopped Then
If IsObjectOnFlipper(movingObject) Then
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
Else
If movingObject.IsBall Then
placedItems(movingObject.X)(movingObject.Y) = "picBall"
ElseIf movingObject.IsBlock Then
placedItems(movingObject.X)(movingObject.Y) = "picBlock1"
End If
sfxManager.PlaySoundEffect("Block Stop")
movingObjects.RemoveAt(i)
End If
End If
Next
picTest.Invalidate()
End Sub
Private Function IsObjectOnFlipper(movingObject As MovingObject) As Boolean
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
If x < verticalWallItems.Length - 1 AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
Return True
End If
End If
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Return True
End If
End If
If y < horizontalWallItems(x).Length - 1 AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
Return True
End If
End If
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Return True
End If
End If
Return False
End Function
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
If x < verticalWallItems.Length - 1 AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If y < horizontalWallItems(x).Length - 1 AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Private Function CanObjectMoveTo(movingObject As MovingObject, currentX As Integer, currentY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim wallExists As Boolean = False
Dim laserExists As Boolean = False
Dim laserX As Integer = -1
Dim laserY As Integer = -1
Dim laserType As String = ""
If deltaX = 1 Then
wallExists = verticalWalls(currentX + 1)(currentY)
If verticalWallItems(currentX + 1)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX + 1
laserY = currentY
laserType = verticalWallItems(laserX)(laserY)
End If
ElseIf deltaX = -1 Then
wallExists = verticalWalls(currentX)(currentY)
If verticalWallItems(currentX)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY
laserType = verticalWallItems(laserX)(laserY)
End If
ElseIf deltaY = 1 Then
wallExists = horizontalWalls(currentX)(currentY + 1)
If horizontalWallItems(currentX)(currentY + 1) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY + 1
laserType = horizontalWallItems(laserX)(laserY)
End If
ElseIf deltaY = -1 Then
wallExists = horizontalWalls(currentX)(currentY)
If horizontalWallItems(currentX)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY
laserType = horizontalWallItems(laserX)(laserY)
End If
End If
If wallExists Then
Return False
End If
If laserExists Then
Dim laserCanBeDestroyed As Boolean = False
If (deltaX <> 0 AndAlso laserType = "picLazer1") Then
laserCanBeDestroyed = True
ElseIf (deltaY <> 0 AndAlso laserType = "picLazer2") Then
laserCanBeDestroyed = True
End If
If laserCanBeDestroyed Then
If deltaX <> 0 Then
verticalWallItems(laserX)(laserY) = Nothing
ElseIf deltaY <> 0 Then
horizontalWallItems(laserX)(laserY) = Nothing
End If
sfxManager.PlaySoundEffect("Break Lazer")
Else
Return False
End If
End If
Return True
End Function
Private Function CanBallMoveTo(currentX As Integer, currentY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBall = True}, currentX, currentY, deltaX, deltaY)
End Function
Private Function IsLaserOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
Return item = "picLazer1" OrElse item = "picLazer2"
End If
Return False
End Function
Private Function IsLaserOnHorizontalWall(x As Integer, y As Integer) As Boolean
If horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
Return item = "picLazer1" OrElse item = "picLazer2"
End If
Return False
End Function
Private Function AttemptPushBlock(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim blockNewX As Integer = blockX + deltaX
Dim blockNewY As Integer = blockY + deltaY
If blockNewX < 0 OrElse blockNewX >= SQCOUNTX OrElse blockNewY < 0 OrElse blockNewY >= SQCOUNTY Then
Return False
End If
If Not CanBlockMoveTo(blockX, blockY, deltaX, deltaY) Then
Return False
End If
Dim blockTargetItem As String = placedItems(blockNewX)(blockNewY)
Dim playerAtNextPos As Boolean = (blockNewX = playerX AndAlso blockNewY = playerY)
If String.IsNullOrEmpty(blockTargetItem) AndAlso Not playerAtNextPos Then
placedItems(blockX)(blockY) = Nothing
placedItems(blockNewX)(blockNewY) = "picBlock1"
sfxManager.PlaySoundEffect("Push Block")
Dim newBlock As New MovingObject With {
.X = blockNewX,
.Y = blockNewY,
.IsBlock = True,
.IsBall = False,
.DeltaX = 0,
.DeltaY = 0
}
CheckForFlipper(newBlock)
If newBlock.DeltaX <> 0 OrElse newBlock.DeltaY <> 0 Then
placedItems(blockNewX)(blockNewY) = Nothing
newBlock.MoveInterval = 50
newBlock.NextMoveTime = DateTime.Now.AddMilliseconds(50)
movingObjects.Add(newBlock)
If movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
End If
Return True
Else
Return False
End If
End Function
Private Function CanBlockMoveTo(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBlock = True}, blockX, blockY, deltaX, deltaY)
End Function
Private Function IsFlipperOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
Return item = "picFlipper1" OrElse item = "picFlipper2"
End If
Return False
End Function
Private Function IsFlipperOnHorizontalWall(x As Integer, y As Integer) As Boolean
If horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
Return item = "picFlipper3" OrElse item = "picFlipper4"
End If
Return False
End Function
Private Function CanMoveTo(newX As Integer, newY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
If deltaX = 1 Then
If verticalWalls(playerX + 1)(playerY) Then Return False
If IsLaserOnVerticalWall(playerX + 1, playerY) Then Return False
If IsFlipperOnVerticalWall(playerX + 1, playerY) Then Return False
ElseIf deltaX = -1 Then
If verticalWalls(playerX)(playerY) Then Return False
If IsLaserOnVerticalWall(playerX, playerY) Then Return False
If IsFlipperOnVerticalWall(playerX, playerY) Then Return False
ElseIf deltaY = 1 Then
If horizontalWalls(playerX)(playerY + 1) Then Return False
If IsLaserOnHorizontalWall(playerX, playerY + 1) Then Return False
If IsFlipperOnHorizontalWall(playerX, playerY + 1) Then Return False
ElseIf deltaY = -1 Then
If horizontalWalls(playerX)(playerY) Then Return False
If IsLaserOnHorizontalWall(playerX, playerY) Then Return False
If IsFlipperOnHorizontalWall(playerX, playerY) Then Return False
End If
If movingObjects.Any(Function(b) b.X = newX AndAlso b.Y = newY) Then
Return False
End If
Return True
End Function
Private Sub GameWon()
sfxManager.PlaySoundEffect("Finish")
MessageBox.Show($"Congratulations! You have completed the level.{Environment.NewLine}Coins Collected: {CollectedCoins}")
Me.Close()
End Sub
#End Region
#Region "Drawing"
Private Sub OnAnimationTick(sender As Object, e As EventArgs)
For Each img In animatedImages
ImageAnimator.UpdateFrames(img)
Next
picTest.Invalidate()
End Sub
Private Sub OnFrameChanged(o As Object, e As EventArgs)
' Required but can be left empty
End Sub
Private Sub picTest_Paint(sender As Object, e As PaintEventArgs) Handles picTest.Paint
If Not isRoomDataLoaded Then
Return
End If
Using backgroundBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
e.Graphics.FillRectangle(backgroundBrush, picTest.ClientRectangle)
End Using
CalculateSquareSizes(picTest.ClientSize.Width, picTest.ClientSize.Height)
e.Graphics.SmoothingMode = SmoothingMode.None
DrawGrid(e.Graphics)
End Sub
Private Sub CalculateSquareSizes(clientWidth As Integer, clientHeight As Integer)
SQSizeX = (clientWidth - 2 * INDENT - (SQCOUNTX + 1) * WALL_THICKNESS) \ SQCOUNTX
SQSizeY = (clientHeight - 2 * INDENT - (SQCOUNTY + 1) * WALL_THICKNESS) \ SQCOUNTY
End Sub
Private Sub DrawGrid(g As Graphics)
Dim xOrigin As Integer = INDENT
Dim yOrigin As Integer = INDENT
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
Dim floorRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
SQSizeX,
SQSizeY
)
If floorsUseEdgeStyle IsNot Nothing AndAlso floorsUseEdgeStyle.Length > x AndAlso
floorsUseEdgeStyle(x) IsNot Nothing AndAlso floorsUseEdgeStyle(x).Length > y AndAlso
floorsUseEdgeStyle(x)(y) Then
Using floorBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(floorBrush, floorRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, floorRect)
End Using
End If
Next
Next
For x As Integer = 0 To SQCOUNTX
For y As Integer = 0 To SQCOUNTY
Dim intersectionRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) - WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) - WALL_THICKNESS \ 2,
WALL_THICKNESS,
WALL_THICKNESS
)
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, intersectionRect)
End Using
Next
Next
For x As Integer = 0 To SQCOUNTX
For y As Integer = 0 To SQCOUNTY - 1
Dim wallRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) - WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
WALL_THICKNESS,
SQSizeY
)
If x >= 0 AndAlso x < verticalWalls.Length AndAlso
verticalWalls(x) IsNot Nothing AndAlso
y >= 0 AndAlso y < verticalWalls(x).Length Then
If verticalWalls(x)(y) Then
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY
Dim wallRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) - WALL_THICKNESS \ 2,
SQSizeX,
WALL_THICKNESS
)
If x >= 0 AndAlso x < horizontalWalls.Length AndAlso
horizontalWalls(x) IsNot Nothing AndAlso
y >= 0 AndAlso y < horizontalWalls(x).Length Then
If horizontalWalls(x)(y) Then
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
DrawItems(g)
DrawWallItems(g)
End Sub
Private Sub DrawItems(g As Graphics)
If placedItems Is Nothing Then Return
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
Dim imageKey As String = placedItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
If imageKey = "picStart" Then
Continue For
End If
Dim img As Image = imageDictionary(imageKey)
Dim xPos As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End If
Next
End If
Next
For Each movingObject In movingObjects
Dim img As Image = Nothing
If movingObject.IsBall Then
img = imageDictionary("picBall")
ElseIf movingObject.IsBlock Then
img = imageDictionary("picBlock1")
End If
If img IsNot Nothing Then
Dim xPos As Integer = INDENT + movingObject.X * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + movingObject.Y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End If
Next
DrawPlayer(g)
End Sub
Private Sub DrawPlayer(g As Graphics)
Dim img As Image = imageDictionary("picStart")
Dim xPos As Integer = INDENT + playerX * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + playerY * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End Sub
Private Sub DrawWallItems(g As Graphics)
If verticalWallItems IsNot Nothing Then
For x As Integer = 0 To verticalWallItems.Length - 1
If verticalWallItems(x) IsNot Nothing Then
For y As Integer = 0 To verticalWallItems(x).Length - 1
Dim imageKey As String = verticalWallItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
Dim img As Image = imageDictionary(imageKey)
ImageAnimator.UpdateFrames(img)
Dim wallX As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) - (WALL_THICKNESS \ 2)
Dim wallY As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) + (WALL_THICKNESS \ 2)
Dim wallWidth As Integer = WALL_THICKNESS
Dim wallHeight As Integer = SQSizeY
Dim newWidth As Integer = img.Width
Dim newHeight As Integer = wallHeight
Dim centeredX As Integer = wallX + (wallWidth - newWidth) \ 2
Dim drawRect As New Rectangle(centeredX, wallY, newWidth, newHeight)
g.DrawImage(img, drawRect)
End If
Next
End If
Next
End If
If horizontalWallItems IsNot Nothing Then
For x As Integer = 0 To horizontalWallItems.Length - 1
If horizontalWallItems(x) IsNot Nothing Then
For y As Integer = 0 To horizontalWallItems(x).Length - 1
Dim imageKey As String = horizontalWallItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
Dim img As Image = imageDictionary(imageKey)
ImageAnimator.UpdateFrames(img)
Dim wallX As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) + (WALL_THICKNESS \ 2)
Dim wallY As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) - (WALL_THICKNESS \ 2)
Dim wallWidth As Integer = SQSizeX
Dim wallHeight As Integer = WALL_THICKNESS
Dim newWidth As Integer = wallWidth
Dim newHeight As Integer = img.Height
Dim centeredY As Integer = wallY + (wallHeight - newHeight) \ 2
Dim drawRect As New Rectangle(wallX, centeredY, newWidth, newHeight)
g.DrawImage(img, drawRect)
End If
Next
End If
Next
End If
End Sub
#End Region
#Region "Closing"
Private Sub frmGame_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
StopAndDisposeAnimationTimer()
StopAndDisposeMovingObjectsTimer()
ClearMovingObjectsList()
StopMusicPlayback()
StopSoundEffects()
End Sub
Private Sub StopAndDisposeAnimationTimer()
If animationTimer IsNot Nothing Then
animationTimer.Stop()
animationTimer.Dispose()
animationTimer = Nothing
End If
End Sub
Private Sub StopAndDisposeMovingObjectsTimer()
If movingObjectsTimer IsNot Nothing Then
movingObjectsTimer.Stop()
movingObjectsTimer.Dispose()
movingObjectsTimer = Nothing
End If
End Sub
Private Sub ClearMovingObjectsList()
movingObjects.Clear()
End Sub
Private Sub StopMusicPlayback()
musicManager.StopMusic()
End Sub
Private Sub StopSoundEffects()
sfxManager.StopSoundEffects()
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
#End Region
#Region "Utility Methods"
Private Function GetProjectDirectory() As String
Dim dir As DirectoryInfo = New DirectoryInfo(Application.StartupPath)
For i As Integer = 1 To 4
If dir.Parent IsNot Nothing Then
dir = dir.Parent
End If
Next
Return dir.FullName
End Function
Private Sub LoadRoomFromFile(filePath As String)
Try
Dim options As New JsonSerializerOptions With {
.IncludeFields = True,
.PropertyNameCaseInsensitive = True
}
Dim jsonString As String = File.ReadAllText(filePath)
Dim roomData As RoomData = JsonSerializer.Deserialize(Of RoomData)(jsonString, options)
If roomData Is Nothing Then
MessageBox.Show("Error: Failed to deserialize room data.")
Return
End If
RestoreRoomData(roomData)
Catch ex As Exception
MessageBox.Show("Error loading room: " & ex.ToString())
End Try
End Sub
Private Sub RestoreRoomData(roomData As RoomData)
Try
SQCOUNTX = roomData.GridSizeX
SQCOUNTY = roomData.GridSizeY
wallsHatchStyle = CType(roomData.wallsHatchStyleValue, HatchStyle)
wallsColor1 = Color.FromArgb(roomData.wallsColor1Argb)
wallsColor2 = Color.FromArgb(roomData.wallsColor2Argb)
floorsHatchStyle = CType(roomData.floorsHatchStyleValue, HatchStyle)
floorsColor1 = Color.FromArgb(roomData.floorsColor1Argb)
floorsColor2 = Color.FromArgb(roomData.floorsColor2Argb)
verticalWalls = roomData.verticalWalls
horizontalWalls = roomData.horizontalWalls
floorsUseEdgeStyle = roomData.floorsUseEdgeStyle
placedItems = RestorePlacedItems(roomData.placedItems)
verticalWallItems = RestorePlacedItems(roomData.verticalWallItems)
horizontalWallItems = RestorePlacedItems(roomData.horizontalWallItems)
SelectedMusic = roomData.SelectedMusic
lblName.Text = roomData.LevelName
PlaySelectedMusic()
isRoomDataLoaded = True
picTest.Invalidate()
Catch ex As Exception
MessageBox.Show("Error restoring room data: " & ex.ToString())
End Try
End Sub
Private Function RestorePlacedItems(data As PlacedItemData()()) As String()()
If data Is Nothing Then
Return Nothing
End If
Dim lengthOuter As Integer = data.Length
Dim restoredItems As String()() = New String(lengthOuter - 1)() {}
For x As Integer = 0 To lengthOuter - 1
If data(x) IsNot Nothing Then
Dim lengthInner As Integer = data(x).Length
restoredItems(x) = New String(lengthInner - 1) {}
For y As Integer = 0 To lengthInner - 1
If data(x)(y) IsNot Nothing Then
restoredItems(x)(y) = data(x)(y).ImageKey
Else
restoredItems(x)(y) = Nothing
End If
Next
Else
restoredItems(x) = Nothing
End If
Next
Return restoredItems
End Function
#End Region
End Class
Key Changes Overview:
Key Image Loading: The InitializeKeyImage method loads the key image and splits it into jigsaw pieces.
Key Collection Logic: The AttemptMove function was modified to check for the collection of keys and update the picKey PictureBox with jigsaw pieces.
Jigsaw Update Logic: The UpdateKeyPictureBox method manages the display and progression of the key image based on collected keys.
Total Keys Handling: Variables to track totalKeys and collectedKeys ensure the game knows how many pieces to display and changes the image when all keys are collected.
With this implementation, your game will allow players to collect keys which reveal parts of a jigsaw puzzle in picKey, culminating in the full key image once all pieces are collected. Make sure to place the key image (Key.png) in the correct folder, as specified in your code, for it to load properly.
No problem! Let's adjust the code to incorporate both key images correctly. We will use Key.gif as the collectible item in the game, while key.png will be used to create the jigsaw puzzle when the keys are collected.
Adjusted Code
Here's the complete modified version of the frmGame class. The changes are focused on handling both key images correctly.
vb
Imports System.IO
Imports System.Text.Json
Imports System.Text.Json.Serialization
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.ComponentModel
Public Class frmGame
#Region "Variables"
Private movingObjects As New List(Of MovingObject)()
Private movingObjectsTimer As Timer
Private CollectedCoins As Integer = 0
Private playerX As Integer
Private playerY As Integer
Private hasKey As Boolean = False
Private justWarped As Boolean = False
Public Property RoomFilePath As String
Private SelectedMusic As String
' Variables for the jigsaw key system
Private keyImage As Image
Private keyPieces As List(Of Image)
Private totalKeys As Integer = 0
Private collectedKeys As Integer = 0
Private pieceWidth As Integer
Private pieceHeight As Integer
Private collectibleKeyImage As Image ' Key.gif for collectible key
Private Const INDENT As Integer = 20
Private Const WALL_THICKNESS As Integer = 10
Private SQCOUNTX As Integer
Private SQCOUNTY As Integer
Private SQSizeX As Integer
Private SQSizeY As Integer
Private wallsHatchStyle As HatchStyle
Private wallsColor1 As Color
Private wallsColor2 As Color
Private floorsHatchStyle As HatchStyle
Private floorsColor1 As Color
Private floorsColor2 As Color
Private verticalWalls()() As Boolean
Private horizontalWalls()() As Boolean
Private placedItems()() As String
Private verticalWallItems()() As String
Private horizontalWallItems()() As String
Private floorsUseEdgeStyle()() As Boolean
Private imageDictionary As New Dictionary(Of String, Image)
Private animatedImages As New List(Of Image)
Private animationTimer As Timer
Private isRoomDataLoaded As Boolean = False
Private ReadOnly projectDir As String = GetProjectDirectory()
Private ReadOnly ImagesFolder As String = Path.Combine(projectDir, "Data", "Images")
Private ReadOnly musicFolder As String = Path.Combine(projectDir, "Data", "Music")
Private ReadOnly SFXFolder As String = Path.Combine(projectDir, "Data", "Sound Effects")
Private musicManager As New MusicManager()
Private sfxManager As New SFXManager(SFXFolder)
Private Class MovingObject
Public Property X As Integer
Public Property Y As Integer
Public Property DeltaX As Integer
Public Property DeltaY As Integer
Public Property IsBall As Boolean
Public Property IsBlock As Boolean
Public Property MoveInterval As Integer
Public Property NextMoveTime As DateTime
End Class
#End Region
#Region "Initialization"
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages()
InitializeKeyImage() ' To load jigsaw puzzle pieces
InitializeSoundEffects()
LoadRoomData()
StartAnimationTimer()
FindPlayerStartPosition()
AddObjectsOnFlippersToMovingObjects()
PlaySelectedMusic()
picTest.Invalidate()
Me.KeyPreview = True
Me.Focus()
End Sub
Private Sub InitializeImages()
Try
imageDictionary("picBlock1") = Image.FromFile(Path.Combine(ImagesFolder, "Block.png"))
imageDictionary("picBall") = Image.FromFile(Path.Combine(ImagesFolder, "Ball.gif"))
imageDictionary("picCoin") = Image.FromFile(Path.Combine(ImagesFolder, "Coin.gif"))
imageDictionary("picFinish") = Image.FromFile(Path.Combine(ImagesFolder, "Finish.gif"))
imageDictionary("picFlipper1") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper1.gif"))
imageDictionary("picFlipper2") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper2.gif"))
imageDictionary("picFlipper3") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper3.gif"))
imageDictionary("picFlipper4") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper4.gif"))
imageDictionary("picGate") = Image.FromFile(Path.Combine(ImagesFolder, "Gate.gif"))
collectibleKeyImage = Image.FromFile(Path.Combine(ImagesFolder, "Key.gif")) ' Key.gif for collectible key
imageDictionary("picLazer1") = Image.FromFile(Path.Combine(ImagesFolder, "Lazer1.gif"))
imageDictionary("picLazer2") = Image.FromFile(Path.Combine(ImagesFolder, "Lazer2.gif"))
imageDictionary("picWarp") = Image.FromFile(Path.Combine(ImagesFolder, "Warp.gif"))
imageDictionary("picWarp2") = Image.FromFile(Path.Combine(ImagesFolder, "Warp2.gif"))
imageDictionary("picStart") = Image.FromFile(Path.Combine(ImagesFolder, "Guy.gif"))
imageDictionary("picBlockStopper1") = Image.FromFile(Path.Combine(ImagesFolder, "Debris1.png"))
Dim animatedImageKeys As String() = {
"picLazer1", "picLazer2", "picFlipper1", "picFlipper2",
"picFlipper3", "picFlipper4", "picCoin", "picGate",
"picKey", "picFinish", "picBall", "picWarp", "picWarp2", "picStart"
}
For Each imgKey In animatedImageKeys
If imageDictionary.ContainsKey(imgKey) Then
Dim img As Image = imageDictionary(imgKey)
animatedImages.Add(img)
ImageAnimator.Animate(img, AddressOf OnFrameChanged)
End If
Next
Catch ex As Exception
MessageBox.Show("Error loading images: " & ex.Message)
End Try
End Sub
Private Sub InitializeKeyImage()
keyImage = Image.FromFile(Path.Combine(ImagesFolder, "Key.png")) ' Load key.png for the jigsaw
' Count total keys by scanning the placedItems grid
totalKeys = placedItems.Sum(Function(row) row.Count(Function(i) i = "picKey"))
If totalKeys > 0 Then
pieceWidth = keyImage.Width / totalKeys
pieceHeight = keyImage.Height ' Assuming we work with a single row.
keyPieces = New List(Of Image)()
For i As Integer = 0 To totalKeys - 1
Dim rect As New Rectangle(i * pieceWidth, 0, pieceWidth, pieceHeight)
Dim piece As Image = New Bitmap(pieceWidth, pieceHeight)
Using g As Graphics = Graphics.FromImage(piece)
g.DrawImage(keyImage, New Rectangle(0, 0, pieceWidth, pieceHeight), rect, GraphicsUnit.Pixel)
End Using
keyPieces.Add(piece)
Next
End If
End Sub
Private Sub InitializeSoundEffects()
sfxManager = New SFXManager(SFXFolder)
End Sub
Private Sub LoadRoomData()
If Not String.IsNullOrEmpty(RoomFilePath) AndAlso File.Exists(RoomFilePath) Then
LoadRoomFromFile(RoomFilePath)
Else
MessageBox.Show("Room file not found.")
Me.Close()
End If
End Sub
Private Sub StartAnimationTimer()
animationTimer = New Timer() With {.Interval = 100}
AddHandler animationTimer.Tick, AddressOf OnAnimationTick
animationTimer.Start()
End Sub
Private Sub FindPlayerStartPosition()
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
Dim imageKey As String = placedItems(x)(y)
If imageKey = "picStart" Then
playerX = x
playerY = y
placedItems(x)(y) = Nothing
Exit Sub
End If
Next
End If
Next
End Sub
Private Sub AddObjectsOnFlippersToMovingObjects()
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
Dim item As String = placedItems(x)(y)
If item = "picBlock1" OrElse item = "picBall" Then
Dim movingObject As New MovingObject With {
.X = x,
.Y = y,
.IsBlock = (item = "picBlock1"),
.IsBall = (item = "picBall"),
.DeltaX = 0,
.DeltaY = 0
}
CheckForFlipper(movingObject)
If movingObject.DeltaX <> 0 OrElse movingObject.DeltaY <> 0 Then
placedItems(x)(y) = Nothing
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
movingObjects.Add(movingObject)
End If
End If
Next
Next
If movingObjects.Count > 0 AndAlso movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
End Sub
Private Sub PlaySelectedMusic()
If Not String.IsNullOrEmpty(SelectedMusic) Then
Dim musicDetails As String() = SelectedMusic.Split(", ")
Dim musicFileName As String = musicDetails(0)
Dim volumeLevel As Single = Integer.Parse(musicDetails(1).Split(":")(1)) / 100.0F
Dim gainLevel As Single = Integer.Parse(musicDetails(2).Split(":")(1)) / 10.0F
Dim musicFilePath As String = Path.Combine(musicFolder, musicFileName)
musicManager.PlaySelectedMusic(musicFilePath, volumeLevel, gainLevel)
End If
End Sub
#End Region
#Region "Movement"
Private Sub frmGame_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Dim moved As Boolean = False
Select Case e.KeyCode
Case Keys.Up, Keys.P
moved = AttemptMove("Up")
Case Keys.Down, Keys.L
moved = AttemptMove("Down")
Case Keys.Left, Keys.Z
moved = AttemptMove("Left")
Case Keys.Right, Keys.X
moved = AttemptMove("Right")
End Select
If moved Then
picTest.Invalidate()
End If
End Sub
Private Function AttemptMove(direction As String) As Boolean
Dim deltaX As Integer = 0
Dim deltaY As Integer = 0
Select Case direction
Case "Up"
deltaY = -1
Case "Down"
deltaY = 1
Case "Left"
deltaX = -1
Case "Right"
deltaX = 1
End Select
Dim newX As Integer = playerX + deltaX
Dim newY As Integer = playerY + deltaY
If newX < 0 OrElse newX >= SQCOUNTX OrElse newY < 0 OrElse newY >= SQCOUNTY Then
Return False
End If
If Not CanMoveTo(newX, newY, deltaX, deltaY) Then
Return False
End If
Dim targetItem As String = placedItems(newX)(newY)
If String.IsNullOrEmpty(targetItem) Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picBlock1" Then
Dim blockMoved As Boolean = AttemptPushBlock(newX, newY, deltaX, deltaY)
If blockMoved Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picBlockStopper1" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picBall" Then
Dim ballMoved As Boolean = AttemptPushBall(newX, newY, deltaX, deltaY)
If ballMoved Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picCoin" Then
CollectedCoins += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Coin")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
ElseIf targetItem = "picKey" Then
hasKey = True
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key collect") ' Play sound for key collection
sfxManager.PlaySoundEffect("Move")
' Update the key puzzle image
UpdateKeyPictureBox()
Return True
ElseIf targetItem = "picGate" Then
If hasKey Then
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Door Open")
sfxManager.PlaySoundEffect("Move")
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picFinish" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
GameWon()
Return True
ElseIf targetItem = "picWarp" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
HandleWarp("picWarp")
Return True
ElseIf targetItem = "picWarp2" Then
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Move")
HandleWarp("picWarp2")
Return True
Else
Return False
End If
End Function
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Set the image in picKey to the corresponding key piece
picKey.Image = keyPieces(collectedKeys)
collectedKeys += 1
End If
' If all keys collected, display the full image
If collectedKeys >= totalKeys Then
picKey.Image = keyImage
MessageBox.Show("All keys collected! The door is now unlocked.")
End If
End Sub
Private Sub CheckForWarp()
Dim currentItem As String = placedItems(playerX)(playerY)
If currentItem = "picWarp" AndAlso Not justWarped Then
HandleWarp("picWarp")
ElseIf currentItem = "picWarp2" AndAlso Not justWarped Then
HandleWarp("picWarp2")
ElseIf currentItem <> "picWarp" AndAlso currentItem <> "picWarp2" Then
justWarped = False
End If
End Sub
Private Sub HandleWarp(warpType As String)
If Not justWarped Then
Dim warpPositions As New List(Of Point)
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
If placedItems(x)(y) = warpType Then
warpPositions.Add(New Point(x, y))
End If
Next
End If
Next
warpPositions.Remove(New Point(playerX, playerY))
If warpPositions.Count = 1 Then
justWarped = True
sfxManager.PlaySoundEffect("Warp")
playerX = warpPositions(0).X
playerY = warpPositions(0).Y
CheckForWarp()
End If
End If
End Sub
Private Function AttemptPushBall(ballX As Integer, ballY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim nextX As Integer = ballX + deltaX
Dim nextY As Integer = ballY + deltaY
If nextX < 0 OrElse nextX >= SQCOUNTX OrElse nextY < 0 OrElse nextY >= SQCOUNTY Then
Return False
End If
If Not CanBallMoveTo(ballX, ballY, deltaX, deltaY) Then
Return False
End If
Dim targetItem As String = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = (nextX = playerX AndAlso nextY = playerY)
If String.IsNullOrEmpty(targetItem) AndAlso Not playerAtNextPos Then
placedItems(ballX)(ballY) = Nothing
Dim newBall As New MovingObject With {
.X = ballX,
.Y = ballY,
.DeltaX = deltaX,
.DeltaY = deltaY,
.IsBall = True,
.IsBlock = False,
.MoveInterval = 100,
.NextMoveTime = DateTime.Now.AddMilliseconds(100)
}
movingObjects.Add(newBall)
If movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
sfxManager.PlaySoundEffect("Push Ball")
Return True
Else
Return False
End If
End Function
Private Sub OnMovingObjectsTimerTick(sender As Object, e As EventArgs)
Dim currentTime As DateTime = DateTime.Now
For i As Integer = movingObjects.Count - 1 To 0 Step -1
Dim movingObject = movingObjects(i)
If movingObject.NextMoveTime > currentTime Then
Continue For
End If
Dim deltaX As Integer = movingObject.DeltaX
Dim deltaY As Integer = movingObject.DeltaY
Dim currentX As Integer = movingObject.X
Dim currentY As Integer = movingObject.Y
Dim objectStopped As Boolean = False
Dim nextX As Integer = currentX + deltaX
Dim nextY As Integer = currentY + deltaY
If nextX < 0 OrElse nextX >= SQCOUNTX OrElse nextY < 0 OrElse nextY >= SQCOUNTY Then
objectStopped = True
Else
If Not CanObjectMoveTo(movingObject, currentX, currentY, deltaX, deltaY) Then
objectStopped = True
Else
Dim targetItem As String = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = (nextX = playerX AndAlso nextY = playerY)
Dim objectAtNextPos As Boolean = movingObjects.Any(Function(o) o.X = nextX AndAlso o.Y = nextY AndAlso o IsNot movingObject)
If String.IsNullOrEmpty(targetItem) AndAlso Not playerAtNextPos AndAlso Not objectAtNextPos Then
movingObject.X = nextX
movingObject.Y = nextY
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
Else
objectStopped = True
End If
End If
End If
If objectStopped Then
If IsObjectOnFlipper(movingObject) Then
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
Else
If movingObject.IsBall Then
placedItems(movingObject.X)(movingObject.Y) = "picBall"
ElseIf movingObject.IsBlock Then
placedItems(movingObject.X)(movingObject.Y) = "picBlock1"
End If
sfxManager.PlaySoundEffect("Block Stop")
movingObjects.RemoveAt(i)
End If
End If
Next
picTest.Invalidate()
End Sub
Private Function IsObjectOnFlipper(movingObject As MovingObject) As Boolean
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
If x < verticalWallItems.Length - 1 AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
Return True
End If
End If
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Return True
End If
End If
If y < horizontalWallItems(x).Length - 1 AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
Return True
End If
End If
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Return True
End If
End If
Return False
End Function
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
If x < verticalWallItems.Length - 1 AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If y < horizontalWallItems(x).Length - 1 AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 50)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Private Function CanObjectMoveTo(movingObject As MovingObject, currentX As Integer, currentY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim wallExists As Boolean = False
Dim laserExists As Boolean = False
Dim laserX As Integer = -1
Dim laserY As Integer = -1
Dim laserType As String = ""
If deltaX = 1 Then
wallExists = verticalWalls(currentX + 1)(currentY)
If verticalWallItems(currentX + 1)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX + 1
laserY = currentY
laserType = verticalWallItems(laserX)(laserY)
End If
ElseIf deltaX = -1 Then
wallExists = verticalWalls(currentX)(currentY)
If verticalWallItems(currentX)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY
laserType = verticalWallItems(laserX)(laserY)
End If
ElseIf deltaY = 1 Then
wallExists = horizontalWalls(currentX)(currentY + 1)
If horizontalWallItems(currentX)(currentY + 1) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY + 1
laserType = horizontalWallItems(laserX)(laserY)
End If
ElseIf deltaY = -1 Then
wallExists = horizontalWalls(currentX)(currentY)
If horizontalWallItems(currentX)(currentY) IsNot Nothing Then
laserExists = True
laserX = currentX
laserY = currentY
laserType = horizontalWallItems(laserX)(laserY)
End If
End If
If wallExists Then
Return False
End If
If laserExists Then
Dim laserCanBeDestroyed As Boolean = False
If (deltaX <> 0 AndAlso laserType = "picLazer1") Then
laserCanBeDestroyed = True
ElseIf (deltaY <> 0 AndAlso laserType = "picLazer2") Then
laserCanBeDestroyed = True
End If
If laserCanBeDestroyed Then
If deltaX <> 0 Then
verticalWallItems(laserX)(laserY) = Nothing
ElseIf deltaY <> 0 Then
horizontalWallItems(laserX)(laserY) = Nothing
End If
sfxManager.PlaySoundEffect("Break Lazer")
Else
Return False
End If
End If
Return True
End Function
Private Function CanBallMoveTo(currentX As Integer, currentY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBall = True}, currentX, currentY, deltaX, deltaY)
End Function
Private Function IsLaserOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
Return item = "picLazer1" OrElse item = "picLazer2"
End If
Return False
End Function
Private Function IsLaserOnHorizontalWall(x As Integer, y As Integer) As Boolean
If horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
Return item = "picLazer1" OrElse item = "picLazer2"
End If
Return False
End Function
Private Function AttemptPushBlock(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim blockNewX As Integer = blockX + deltaX
Dim blockNewY As Integer = blockY + deltaY
If blockNewX < 0 OrElse blockNewX >= SQCOUNTX OrElse blockNewY < 0 OrElse blockNewY >= SQCOUNTY Then
Return False
End If
If Not CanBlockMoveTo(blockX, blockY, deltaX, deltaY) Then
Return False
End If
Dim blockTargetItem As String = placedItems(blockNewX)(blockNewY)
Dim playerAtNextPos As Boolean = (blockNewX = playerX AndAlso blockNewY = playerY)
If String.IsNullOrEmpty(blockTargetItem) AndAlso Not playerAtNextPos Then
placedItems(blockX)(blockY) = Nothing
placedItems(blockNewX)(blockNewY) = "picBlock1"
sfxManager.PlaySoundEffect("Push Block")
Dim newBlock As New MovingObject With {
.X = blockNewX,
.Y = blockNewY,
.IsBlock = True,
.IsBall = False,
.DeltaX = 0,
.DeltaY = 0
}
CheckForFlipper(newBlock)
If newBlock.DeltaX <> 0 OrElse newBlock.DeltaY <> 0 Then
placedItems(blockNewX)(blockNewY) = Nothing
newBlock.MoveInterval = 50
newBlock.NextMoveTime = DateTime.Now.AddMilliseconds(50)
movingObjects.Add(newBlock)
If movingObjectsTimer Is Nothing Then
movingObjectsTimer = New Timer()
AddHandler movingObjectsTimer.Tick, AddressOf OnMovingObjectsTimerTick
movingObjectsTimer.Interval = 50
movingObjectsTimer.Start()
End If
End If
Return True
Else
Return False
End If
End Function
Private Function CanBlockMoveTo(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBlock = True}, blockX, blockY, deltaX, deltaY)
End Function
Private Function IsFlipperOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
Return item = "picFlipper1" OrElse item = "picFlipper2"
End If
Return False
End Function
Private Function IsFlipperOnHorizontalWall(x As Integer, y As Integer) As Boolean
If horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
Return item = "picFlipper3" OrElse item = "picFlipper4"
End If
Return False
End Function
Private Function CanMoveTo(newX As Integer, newY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
If deltaX = 1 Then
If verticalWalls(playerX + 1)(playerY) Then Return False
If IsLaserOnVerticalWall(playerX + 1, playerY) Then Return False
If IsFlipperOnVerticalWall(playerX + 1, playerY) Then Return False
ElseIf deltaX = -1 Then
If verticalWalls(playerX)(playerY) Then Return False
If IsLaserOnVerticalWall(playerX, playerY) Then Return False
If IsFlipperOnVerticalWall(playerX, playerY) Then Return False
ElseIf deltaY = 1 Then
If horizontalWalls(playerX)(playerY + 1) Then Return False
If IsLaserOnHorizontalWall(playerX, playerY + 1) Then Return False
If IsFlipperOnHorizontalWall(playerX, playerY + 1) Then Return False
ElseIf deltaY = -1 Then
If horizontalWalls(playerX)(playerY) Then Return False
If IsLaserOnHorizontalWall(playerX, playerY) Then Return False
If IsFlipperOnHorizontalWall(playerX, playerY) Then Return False
End If
If movingObjects.Any(Function(b) b.X = newX AndAlso b.Y = newY) Then
Return False
End If
Return True
End Function
Private Sub GameWon()
sfxManager.PlaySoundEffect("Finish")
MessageBox.Show($"Congratulations! You have completed the level.{Environment.NewLine}Coins Collected: {CollectedCoins}")
Me.Close()
End Sub
#End Region
#Region "Drawing"
Private Sub OnAnimationTick(sender As Object, e As EventArgs)
For Each img In animatedImages
ImageAnimator.UpdateFrames(img)
Next
picTest.Invalidate()
End Sub
Private Sub OnFrameChanged(o As Object, e As EventArgs)
' Required but can be left empty
End Sub
Private Sub picTest_Paint(sender As Object, e As PaintEventArgs) Handles picTest.Paint
If Not isRoomDataLoaded Then
Return
End If
Using backgroundBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
e.Graphics.FillRectangle(backgroundBrush, picTest.ClientRectangle)
End Using
CalculateSquareSizes(picTest.ClientSize.Width, picTest.ClientSize.Height)
e.Graphics.SmoothingMode = SmoothingMode.None
DrawGrid(e.Graphics)
End Sub
Private Sub CalculateSquareSizes(clientWidth As Integer, clientHeight As Integer)
SQSizeX = (clientWidth - 2 * INDENT - (SQCOUNTX + 1) * WALL_THICKNESS) \ SQCOUNTX
SQSizeY = (clientHeight - 2 * INDENT - (SQCOUNTY + 1) * WALL_THICKNESS) \ SQCOUNTY
End Sub
Private Sub DrawGrid(g As Graphics)
Dim xOrigin As Integer = INDENT
Dim yOrigin As Integer = INDENT
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
Dim floorRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
SQSizeX,
SQSizeY
)
If floorsUseEdgeStyle IsNot Nothing AndAlso floorsUseEdgeStyle.Length > x AndAlso
floorsUseEdgeStyle(x) IsNot Nothing AndAlso floorsUseEdgeStyle(x).Length > y AndAlso
floorsUseEdgeStyle(x)(y) Then
Using floorBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(floorBrush, floorRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, floorRect)
End Using
End If
Next
Next
For x As Integer = 0 To SQCOUNTX
For y As Integer = 0 To SQCOUNTY
Dim intersectionRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) - WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) - WALL_THICKNESS \ 2,
WALL_THICKNESS,
WALL_THICKNESS
)
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, intersectionRect)
End Using
Next
Next
For x As Integer = 0 To SQCOUNTX
For y As Integer = 0 To SQCOUNTY - 1
Dim wallRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) - WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
WALL_THICKNESS,
SQSizeY
)
If x >= 0 AndAlso x < verticalWalls.Length AndAlso
verticalWalls(x) IsNot Nothing AndAlso
y >= 0 AndAlso y < verticalWalls(x).Length Then
If verticalWalls(x)(y) Then
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY
Dim wallRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) - WALL_THICKNESS \ 2,
SQSizeX,
WALL_THICKNESS
)
If x >= 0 AndAlso x < horizontalWalls.Length AndAlso
horizontalWalls(x) IsNot Nothing AndAlso
y >= 0 AndAlso y < horizontalWalls(x).Length Then
If horizontalWalls(x)(y) Then
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
Else
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
DrawItems(g)
DrawWallItems(g)
End Sub
Private Sub DrawItems(g As Graphics)
If placedItems Is Nothing Then Return
For x As Integer = 0 To placedItems.Length - 1
If placedItems(x) IsNot Nothing Then
For y As Integer = 0 To placedItems(x).Length - 1
Dim imageKey As String = placedItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
If imageKey = "picStart" Then
Continue For
End If
Dim img As Image = imageDictionary(imageKey)
Dim xPos As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End If
Next
End If
Next
' Draw the collectible keys on the grid
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
If placedItems(x)(y) = "picKey" Then
Dim keyDestRect As New Rectangle(
INDENT + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
INDENT + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
SQSizeX,
SQSizeY
)
g.DrawImage(collectibleKeyImage, keyDestRect) ' Draw the collectible key
End If
Next
Next
For Each movingObject In movingObjects
Dim img As Image = Nothing
If movingObject.IsBall Then
img = imageDictionary("picBall")
ElseIf movingObject.IsBlock Then
img = imageDictionary("picBlock1")
End If
If img IsNot Nothing Then
Dim xPos As Integer = INDENT + movingObject.X * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + movingObject.Y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End If
Next
DrawPlayer(g)
End Sub
Private Sub DrawPlayer(g As Graphics)
Dim img As Image = imageDictionary("picStart")
Dim xPos As Integer = INDENT + playerX * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + playerY * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
End Sub
Private Sub DrawWallItems(g As Graphics)
If verticalWallItems IsNot Nothing Then
For x As Integer = 0 To verticalWallItems.Length - 1
If verticalWallItems(x) IsNot Nothing Then
For y As Integer = 0 To verticalWallItems(x).Length - 1
Dim imageKey As String = verticalWallItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
Dim img As Image = imageDictionary(imageKey)
ImageAnimator.UpdateFrames(img)
Dim wallX As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) - (WALL_THICKNESS \ 2)
Dim wallY As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) + (WALL_THICKNESS \ 2)
Dim wallWidth As Integer = WALL_THICKNESS
Dim wallHeight As Integer = SQSizeY
Dim newWidth As Integer = img.Width
Dim newHeight As Integer = wallHeight
Dim centeredX As Integer = wallX + (wallWidth - newWidth) \ 2
Dim drawRect As New Rectangle(centeredX, wallY, newWidth, newHeight)
g.DrawImage(img, drawRect)
End If
Next
End If
Next
End If
If horizontalWallItems IsNot Nothing Then
For x As Integer = 0 To horizontalWallItems.Length - 1
If horizontalWallItems(x) IsNot Nothing Then
For y As Integer = 0 To horizontalWallItems(x).Length - 1
Dim imageKey As String = horizontalWallItems(x)(y)
If Not String.IsNullOrEmpty(imageKey) AndAlso imageDictionary.ContainsKey(imageKey) Then
Dim img As Image = imageDictionary(imageKey)
ImageAnimator.UpdateFrames(img)
Dim wallX As Integer = INDENT + x * (SQSizeX + WALL_THICKNESS) + (WALL_THICKNESS \ 2)
Dim wallY As Integer = INDENT + y * (SQSizeY + WALL_THICKNESS) - (WALL_THICKNESS \ 2)
Dim wallWidth As Integer = SQSizeX
Dim wallHeight As Integer = WALL_THICKNESS
Dim newWidth As Integer = wallWidth
Dim newHeight As Integer = img.Height
Dim centeredY As Integer = wallY + (wallHeight - newHeight) \ 2
Dim drawRect As New Rectangle(wallX, centeredY, newWidth, newHeight)
g.DrawImage(img, drawRect)
End If
Next
End If
Next
End If
End Sub
#End Region
#Region "Closing"
Private Sub frmGame_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
StopAndDisposeAnimationTimer()
StopAndDisposeMovingObjectsTimer()
ClearMovingObjectsList()
StopMusicPlayback()
StopSoundEffects()
End Sub
Private Sub StopAndDisposeAnimationTimer()
If animationTimer IsNot Nothing Then
animationTimer.Stop()
animationTimer.Dispose()
animationTimer = Nothing
End If
End Sub
Private Sub StopAndDisposeMovingObjectsTimer()
If movingObjectsTimer IsNot Nothing Then
movingObjectsTimer.Stop()
movingObjectsTimer.Dispose()
movingObjectsTimer = Nothing
End If
End Sub
Private Sub ClearMovingObjectsList()
movingObjects.Clear()
End Sub
Private Sub StopMusicPlayback()
musicManager.StopMusic()
End Sub
Private Sub StopSoundEffects()
sfxManager.StopSoundEffects()
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
#End Region
#Region "Utility Methods"
Private Function GetProjectDirectory() As String
Dim dir As DirectoryInfo = New DirectoryInfo(Application.StartupPath)
For i As Integer = 1 To 4
If dir.Parent IsNot Nothing Then
dir = dir.Parent
End If
Next
Return dir.FullName
End Function
Private Sub LoadRoomFromFile(filePath As String)
Try
Dim options As New JsonSerializerOptions With {
.IncludeFields = True,
.PropertyNameCaseInsensitive = True
}
Dim jsonString As String = File.ReadAllText(filePath)
Dim roomData As RoomData = JsonSerializer.Deserialize(Of RoomData)(jsonString, options)
If roomData Is Nothing Then
MessageBox.Show("Error: Failed to deserialize room data.")
Return
End If
RestoreRoomData(roomData)
Catch ex As Exception
MessageBox.Show("Error loading room: " & ex.ToString())
End Try
End Sub
Private Sub RestoreRoomData(roomData As RoomData)
Try
SQCOUNTX = roomData.GridSizeX
SQCOUNTY = roomData.GridSizeY
wallsHatchStyle = CType(roomData.wallsHatchStyleValue, HatchStyle)
wallsColor1 = Color.FromArgb(roomData.wallsColor1Argb)
wallsColor2 = Color.FromArgb(roomData.wallsColor2Argb)
floorsHatchStyle = CType(roomData.floorsHatchStyleValue, HatchStyle)
floorsColor1 = Color.FromArgb(roomData.floorsColor1Argb)
floorsColor2 = Color.FromArgb(roomData.floorsColor2Argb)
verticalWalls = roomData.verticalWalls
horizontalWalls = roomData.horizontalWalls
floorsUseEdgeStyle = roomData.floorsUseEdgeStyle
placedItems = RestorePlacedItems(roomData.placedItems)
verticalWallItems = RestorePlacedItems(roomData.verticalWallItems)
horizontalWallItems = RestorePlacedItems(roomData.horizontalWallItems)
SelectedMusic = roomData.SelectedMusic
lblName.Text = roomData.LevelName
PlaySelectedMusic()
isRoomDataLoaded = True
picTest.Invalidate()
Catch ex As Exception
MessageBox.Show("Error restoring room data: " & ex.ToString())
End Try
End Sub
Private Function RestorePlacedItems(data As PlacedItemData()()) As String()()
If data Is Nothing Then
Return Nothing
End If
Dim lengthOuter As Integer = data.Length
Dim restoredItems As String()() = New String(lengthOuter - 1)() {}
For x As Integer = 0 To lengthOuter - 1
If data(x) IsNot Nothing Then
Dim lengthInner As Integer = data(x).Length
restoredItems(x) = New String(lengthInner - 1) {}
For y As Integer = 0 To lengthInner - 1
If data(x)(y) IsNot Nothing Then
restoredItems(x)(y) = data(x)(y).ImageKey
Else
restoredItems(x)(y) = Nothing
End If
Next
Else
restoredItems(x) = Nothing
End If
Next
Return restoredItems
End Function
#End Region
End Class
Key Changes Overview:
Two Key Images:
collectibleKeyImage: This new variable is introduced to hold the Key.gif image for the collectible key that players will be able to pick up in the game.
The InitializeImages method now loads Key.gif as the collectible key.
Jigsaw Handling:
The keyImage and keyPieces logic remains unchanged and is used to handle the puzzle.
Drawing the Collectible Key:
In the DrawItems method, logic is added to draw the collectible keys on the grid, ensuring they are displayed appropriately when placed in the game.
With these adjustments, your game will correctly handle both the collectible key (Key.gif) and the jigsaw puzzle (key.png). Players will be able to collect keys and visually see their progress in the jigsaw puzzle displayed on picKey.
The ArgumentNullException indicates that there's an attempt to operate on a null or uninitialized object within your code, specifically occurring during the calculation of the total keys with Enumerable.Sum. Based on your previous implementation, it seems that the issue arises from the placedItems array or a related variable not being properly initialized before you call InitializeKeyImage.
Steps to Resolve the Error
Ensure placedItems is Properly Initialized: Before calling InitializeKeyImage, make sure that placedItems has been correctly set up and contains valid data. If it’s null or contains only null values, it will cause this error.
Suggested Modifications
Add a null check for placedItems or initialize it appropriately in the LoadRoomData or another relevant method. You can also add error handling to log or debug the state of the placedItems.
Here’s how you could modify the relevant parts of the code:
Ensure placedItems is Initialized
Make sure placedItems is initialized in the room loading logic. You should do this in the RestoreRoomData method, right after reading the room data:
vb
Private Sub RestoreRoomData(roomData As RoomData)
Try
SQCOUNTX = roomData.GridSizeX
SQCOUNTY = roomData.GridSizeY
' Initialize placedItems in case it's not properly set
placedItems = New String(SQCOUNTX - 1)() {}
For i As Integer = 0 To SQCOUNTX - 1
placedItems(i) = New String(SQCOUNTY - 1) {}
Next
wallsHatchStyle = CType(roomData.wallsHatchStyleValue, HatchStyle)
wallsColor1 = Color.FromArgb(roomData.wallsColor1Argb)
wallsColor2 = Color.FromArgb(roomData.wallsColor2Argb)
floorsHatchStyle = CType(roomData.floorsHatchStyleValue, HatchStyle)
floorsColor1 = Color.FromArgb(roomData.floorsColor1Argb)
floorsColor2 = Color.FromArgb(roomData.floorsColor2Argb)
verticalWalls = roomData.verticalWalls
horizontalWalls = roomData.horizontalWalls
floorsUseEdgeStyle = roomData.floorsUseEdgeStyle
placedItems = RestorePlacedItems(roomData.placedItems)
verticalWallItems = RestorePlacedItems(roomData.verticalWallItems)
horizontalWallItems = RestorePlacedItems(roomData.horizontalWallItems)
SelectedMusic = roomData.SelectedMusic
lblName.Text = roomData.LevelName
PlaySelectedMusic()
isRoomDataLoaded = True
' Ensure placedItems is not null before calling key handling
If placedItems IsNot Nothing AndAlso placedItems.Any(Function(row) row IsNot Nothing) Then
InitializeKeyImage() ' Move this method call here to ensure placedItems is ready
End If
picTest.Invalidate()
Catch ex As Exception
MessageBox.Show("Error restoring room data: " & ex.ToString())
End Try
End Sub
Additional Debugging
You might want to temporarily add debug statements to understand if placedItems is being populated correctly:
vb
Debug.WriteLine("Placed Items Length: " & (placedItems?.Length).ToString())
For x As Integer = 0 To placedItems.Length - 1
Debug.WriteLine($"Row {x}: {String.Join(", ", placedItems(x)?.Select(Function(i) i))}")
Next
Conclusion
These changes ensure that your placedItems variable is initialized correctly and contains the expected data before InitializeKeyImage is called. This should help you avoid the ArgumentNullException you're encountering. If the issue persists, you might also want to take a close look at the data being deserialized from your room files to ensure they create valid structures.