#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 totalKeys As Integer = 0
Private collectedKeys As Integer = 0
Private keyPieces As List(Of Image)
Private blackBoxHeight As Integer = 0
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()
InitializeSoundEffects()
LoadRoomData()
StartAnimationTimer()
FindPlayerStartPosition()
AddObjectsOnFlippersToMovingObjects()
PlaySelectedMusic()
picTest.Invalidate()
Me.KeyPreview = True
Me.Focus()
picKey.Image = Nothing ' Initialize picKey with no image
CenterPicKeyAboveScreen()
End Sub
code
#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
#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
#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
#End Region
End Class
Can you see why picKey (picturebox) isn't updating when a key is collected? When the player picks up a key, the picturebox should reveal some of the key
Assistant
It appears that the issue with the picKey PictureBox not updating when a key is collected might stem from several potential issues in the UpdateKeyPictureBox method and how you handle the image rendering in the picKey_Paint event.
Here are some steps to troubleshoot and potentially fix the problem:
Make sure the Image is set properly:
Ensure that the Image property of picKey is set correctly upon initialization of InitializeKeyPieces.
Invalidate the PictureBox:
Ensuring that you call picKey.Invalidate() after updating the black box height is crucial. This will trigger a repaint of the PictureBox.
Check the picKey_Paint Method:
Ensure the drawing logic inside picKey_Paint accurately renders the key image based on the current values of the collectedKeys and totalKeys.
Here’s a detailed look on how you might approach fixing the issue and the modifications you might want to make:
Update UpdateKeyPictureBox method
vb
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Update the black box height
blackBoxHeight = (picKey.Height * (totalKeys - collectedKeys)) \ totalKeys
picKey.Invalidate() ' Trigger a repaint to update the black box
Else
' Reveal the complete key image
' Ensure to set the image only once when all keys are collected
If picKey.Image IsNot Nothing) Then
picKey.Image.Dispose() ' Dispose the old image to prevent memory leaks
End If
picKey.Image = Image.FromFile(Path.Combine(ImagesFolder, "Key.png")) ' Use Key.png for complete image
picKey.Invalidate() ' Trigger a repaint to update the image
End If
End Sub
Update picKey_Paint
Make sure your picKey_Paint event handles the drawing correctly. Here’s an example approach:
User
That didn't work. What should be happening is. The picture of the key should remain there. Over the top of the image we draw a black box. When the user collects a key the blackbox should shrink, revealing some of the key. I'm wondering if I should instead use another picturebox wiha black background that goes on top of pickey.?
Assistant
If the approach of shrinking the black box on top of the key image isn't working as expected, using a separate PictureBox as an overlay for the black box is a valid and effective solution. This way, you have more control over the visual representation and can easily manage the layering without worrying about drawing issues in the Paint event.
Here’s how you can implement the new approach:
Add a Separate PictureBox for the Black Box:
Create a new PictureBox (let's call it picBlackBox) that will overlay the picKey. This PictureBox should have a black background.
Set the Size and Position:
Ensure that picBlackBox is positioned directly over picKey and set its size to match picKey.
Update the Size of the Black Box:
When a key is collected, you can simply adjust the size of picBlackBox, thus revealing more of the key image each time.
Example Implementation Steps:
Design the Form:
Ensure to add picBlackBox in the designer or programmatically, and set its properties:
vb
' Setup picBlackBox in the designer or programmatically
With picBlackBox
.Location = picKey.Location
.Size = picKey.Size
.BackColor = Color.Black ' Set the background to black
.Visible = True ' Make it initially visible
End With
Update Key Collection Logic:
In your UpdateKeyPictureBox, adjust the height of picBlackBox when a key is collected:
vb
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Update the black box height with calculation
blackBoxHeight = (picKey.Height * (totalKeys - collectedKeys)) \ totalKeys
' Set the size of the picBlackBox based on blackBoxHeight
picBlackBox.Height = blackBoxHeight
picBlackBox.Invalidate() ' Update the Box to reflect changes
Else
' Hide the black box when all keys are collected
picBlackBox.Visible = False
End If
End Sub
User
Can I delete picKey_Paint?
Assistant
Yes, if you're using a separate PictureBox (picBlackBox) to handle the black box overlay instead of drawing it in the picKey_Paint method, you can safely delete the picKey_Paint method. Here's a summary of why you can remove it and what you should do next:
Why You Can Remove picKey_Paint:
Redundant Drawing Logic: The drawing logic that was originally used to handle the black box over the key image is now being managed by picBlackBox. Since you’re no longer using custom drawing in picKey, the picKey_Paint method is redundant.
Simplification: Removing the picKey_Paint method simplifies your code. You are relying on standard PictureBox behaviors instead of custom drawing, which is easier to maintain and understand.
Steps After Removing picKey_Paint:
Delete the Method: Remove the entire picKey_Paint subroutine from your code.
Ensure No References to It: Check for any existing code that may still reference picKey_Paint. If found, either remove those references or modify them to suit your new design.
Adjust Properties (if needed): If there were any specific properties set in the picKey_Paint that you may need (like image handling), ensure that the picKey is properly configured in the form designer or through code to display the key image correctly.
Test the Application: After making the changes, run your application to ensure everything works as expected. The key image should remain visible, and the picBlackBox should correctly show and update the overlay as keys are collected.
Final Implementation Tips:
When you remove picKey_Paint, ensure that the Image property of picKey is still set correctly, typically in the form's Load event or a similar initialization routine.
If your interface allows for additional changes or enhancements, maintain clear documentation for your modifications for future reference. This will aid in maintaining the code and possibly expanding features.
Here's how you can confirm the removal:
vb
' Remove this entire method if it exists in your code
Private Sub picKey_Paint(sender As Object, e As PaintEventArgs) Handles picKey.Paint
' This method is no longer needed with picBlackBox handling the visual aspect
End Sub
With these adjustments, your application will function as intended, showing the key image with a shrinking black box overlay as keys are collected, utilizing the separate PictureBox (picBlackBox).
User
ok not working. I don't think updatepicturebox is being called. As I put debugging code in there
Assistant
If you've confirmed that the UpdateKeyPictureBox method is not being called as expected, here are some steps to diagnose and fix the issue.
Steps to Troubleshoot
Check Where UpdateKeyPictureBox is Called:
Make sure you are calling UpdateKeyPictureBox in all the appropriate places where a key is collected. Specifically, check the logic in the various cases of your AttemptMove function, particularly where you handle the key collection:
vb
ElseIf targetItem = "picKey" Then
collectedKeys += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key")
sfxManager.PlaySoundEffect("Move")
UpdateKeyPictureBox() ' Ensure this line is present and correctly placed
CheckForWarp()
Return True
Make sure that this line of code is present and not inadvertently commented out or skipped.
Confirm collectedKeys Update:
Ensure that when you collect a key, the collectedKeys variable is indeed incrementing. You can add a debug message right after incrementing collectedKeys:
Verify Total Keys:
Confirm that totalKeys has been correctly initialized before you start collecting keys. This should be checked in the CountKeysInGrid function or somewhere similar.
Add Debugging to UpdateKeyPictureBox:
Since you've indicated you've already added debugging code there, double-check the method’s implementation. For example:
vb
Private Sub UpdateKeyPictureBox()
Debug.WriteLine("UpdateKeyPictureBox called. Collected Keys: " & collectedKeys & ", Total Keys: " & totalKeys)
If collectedKeys < totalKeys Then
blackBoxHeight = (picKey.Height * (totalKeys - collectedKeys)) \ totalKeys
picBlackBox.Height = blackBoxHeight
picBlackBox.Invalidate()
Else
picBlackBox.Visible = False
End If
End Sub
User
Ok it's calling. But for soem reason. the following doesn't show the key
code
Private Sub UpdateKeyPictureBox()
picBlackBox.Visible = False
If collectedKeys < totalKeys Then
' Update the black box height with calculation
blackBoxHeight = (picKey.Height * (totalKeys - collectedKeys)) \ totalKeys
' Set the size of the picBlackBox based on blackBoxHeight
picBlackBox.Height = blackBoxHeight
picBlackBox.Invalidate() ' Update the Box to reflect changes
Else
' Hide the black box when all keys are collected
picBlackBox.Visible = False
End If
End Sub
' picBlackBox.Visible = False <(--- not showing the key. So we must be hiding picKey somewhere
Assistant
Given your description, it sounds like the visibility of picBlackBox is causing the picKey to be hidden because you set picBlackBox.Visible = False at the start of your UpdateKeyPictureBox method. If picBlackBox is always hidden before you perform the calculations and set it to visible conditionally, this could lead to unexpected behavior.
Here’s the issue:
Setting picBlackBox.Visible = False Initially:
This line makes picBlackBox invisible every time UpdateKeyPictureBox is called. As a result, even when blackBoxHeight is updated, if the condition is true, the black box remains hidden and does not display.
Suggested Solution:
You should only hide or set the visibility of picBlackBoxif all keys have been collected. Remove or adjust the first line of the method to ensure that it does not hide picBlackBox prematurely.
Updated Code:
Here's how to modify your UpdateKeyPictureBox method accordingly:
vb
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Update the black box height with calculation
blackBoxHeight = (picKey.Height * (totalKeys - collectedKeys)) \ totalKeys
' Set the size of the picBlackBox based on blackBoxHeight
picBlackBox.Height = blackBoxHeight
picBlackBox.Visible = True ' Ensure the black box is visible while it serves its purpose
picBlackBox.Invalidate() ' Update the Box to reflect changes
Else
' Hide the black box when all keys are collected
picBlackBox.Visible = False
End If
End Sub
Explanation of the Changes:
Conditional Visibility:
The picBlackBox.Visible property is set to True only when collectedKeys < totalKeys, ensuring that the black box is visible right when it's functional.
Setting picBlackBox.Visible = False in the statement ensures that the black box is only hidden when all keys are collected.
User
Right. I moved the black box image somewhere else. and pickey is completely not showinbg in game at all
Assistant
If picKey is not showing at all after moving the black box and making other changes, here are some troubleshooting steps to help ensure that the key image displays correctly.
1. Ensure picKey is Initialized Properly
Make sure the picKey PictureBox is being properly initialized and that its Image property is set with the correct image of the key. This should usually be done in an initialization method, like in frmGame_Load.
Example Initialization Code:
vb
Private Sub InitializeKeyPictureBox()
Dim keyImage As Image = Image.FromFile(Path.Combine(ImagesFolder, "Key.png"))
picKey.Image = keyImage
picKey.SizeMode = PictureBoxSizeMode.StretchImage ' Optional: Change sizing mode as needed
End Sub
2. Confirm Placement
Check the placement and visibility settings of picKey. It should be positioned within the bounds of the form and set to visible.
Check Properties:
Location: Make sure the Location property is set to a visible area on the form.
Size: Confirm that the size of picKey is appropriate for the key image.
Visible: Ensure that the Visible property is set to True.
3. Ensure picKey is Not Behind Other Controls
If other controls are overlapping picKey, it may be obscured. You can call BringToFront() on picKey to ensure it is drawn on top.
Example Code:
vb
picKey.BringToFront()
4. Debugging Output
Add debug statements in your load method and anywhere else picKey gets modified, to confirm its status during runtime. For example, right after you set the image:
Private Sub CenterPicKeyAboveScreen()
Dim screenWidth As Integer = Screen.PrimaryScreen.Bounds.Width
Dim picKeyWidth As Integer = picKey.Width
Dim picKeyHeight As Integer = picKey.Height
picKey.Location = New Point((screenWidth - picKeyWidth) \ 2, -picKeyHeight)
picKey.BringToFront()
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")) ' Use Key.gif for collectable
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
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
collectedKeys += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key")
sfxManager.PlaySoundEffect("Move")
UpdateKeyPictureBox()
CheckForWarp()
Return True
ElseIf targetItem = "picGate" Then
If collectedKeys = totalKeys 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
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
Private Sub picKey_Paint(sender As Object, e As PaintEventArgs) Handles picKey.Paint
If picKey.Image Is Nothing Then
Return
End If
' Draw the key image
e.Graphics.DrawImage(picKey.Image, 0, 0)
' Draw the black box over the key image
If collectedKeys < totalKeys Then
Using blackBrush As New SolidBrush(Color.Black)
e.Graphics.FillRectangle(blackBrush, New Rectangle(0, 0, picKey.Width, blackBoxHeight))
End Using
End If
End Sub
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)
CountKeysInGrid(roomData)
Catch ex As Exception
MessageBox.Show("Error loading room: " & ex.ToString())
End Try
End Sub
Private Sub CountKeysInGrid(roomData As RoomData)
totalKeys = 0
For x As Integer = 0 To roomData.placedItems.Length - 1
If roomData.placedItems(x) IsNot Nothing Then
For y As Integer = 0 To roomData.placedItems(x).Length - 1
If roomData.placedItems(x)(y) IsNot Nothing AndAlso roomData.placedItems(x)(y).ImageKey = "picKey" Then
totalKeys += 1
End If
Next
End If
Next
InitializeKeyPieces(totalKeys)
End Sub
Private Sub InitializeKeyPieces(totalKeys As Integer)
Dim keyImage As Image = Image.FromFile(Path.Combine(ImagesFolder, "Key.png")) ' Use Key.png for picKey
picKey.Image = keyImage
blackBoxHeight = picKey.Height
End Sub
Private Sub UpdateKeyPictureBox()
If collectedKeys < totalKeys Then
' Update the black box height
blackBoxHeight = (picKey.Height * (totalKeys - collectedKeys)) \ totalKeys
picKey.Invalidate() ' Trigger a repaint to update the black box
Else
' Reveal the complete key image
picKey.Image = Image.FromFile(Path.Combine(ImagesFolder, "Key.png")) ' Use Key.png for complete image
picKey.Invalidate() ' Trigger a repaint to update the image
End If
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
vb
Private Sub picKey_Paint(sender As Object, e As PaintEventArgs) Handles picKey.Paint
If picKey.Image Is Nothing Then
Return
End If
' Draw the key image
e.Graphics.DrawImage(picKey.Image, 0, 0)
' Draw the black box over the key image
If collectedKeys < totalKeys Then
Using blackBrush As New SolidBrush(Color.Black)
e.Graphics.FillRectangle(blackBrush, New Rectangle(0, 0, picKey.Width, blackBoxHeight))
End Using
End If
End Sub
Key Points:
Invalidation: Always use Invalidate() after updating properties related to the UI to ensure they repaint correctly.
Resource Management: If you replace images, remember to dispose of the old image to free up memory.
Key Collection Logic: Make sure that the logic around counting collected keys and total keys is accurate when the key is picked up.
Test Your Changes:
After making these changes, run your program and try collecting a key again. Observe if the PictureBox reflects the updated key status correctly. If it still does not update, consider adding breakpoints or logging to understand the flow of updates during the key collection process.
Redraw When Key is Collected:
Make sure to call UpdateKeyPictureBox() whenever a key is collected in your AttemptMove method.
Remove Unnecessary Drawing Logic:
Since you'll now have a dedicated overlay PictureBox, you can remove the drawing and invalidation logic from the picKey_Paint event for the black box.
Example Form Layout Configuration:
Ensure your form layout looks something like this:
plaintext
+-------------------+
| |
| picKey | <-- Key PictureBox
| picBlackBox | <-- Overlay for black box (on top of picKey)
| |
+-------------------+
Advantages of the New Approach:
Simplicity: Separating the key image and the black-out effect reduces complexity since you no longer need to manage custom drawing logic.
Visibility Control: Changing visibility or size of picBlackBox is straightforward, and changes are immediate and clear.
Less Error-Prone: By using standard UI components, you can avoid potential issues related to graphics and drawing that may occur in custom paint methods.
Testing:
After making these changes, run your application and test the key collection functionality. You should see that the black box progressively shrinks to reveal the key beneath it, providing clear visual feedback on key collection.
Ensure Method Visibility:
Check the access modifier of UpdateKeyPictureBox. Make sure it's declared as Private:
vb
Private Sub UpdateKeyPictureBox()
If it's Protected or Public, ensure you’re not inadvertently calling it from an incorrect context.
Ensure Form Is Active:
Make sure that your form is active (not minimized) when you're testing because if it is not visible when a key is collected, it won’t trigger UI updates (Invalidate) as expected.
Test in a Simplified Scenario:
Temporarily simplify the game mechanics for testing. For instance, allow direct calls to UpdateKeyPictureBox, bypassing the normal game flow to see if it works when manually triggered, which can help confirm if the method itself is working.
vb
' For testing purposes
UpdateKeyPictureBox() ' Call this directly at initialization or with a key press
Example Testing Code Snippet:
Add this code in your form load event or any button click for debugging:
vb
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages()
InitializeSoundEffects()
LoadRoomData()
' Test the UpdateKeyPictureBox directly
totalKeys = 5 ' Example total keys
collectedKeys = 0 ' Example initial collected keys
UpdateKeyPictureBox() ' Test the call directly
...
End Sub
Conclusion
If none of these suggestions resolve the issue, you might want to check if there's any event or condition that resets or alters collectedKeys or totalKeys after you attempt to collect keys.
By carefully checking each point, you'll narrow down where the flow breaks and why UpdateKeyPictureBox isn’t being called as expected.
Else
Additional Steps to Verify:
Ensure Overlapping: Verify that picBlackBox is positioned exactly over picKey in the designer or programmatically. If it's not, the black box may appear elsewhere, but you would not see it covering the key.
Confirm Image of picKey: Ensure that picKey itself still contains the key image you expect. You can add debugging output before drawing to ensure the image is set correctly.
Run Your Application: After making the changes, run your application again and collect keys to see if they are revealed as expected.
Debugging Visual Confirmation:
You can add debug statements to visually confirm both collectedKeys and picBlackBox properties:
By implementing these changes, your application should correctly show the key image under the black box and reveal it gradually as keys are collected.
If you’re enabling or disabling the visibility at some point, check the logic to ensure picKey remains visible as expected.
6. Revisit Black Box Implementation
If you relocated the black box, ensure that its new location does not interfere with picKey being displayed. Additionally, ensure picKey is located behind the black box correctly if you intend to have it overlay correctly.
Sample Setup in frmGame_Load:
Here’s how the setup in frmGame_Load might look incorporating the above suggestions:
vb
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages() ' Ensure all images are loaded correctly
InitializeSoundEffects()
InitializeKeyPictureBox() ' Ensure the key picture box is initialized
LoadRoomData()
StartAnimationTimer()
FindPlayerStartPosition()
AddObjectsOnFlippersToMovingObjects()
PlaySelectedMusic()
picTest.Invalidate()
Me.KeyPreview = True
Me.Focus()
' Example initialization for the black box
picBlackBox.Location = picKey.Location
picBlackBox.Size = picKey.Size
picBlackBox.BackColor = Color.Black ' Make it a black overlay
UpdateKeyPictureBox() ' To set up the initial visibility and size
End Sub
Final Tests
Run the application after making these adjustments and check the following:
Does picKey have an image?
Is it located within the visible area of the form?
Is it not obscured by other controls?
Does the black box overlay correctly on top of picKey after collecting keys?
By following these steps, you should be able to identify why picKey isn’t showing as intended and correct it to display the key image appropriately.