Public Class frmGame
Private baddyMovementTimer As Timer
code
Private baddies As New List(Of Baddy)
Private lastDirection As String = "Left" ' Default to left
Private lastMoveTime As DateTime
Private idleTimer As Timer
Private doorImage As Image
Private doorAnimationTimer As Timer
Private doorX As Integer
Private doorY As Integer
Private doorAnimationStartTime As DateTime
Private movingObjects As New List(Of MovingObject)()
Private movingObjectsTimer As Timer
Private CollectedCoins As Integer = 0
Private totalCoins 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", "Sound/Music")
Private ReadOnly SFXFolder As String = Path.Combine(projectDir, "Data", "Sound/Sound Effects")
Private ReadOnly musicManager As New MusicManager()
Private ReadOnly sfxManager As New SFXManager(SFXFolder)
Private totalKeys As Integer = 0
Private collectedKeys As Integer = 0
Private resourceManager As ResourceManager
Private itemAnimations As New List(Of ItemAnimation)()
Private itemAnimationTimer As Timer
' New property to determine if gradient background should be used
Public Property useGradient As Boolean = False
' Timer for redrawing
Private redrawTimer As Timer
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
Private Class ItemAnimation
Public Property ItemImage As Image
Public Property StartX As Integer
Public Property StartY As Integer
Public Property EndX As Integer
Public Property EndY As Integer
Public Property CurrentX As Integer
Public Property CurrentY As Integer
Public Property AnimationDuration As Integer
Public Property StartTime As DateTime
Public Sub New(itemImage As Image, startX As Integer, startY As Integer, endX As Integer, endY As Integer, animationDuration As Integer)
Me.ItemImage = itemImage
Me.StartX = startX
Me.StartY = startY
Me.EndX = endX
Me.EndY = endY
Me.CurrentX = startX
Me.CurrentY = startY
Me.AnimationDuration = animationDuration
Me.StartTime = DateTime.Now
End Sub
Public Function IsAnimationComplete() As Boolean
Return (DateTime.Now - StartTime).TotalMilliseconds >= AnimationDuration
End Function
Public Sub UpdatePosition()
Dim elapsedTime As Integer = CInt((DateTime.Now - StartTime).TotalMilliseconds)
Dim progress As Double = elapsedTime / AnimationDuration
CurrentX = StartX + CInt((EndX - StartX) * progress)
CurrentY = StartY + CInt((EndY - StartY) * progress)
End Sub
End Class
Friend Class Baddy
Public Property X As Integer
Public Property Y As Integer
Public Property CurrentDirection As String
Public Property ImageKey As String
Public Sub New(startX As Integer, startY As Integer, imageKey As String)
Me.X = startX
Me.Y = startY
Me.CurrentDirection = "Right" ' Start moving to the right
Me.ImageKey = imageKey
End Sub
End Class
#Region "Initialization"
Public Sub New()
InitializeComponent()
resourceManager = New ResourceManager("Enigma.frmGame", GetType(frmGame).Assembly)
InitializeSoundEffects()
code
#End Region
#Region " Baddies "
Private Sub AddBaddiesOnGrid()
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
If placedItems(x)(y) IsNot Nothing Then
Dim imageKey As String = placedItems(x)(y)
If imageKey.StartsWith("picBaddy") Then
Dim baddy As New Baddy(x, y, imageKey) ' Pass the imageKey here
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
Debug.WriteLine($"Baddy added at ({x}, {y})")
End If
End If
Next
Next
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
lastMoveTime = DateTime.Now
' No need to invalidate here, the redraw timer will handle it
End If
code
#End Region
#Region "Drawing"
Private Sub OnAnimationTick(sender As Object, e As EventArgs)
For Each img In animatedImages
ImageAnimator.UpdateFrames(img)
Next
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()
StopAndDisposeRedrawTimer()
StopAndDisposeIdleTimer()
End Sub
code
Private Sub StopAndDisposeIdleTimer()
If idleTimer IsNot Nothing Then
idleTimer.Stop()
idleTimer.Dispose()
idleTimer = Nothing
End If
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 StopAndDisposeRedrawTimer()
If redrawTimer IsNot Nothing Then
redrawTimer.Stop()
redrawTimer.Dispose()
redrawTimer = Nothing
End If
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnCLose.Click
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
Public Class DoubleBufferedPictureBox
Inherits PictureBox
code
Public Sub New()
Me.DoubleBuffered = True
End Sub
End Class
Public Class NoBorderToolStripRenderer
Inherits ToolStripRenderer
code
Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs)
' Do nothing to prevent the border from being drawn
End Sub
Protected Overrides Sub OnRenderButtonBackground(e As ToolStripItemRenderEventArgs)
' Do nothing to prevent the button background from being drawn
End Sub
Protected Overrides Sub OnRenderItemBackground(e As ToolStripItemRenderEventArgs)
' Do nothing to prevent the item background from being drawn
End Sub
End Class
I have a flipper on Verticalwall 0, 5 and HorizontalWall 7, 0.
I also have a flipper on VerticalWall 16, 5 and HorizontalWall 7, 11 (These 2 work as intended)
remember wall items start at 0,0 and squares start at 0,0 There is 1 more Vertical wall than there is squares going from left to right and there is 1 more horizontal wall than squares going from top to bottom. As you can see we have 16 vertical walls to the 15 Squares and horizontal walls. Going from left to right. We also have 11 horizontal walls and 10 squares and 10 vertical walls going from top to bottom. So the maths needs to work around that.
Here is the output when I run a test level.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.Wasapi.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Flipper3 detected at (7, 11)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Flipper1 detected at (16, 5)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
The program '[5336] Enigma.exe' has exited with code 0 (0x0).
As you can see, it is skipping the flippers on the left and top border. Can you help?
Assistant
Based on the information you've provided, it seems like the flippers you have on the left and top edges (VerticalWall 0, 5 and HorizontalWall 7, 0) are causing issues because of how you're managing the flipper detection and wall arrangement relative to the grid coordinates.
The problem lies with how you're verifying the existence and detection of flippers, particularly at the edges of your grid system. Let's review your wall and flipper detection logic to ensure we handle these edges appropriately.
Key Considerations:
Wall and Square Offsets: Since there is an extra wall for both vertical and horizontal, you need to ensure that your detection does not exceed the bounds of the arrays you are checking against.
Flipper Positioning: If you're trying to map flipper positions in a grid where walls are counted but not squares, your checks must accommodate this difference.
Boundary Checks: Before accessing elements in your array (verticalWallItems and horizontalWallItems), ensure that the indices are within valid ranges.
Suggested Changes:
Checking for Flippers:
When checking if a moving object is on a flipper, ensure you do not exceed array bounds.
Consider conditionally adjusting your offset for flipper detection when dealing with grid edges.
Update CheckForFlipper Method:
Here’s a revised version of your CheckForFlipper function that adds proper boundary checks:
vb
User
Output is exactly the same.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.Wasapi.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Flipper3 detected at (7, 11)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Flipper1 detected at (16, 5)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
The program '[2404] Enigma.exe' has exited with code 0 (0x0).
Assistant
Based on the output you provided and your previous description of the issue with flipper detection on the borders, it seems that while the flippers are detected, the issue lies within the parameters and boundaries of the arrays you're using.
The System.ArgumentException is likely being thrown by something related to audio playback (as indicated by the stack trace snippet mentioning NAudio), but it could also be a symptom of other issues in your game logic that are indirectly causing audio handling to fail. However, since your main concern indicates the flipper not functioning as expected at the beginning of the walls, let's analyze the possible issues.
Main Areas to Review
Wall Items vs. Square Items:
The confusion between wall indices and square indices seems to be the main culprit. Ensure that when you check for flipper presence, the mapping of wall to square indices is understood correctly. Since you have one more wall than squares, your checks must reflect that.
Flipper Positioning:
Ensure your flipper objects are correctly positioned on the walls as intended, and understand how walls are defined (extra walls).
Array Lengths:
When accessing verticalWallItems or horizontalWallItems, ensure you check their dimensions properly.
Steps to Debug
To facilitate debugging and ensure the logic is correct, consider the following:
Flipper Placement:
Verify that the flippers are correctly initialized in your level data. Use debugging statements to output the current wall and square lengths and confirm the expected positions of the flippers.
Comprehensive Debugging:
Add more detailed logging before your flipper detection logic to see exactly what conditions are met when you attempt to check for flippers. This will help you identify whether the correct paths in your logic are being executed.
Check for Conflicting Code:
Ensure there are no other parts of the code that might interfere with the flipper's behavior or state.
Example of Comprehensive Debugging
Here’s how you might add some debug output in your CheckForFlipper method to get more insight:
vb
User
'Enigma.exe' (CoreCLR: DefaultDomain): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Private.CoreLib.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\Enigma.dll'. Symbols loaded.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\Microsoft.VisualBasic.Forms.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\System.Windows.Forms.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'c:\program files\microsoft visual studio\2022\community\common7\ide\commonextensions\microsoft\hotreload\Microsoft.Extensions.DotNetDeltaApplier.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.IO.Pipes.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Linq.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Collections.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Console.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Threading.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Runtime.InteropServices.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Threading.Overlapped.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Security.AccessControl.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Security.Principal.Windows.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Security.Claims.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Runtime.Loader.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Collections.Concurrent.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\System.Windows.Forms.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Diagnostics.TraceSource.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.ComponentModel.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Drawing.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Collections.Specialized.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Threading.Thread.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.ComponentModel.EventBasedAsync.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.ComponentModel.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\System.Drawing.Common.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\Microsoft.Win32.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\Accessibility.dll'. Module was built without symbols.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.ComponentModel.TypeConverter.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\Microsoft.VisualBasic.Core.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Numerics.Vectors.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\Microsoft.Win32.SystemEvents.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Memory.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\System.Resources.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.11\System.Drawing.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.ObjectModel.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Private.Uri.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Collections.NonGeneric.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Threading.ThreadPool.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Text.Json.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Text.Encoding.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Text.Encodings.Web.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Runtime.Intrinsics.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Reflection.Emit.Lightweight.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Reflection.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\System.Reflection.Emit.ILGeneration.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.Core.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.11\netstandard.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.WinMM.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.Wasapi.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Checking flipper for moving object at (7, 10)
Checking right flipper at (8, 10)
Left flipper check skipped at (7, 10)
Checking down flipper at (7, 11)
Flipper3 detected at (7, 11)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Up flipper check skipped at (7, 10)
Checking flipper for moving object at (15, 5)
Checking right flipper at (16, 5)
Flipper1 detected at (16, 5)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Left flipper check skipped at (15, 5)
Down flipper check exceeded bounds at (15, 6)
Up flipper check skipped at (15, 5)
Checking flipper for moving object at (14, 5)
Checking right flipper at (15, 5)
Left flipper check skipped at (14, 5)
Down flipper check exceeded bounds at (14, 6)
Up flipper check skipped at (14, 5)
Checking flipper for moving object at (7, 9)
Checking right flipper at (8, 9)
Left flipper check skipped at (7, 9)
Down flipper check exceeded bounds at (7, 10)
Up flipper check skipped at (7, 9)
Checking flipper for moving object at (13, 5)
Checking right flipper at (14, 5)
Left flipper check skipped at (13, 5)
Down flipper check exceeded bounds at (13, 6)
Up flipper check skipped at (13, 5)
Checking flipper for moving object at (7, 8)
Checking right flipper at (8, 8)
Left flipper check skipped at (7, 8)
Down flipper check exceeded bounds at (7, 9)
Up flipper check skipped at (7, 8)
Checking flipper for moving object at (12, 5)
Checking right flipper at (13, 5)
Left flipper check skipped at (12, 5)
Down flipper check exceeded bounds at (12, 6)
Up flipper check skipped at (12, 5)
Checking flipper for moving object at (7, 7)
Checking right flipper at (8, 7)
Left flipper check skipped at (7, 7)
Down flipper check exceeded bounds at (7, 8)
Up flipper check skipped at (7, 7)
Checking flipper for moving object at (11, 5)
Checking right flipper at (12, 5)
Left flipper check skipped at (11, 5)
Down flipper check exceeded bounds at (11, 6)
Up flipper check skipped at (11, 5)
Checking flipper for moving object at (7, 6)
Checking right flipper at (8, 6)
Left flipper check skipped at (7, 6)
Down flipper check exceeded bounds at (7, 7)
Up flipper check skipped at (7, 6)
Checking flipper for moving object at (10, 5)
Checking right flipper at (11, 5)
Left flipper check skipped at (10, 5)
Down flipper check exceeded bounds at (10, 6)
Up flipper check skipped at (10, 5)
Checking flipper for moving object at (7, 5)
Checking right flipper at (8, 5)
Left flipper check skipped at (7, 5)
Down flipper check exceeded bounds at (7, 6)
Up flipper check skipped at (7, 5)
Checking flipper for moving object at (9, 5)
Checking right flipper at (10, 5)
Left flipper check skipped at (9, 5)
Down flipper check exceeded bounds at (9, 6)
Up flipper check skipped at (9, 5)
Checking flipper for moving object at (7, 4)
Checking right flipper at (8, 4)
Left flipper check skipped at (7, 4)
Down flipper check exceeded bounds at (7, 5)
Up flipper check skipped at (7, 4)
Checking flipper for moving object at (8, 5)
Checking right flipper at (9, 5)
Left flipper check skipped at (8, 5)
Down flipper check exceeded bounds at (8, 6)
Up flipper check skipped at (8, 5)
Checking flipper for moving object at (7, 3)
Checking right flipper at (8, 3)
Left flipper check skipped at (7, 3)
Down flipper check exceeded bounds at (7, 4)
Up flipper check skipped at (7, 3)
Checking flipper for moving object at (7, 5)
Checking right flipper at (8, 5)
Left flipper check skipped at (7, 5)
Down flipper check exceeded bounds at (7, 6)
Up flipper check skipped at (7, 5)
Checking flipper for moving object at (7, 2)
Checking right flipper at (8, 2)
Left flipper check skipped at (7, 2)
Down flipper check exceeded bounds at (7, 3)
Up flipper check skipped at (7, 2)
Checking flipper for moving object at (6, 5)
Checking right flipper at (7, 5)
Left flipper check skipped at (6, 5)
Down flipper check exceeded bounds at (6, 6)
Up flipper check skipped at (6, 5)
Checking flipper for moving object at (7, 1)
Checking right flipper at (8, 1)
Left flipper check skipped at (7, 1)
Down flipper check exceeded bounds at (7, 2)
Up flipper check skipped at (7, 1)
Checking flipper for moving object at (5, 5)
Checking right flipper at (6, 5)
Left flipper check skipped at (5, 5)
Down flipper check exceeded bounds at (5, 6)
Up flipper check skipped at (5, 5)
Checking flipper for moving object at (7, 0)
Checking right flipper at (8, 0)
Left flipper check skipped at (7, 0)
Down flipper check exceeded bounds at (7, 1)
Up flipper check skipped at (7, 0)
Checking flipper for moving object at (4, 5)
Checking right flipper at (5, 5)
Left flipper check skipped at (4, 5)
Down flipper check exceeded bounds at (4, 6)
Up flipper check skipped at (4, 5)
Checking flipper for moving object at (3, 5)
Checking right flipper at (4, 5)
Left flipper check skipped at (3, 5)
Down flipper check exceeded bounds at (3, 6)
Up flipper check skipped at (3, 5)
Checking flipper for moving object at (2, 5)
Checking right flipper at (3, 5)
Left flipper check skipped at (2, 5)
Down flipper check exceeded bounds at (2, 6)
Up flipper check skipped at (2, 5)
Checking flipper for moving object at (1, 5)
Checking right flipper at (2, 5)
Left flipper check skipped at (1, 5)
Down flipper check exceeded bounds at (1, 6)
Up flipper check skipped at (1, 5)
Checking flipper for moving object at (0, 5)
Checking right flipper at (1, 5)
Left flipper check skipped at (0, 5)
Down flipper check exceeded bounds at (0, 6)
Up flipper check skipped at (0, 5)
The program '[6688] Enigma.exe' has exited with code 0 (0x0).
Assistant
Based on your output, we can see that the flippers are detected, but there are exceptions occurring when interacting with the NAudio audio system. The issue persists primarily at positions (7, 11) for Flipper3 and (16, 5) for Flipper1, and both trigger System.ArgumentException.
While debugging indicates that the checks for flippers work correctly, there seems to be an issue with audio playback in your code and how it interacts with flippers. Additionally, the Down flipper check exceeded bounds and similar messages suggest you're possibly checking indices beyond the limits of your arrays, which could cause exceptions.
Steps to Troubleshoot the Issue
Check Audio Playback Logic:
Since NAudio is raising ArgumentException, this is likely due to an invalid operation such as trying to play a sound on a disposed or null object. Ensure that your audio playback logic (particularly when you call PlaySoundEffect) is robust and can handle cases where the sound might not be initialized or is otherwise unavailable.
Bounds Checking:
You mentioned having one extra wall than there are squares. In your checks for flipper conditions, ensure that you are not attempting to access out-of-bounds indices. For example, when checking for walls, ensure you're always validating against the length of your arrays:
vb
If x + 1 < verticalWallItems.Length Then
' Proceed with your flipper check
Else
' Log that you're skipping the check.
End If
Logging Sound Effect Play Attempts:
Add debug logging to show when you're attempting to play sound effects, and print the file path or key you're providing to the sfxManager. This will help identify if the sound being played exists and is valid.
Flipper Logic Verification:
Confirm that the logic for activating flippers is sound. Review if the conditions under which a flipper plays sound effects are properly set up (i.e., activated by the right object).
Inspect Sound Effect Initialization:
Check how your SFXManager is configured. If you're playing a sound that isn't loaded properly, it may throw an ArgumentException. You can do this in the class where you manage sound effects by ensuring that sound files are loaded successfully before attempting playback.
Check for Null Values:
Ensure that whenever you're about to play a sound, the retrieved sound object is not null. For example:
User
I'm aware of the sound effect. I know what's causing it, I know what to do. Let's stick to the problem at hand. The flipper.
Assistant
Understood! Let's focus on the flipper detection problem. Based on the debugging output you've shared, it appears that the flippers are being detected correctly, but you're running into boundary issues with the checks related to wall items and grid coordinates.
Summary of Findings
Detection Logic: It appears that the logic for detecting flippers works correctly based on their intended locations.
Boundary Checks: You are getting messages like Down flipper check exceeded bounds and Left flipper check skipped. This indicates that the checks are not correctly accounting for the boundaries of your wall items versus your squares geometry.
Revising the Flipper Detection Logic
With the understanding that walls and squares are organized somewhat differently (one extra row for walls and one extra for columns), we can refine the boundary checks just a bit more in the CheckForFlipper method.
Key Adjustments Needed:
Understanding Wall vs. Square Indexing:
Ensure that when checking for flippers, you're checking the right index based on how many walls there are relative to the actual square grid.
Boundary Adjustments:
Your flipper checks need to account for the additional wall indices correctly. When checking wall items, consider how they relate back to the square grid.
Here’s a refined version of the CheckForFlipper function to improve how it verifies flippers while adhering to proper bounds:
vb
User
Checking flipper for moving object at (7, 9)
Checking flipper for moving object at (14, 5)
Checking flipper for moving object at (7, 8)
Checking flipper for moving object at (13, 5)
Checking flipper for moving object at (7, 7)
Checking flipper for moving object at (12, 5)
Checking flipper for moving object at (7, 6)
Checking flipper for moving object at (11, 5)
Checking flipper for moving object at (7, 5)
Checking flipper for moving object at (10, 5)
Checking flipper for moving object at (7, 4)
Checking flipper for moving object at (9, 5)
Checking flipper for moving object at (7, 3)
Checking flipper for moving object at (8, 5)
Checking flipper for moving object at (7, 2)
Checking flipper for moving object at (7, 5)
Checking flipper for moving object at (7, 1)
Checking flipper for moving object at (6, 5)
Checking flipper for moving object at (7, 0)
Up flipper check skipped at (7, 0)
Checking flipper for moving object at (5, 5)
Checking flipper for moving object at (4, 5)
Checking flipper for moving object at (3, 5)
Checking flipper for moving object at (2, 5)
Checking flipper for moving object at (1, 5)
Checking flipper for moving object at (0, 5)
Left flipper check skipped at (0, 5)
The program '[19300] Enigma.exe' has exited with code 0 (0x0).
Assistant
Thank you for sharing the most recent output regarding flipper detection in your game. Based on the information, it appears that your logging statements effectively track the positions being checked, indicating that the detection logic runs properly in terms of calling the method for the moving objects.
Observations from the Output
Flipper Check Mechanism: The method is checking for flippers at expected positions but is skipping checks and failing to detect the flippers, especially at the coordinates that correspond to the border conditions. You are seeing messages like Up flipper check skipped at (7, 0) and Left flipper check skipped at (0, 5). This indicates that the checks are not accessing the right items due to boundary conditions.
Identification of Issues
The logic for determining whether a flipper is present might be bypassing checks due to:
Improper handling of array bounds.
The differences in how walls and squares are indexed in your game.
Refining the Logic Further
To address the skipped conditions and ensure that flipper detection works properly, we need to revisit how we check the conditions. Specifically, we should implement additional checks for boundary alignment based on square dimensions and walls effectively.
Boundary Handling: Ensure you correctly access vertical and horizontal wall items based on the indexing of your array.
Consistent Checks: Use the dimensions of verticalWallItems and horizontalWallItems while checking to avoid skipping any potential flippers that are located on the edges of your grid.
Revised Check for Flippers
Here’s a more targeted implementation:
vb
User
Checking flipper for moving object at (7, 10)
Flipper3 detected at (7, 11)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Checking flipper for moving object at (15, 5)
Flipper1 detected at (16, 5)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Checking flipper for moving object at (14, 5)
Checking flipper for moving object at (7, 9)
Checking flipper for moving object at (13, 5)
Checking flipper for moving object at (7, 8)
Checking flipper for moving object at (12, 5)
Checking flipper for moving object at (7, 7)
Checking flipper for moving object at (11, 5)
Checking flipper for moving object at (7, 6)
Checking flipper for moving object at (10, 5)
Checking flipper for moving object at (7, 5)
Checking flipper for moving object at (9, 5)
Checking flipper for moving object at (7, 4)
Checking flipper for moving object at (8, 5)
Checking flipper for moving object at (7, 3)
Checking flipper for moving object at (7, 5)
Checking flipper for moving object at (7, 2)
Checking flipper for moving object at (6, 5)
Checking flipper for moving object at (7, 1)
Checking flipper for moving object at (5, 5)
Checking flipper for moving object at (7, 0)
Checking flipper for moving object at (4, 5)
Checking flipper for moving object at (3, 5)
Checking flipper for moving object at (2, 5)
Checking flipper for moving object at (1, 5)
Checking flipper for moving object at (0, 5)
The program '[17392] Enigma.exe' has exited with code 0 (0x0).
Please ignore the Naudio. I know what is happening there. It will be fixed at a later date. It's a caught bug, and I know what to do.
Assistant
Thanks for clarifying the situation regarding the NAudio exception. Let's focus solely on the flipper detection issue you're experiencing.
Current Output Analysis
From the latest output you've shared, it seems that:
The flippers are being detected accurately where expected, e.g., Flipper3 detected at (7, 11) and Flipper1 detected at (16, 5).
However, since you are seeing consistent checks on squares like (7, 10), (15, 5), etc., it indicates the flipper detection logic itself is functioning but may still result in accessing wall items or square positions incorrectly.
Revisiting Flipper Logic
Given that flipper detection occurs successfully in some cases but anomalies arise elsewhere, let's verify a few key points in the grid arrangement, particularly ensuring your checks align with how walls relate to squares:
Square-Wall Indexing Relationship:
Ensure that the checks correctly correspond to available wall items and their indices.
Confirm that flippers are correct in terms of the items placed within your logic.
Array Bounds and Wall Items:
Make sure the conditions allow for checks against both wall indices correctly according to your game grid layout.
Review how you handle boundary conditions to make sure flippers on the edges are correctly evaluated during movement.
Detailed Check Implementation
Here’s an enhanced version of your flipper checking logic, along with boundary precautions to ensure you’re accurately identifying the flippers without index misconduct.
vb
User
No different. It should find a flipper VerticalWall 0,5 and a flipper at horizontal wall 7,0. But it does not. I assure you they are there
Assistant
Thank you for your patience and clarification regarding the specific flipper positions (VerticalWall 0, 5 and HorizontalWall 7, 0) that should be detected and are not being recognized by your code.
Let's revisit the logic and debugging steps carefully to identify what might be preventing the detection of these specific flippers.
Key Points to Investigate
Array Dimensions: Ensure that the dimensions of verticalWallItems and horizontalWallItems support your checks without going out of bounds. Specifically, since you mentioned the flippers are located at the edges (0 or maximum values), your checks should accommodate this.
Flipper Positioning: Given that these indices correspond to the wall structure, confirm that they are indeed set up correctly in your level data and that wall items are being loaded correctly.
Detailed Debugging: Add a more extensive debug output to clarify exactly what indices are being accessed and what values exist at those locations.
Steps to Address the Issue
Step 1: Inspect the Wall Indices
In your data setup, check how flippers are represented in both the vertical and horizontal wall items. Verify that the indices correspond correctly with your expectations.
Step 2: Adjust Condition Checks
Update your CheckForFlipper method to log not only the attempted checks but also the sizes of the arrays and the specific values at the indices being accessed.
Revised Check for Flippers
Here’s an example of how to enhance your CheckForFlipper method to include more comprehensive logging:
vb
User
'Enigma.exe' (CoreCLR: clrhost): Loaded 'D:\01 - Grags\Visual Studio\Enigma\Enigma\bin\Debug\net8.0-windows\NAudio.Wasapi.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Checking flipper for moving object at (7, 10)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 10) - Value:
Checking left flipper at (7, 10) - Value:
Checking down flipper at (7, 11) - Value: picFlipper3
Flipper3 detected at (7, 11)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Checking up flipper at (7, 10) - Value:
Checking flipper for moving object at (15, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (16, 5) - Value: picFlipper1
Flipper1 detected at (16, 5)
Exception thrown: 'System.ArgumentException' in NAudio.Core.dll
Checking left flipper at (15, 5) - Value:
Checking down flipper at (15, 6) - Value:
Checking up flipper at (15, 5) - Value:
Checking flipper for moving object at (7, 9)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 9) - Value:
Checking left flipper at (7, 9) - Value:
Checking down flipper at (7, 10) - Value:
Checking up flipper at (7, 9) - Value:
Checking flipper for moving object at (14, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (15, 5) - Value:
Checking left flipper at (14, 5) - Value:
Checking down flipper at (14, 6) - Value:
Checking up flipper at (14, 5) - Value:
Checking flipper for moving object at (7, 8)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 8) - Value:
Checking left flipper at (7, 8) - Value:
Checking down flipper at (7, 9) - Value:
Checking up flipper at (7, 8) - Value:
Checking flipper for moving object at (13, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (14, 5) - Value:
Checking left flipper at (13, 5) - Value:
Checking down flipper at (13, 6) - Value:
Checking up flipper at (13, 5) - Value:
Checking flipper for moving object at (7, 7)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 7) - Value:
Checking left flipper at (7, 7) - Value:
Checking down flipper at (7, 8) - Value:
Checking up flipper at (7, 7) - Value:
Checking flipper for moving object at (12, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (13, 5) - Value:
Checking left flipper at (12, 5) - Value:
Checking down flipper at (12, 6) - Value:
Checking up flipper at (12, 5) - Value:
Checking flipper for moving object at (7, 6)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 6) - Value:
Checking left flipper at (7, 6) - Value:
Checking down flipper at (7, 7) - Value:
Checking up flipper at (7, 6) - Value:
Checking flipper for moving object at (11, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (12, 5) - Value:
Checking left flipper at (11, 5) - Value:
Checking down flipper at (11, 6) - Value:
Checking up flipper at (11, 5) - Value:
Checking flipper for moving object at (7, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 5) - Value:
Checking left flipper at (7, 5) - Value:
Checking down flipper at (7, 6) - Value:
Checking up flipper at (7, 5) - Value:
Checking flipper for moving object at (10, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (11, 5) - Value:
Checking left flipper at (10, 5) - Value:
Checking down flipper at (10, 6) - Value:
Checking up flipper at (10, 5) - Value:
Checking flipper for moving object at (7, 4)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 4) - Value:
Checking left flipper at (7, 4) - Value:
Checking down flipper at (7, 5) - Value:
Checking up flipper at (7, 4) - Value:
Checking flipper for moving object at (9, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (10, 5) - Value:
Checking left flipper at (9, 5) - Value:
Checking down flipper at (9, 6) - Value:
Checking up flipper at (9, 5) - Value:
Checking flipper for moving object at (7, 3)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 3) - Value:
Checking left flipper at (7, 3) - Value:
Checking down flipper at (7, 4) - Value:
Checking up flipper at (7, 3) - Value:
Checking flipper for moving object at (8, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (9, 5) - Value:
Checking left flipper at (8, 5) - Value:
Checking down flipper at (8, 6) - Value:
Checking up flipper at (8, 5) - Value:
Checking flipper for moving object at (7, 2)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 2) - Value:
Checking left flipper at (7, 2) - Value:
Checking down flipper at (7, 3) - Value:
Checking up flipper at (7, 2) - Value:
Checking flipper for moving object at (7, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 5) - Value:
Checking left flipper at (7, 5) - Value:
Checking down flipper at (7, 6) - Value:
Checking up flipper at (7, 5) - Value:
Checking flipper for moving object at (7, 1)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 1) - Value:
Checking left flipper at (7, 1) - Value:
Checking down flipper at (7, 2) - Value:
Checking up flipper at (7, 1) - Value:
Checking flipper for moving object at (6, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (7, 5) - Value:
Checking left flipper at (6, 5) - Value:
Checking down flipper at (6, 6) - Value:
Checking up flipper at (6, 5) - Value:
Checking flipper for moving object at (7, 0)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (8, 0) - Value:
Checking left flipper at (7, 0) - Value:
Checking down flipper at (7, 1) - Value:
Up flipper check skipped - Out of bounds at (7, 0)
Checking flipper for moving object at (5, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (6, 5) - Value:
Checking left flipper at (5, 5) - Value:
Checking down flipper at (5, 6) - Value:
Checking up flipper at (5, 5) - Value:
Checking flipper for moving object at (4, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (5, 5) - Value:
Checking left flipper at (4, 5) - Value:
Checking down flipper at (4, 6) - Value:
Checking up flipper at (4, 5) - Value:
Checking flipper for moving object at (3, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (4, 5) - Value:
Checking left flipper at (3, 5) - Value:
Checking down flipper at (3, 6) - Value:
Checking up flipper at (3, 5) - Value:
Checking flipper for moving object at (2, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (3, 5) - Value:
Checking left flipper at (2, 5) - Value:
Checking down flipper at (2, 6) - Value:
Checking up flipper at (2, 5) - Value:
Checking flipper for moving object at (1, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (2, 5) - Value:
Checking left flipper at (1, 5) - Value:
Checking down flipper at (1, 6) - Value:
Checking up flipper at (1, 5) - Value:
Checking flipper for moving object at (0, 5)
Vertical wall array length: 17, Horizontal wall array length: 16
Checking right flipper at (1, 5) - Value:
Checking down flipper at (0, 6) - Value:
Checking up flipper at (0, 5) - Value:
The program '[2524] Enigma.exe' has exited with code 0 (0x0).
Assistant
From your latest output, I see that the checks for flippers at the intended locations seem to fail due to the indices not accessing the correct wall item values. Specifically:
The check for the vertical wall at (0, 5) and the horizontal wall at (7, 0) does not yield the expected results in terms of returning the flipper when it should.
Observations from Logging
Vertical Wall Length: Vertical wall array length: 17 indicates that you have 17 entries in your vertical wall items. Given that you have a grid of 0 to 15 squares (16 grid positions), it makes sense that you have an extra entry for the walls.
Horizontal Wall Length: Horizontal wall array length: 16 means you are on the right track here as you should have one row of wall items larger than the grid squares themselves.
Flipper Detection: The log output confirms that the values you are trying to read at certain indices are either empty or producing no valid returns. Specifically:
Value: for several checks indicates that no item exists at those positions in the wall arrays.
Suggested Steps to Resolve the Issue
Verify Initialization:
Ensure that, during your room data loading or initialization, the walls and their respective properties (including flippers) are correctly set. This means checking how verticalWallItems and horizontalWallItems are populated.
Check Wall Item Population:
Add checks right after you populate these arrays to ensure the items are set correctly. You should be populating according to how you store flippers in your data.
Refined Array Access Check:
When checking for the presence of flippers, ensure that whenever you are trying to access something in an array, the indices being referenced are verified to contain values (and are indeed intended to contain properties such as picFlipperX).
Debugging Changes
To further investigate, you can add more checks right after you’ve populated your wall arrays. For example:
vb
User
OK. Now the flippers on the right and bottom aren't pushing the blocks.
Checking flipper for moving object at (7, 10)
Checking right flipper at (8, 10) - Value:
Checking left flipper at (7, 10) - Value:
Checking down flipper at (7, 11) - Value: picFlipper3
Flipper3 detected at (7, 11)
Checking up flipper at (7, 10) - Value:
Checking flipper for moving object at (15, 5)
Checking right flipper at (16, 5) - Value: picFlipper1
Flipper1 detected at (16, 5)
Checking left flipper at (15, 5) - Value:
Checking down flipper at (15, 6) - Value:
Checking up flipper at (15, 5) - Value:
The program '[20300] Enigma.exe' has exited with code 0 (0x0).
Assistant
Thank you for your update about the flippers and the current state of the block-pushing mechanics. Based on your outputs, it seems the detection for the flippers has improved, but the functionality of pushing blocks using the flippers is not being activated properly.
Observations
Flipper Detection:
You're detecting Flipper3 at (7, 11) and Flipper1 at (16, 5) successfully.
The values of items at wall indices are being logged properly, indicating that flippers are recognized.
Block Pushing:
You mentioned that flippers on the right and bottom are not pushing blocks as expected. This signals that while flippers are detected, the logic that governs their effects, particularly on blocks, may be insufficient or incorrectly set up.
Steps to Resolve Block Pushing Issue
Verify the Logic Handling Block Movement with Flippers:
Flippers should modify the DeltaX and DeltaY properties of the blocks or the moving objects they come into contact with. Check if the logic correctly updates the movingObject's parameters when activating a flipper.
Ensure the CheckForFlipper Method Updates the Moving Object:
Every time a flipper is detected, ensure that the corresponding moving object also modifies its parameters according to the flipper’s behavior.
Check Activation of Movement on Flippers:
When a flipper is detected, add a mechanism to check if there is a block or ball immediately in the direction of the flipper's action. If so, act upon it.
Implementing the Logic for Flipper Activation
Here’s a potential revision of your CheckForFlipper method, ensuring blocks are pushed upon flipper activation:
vb
User
I'm sorry, but we don't need new subs. All the code to push the blocks is already present. The error is 100% inside CheckForFlipper. Before the last bit of code, all i had to do was move the border flippers over 1 square and everything works as intended. The fault is, due to fear of indexoutside... it isn't checking the borders on the left and the top.
Assistant
Thank you for the clarification! Let's focus on adjusting the CheckForFlipper method to properly handle the flippers at the borders without skipping checks due to index bounds.
Goal:
The goal is to ensure that flippers located at the left and top boundaries can be checked without causing out-of-bounds exceptions.
Adjusting CheckForFlipper
Boundary Conditions: The main change here is to ensure we are checking the left and top boundary cases more effectively.
Checking Flippers: We will ensure that checks do not skip the borders by refining the condition checks while maintaining necessary boundary safety.
Here’s an updated version of the CheckForFlipper method that explicitly checks the borders while still being cautious about accessing arrays:
vb
User
You did it !!
Assistant
Fantastic! I'm glad to hear that it worked! 🎉 If you have any more questions or need further assistance with any other part of your project, feel free to ask. Happy coding, and good luck with the rest of your game development!
User
Awesome. Let's tidy it up npw and remove the unesersary comments
Assistant
Absolutely! Here’s a cleaner version of the CheckForFlipper function with unnecessary comments removed and the code streamlined. This should help improve readability while retaining the functionality you’ve established:
vb
User
Thank you. That works perfectly now. Thanks a lot
Assistant
You're very welcome! I'm glad to hear that everything is working perfectly now. If you have any more questions or need assistance in the future—whether it's about your game or any other topic—don’t hesitate to reach out. Happy coding, and best of luck with the rest of your project! 🎮😊
Not yet included in a published release.
' Enable double buffering for the form
Me.DoubleBuffered = True
' Enable double buffering for the PictureBox
EnableDoubleBuffering(picTest)
' Initialize the idle timer
idleTimer = New Timer() With {.Interval = 250} ' 1 second
AddHandler idleTimer.Tick, AddressOf OnIdleTick
idleTimer.Start()
End Sub
Private Sub EnableDoubleBuffering(control As Control)
Dim propertyInfo As PropertyInfo = control.GetType().GetProperty("DoubleBuffered", BindingFlags.NonPublic Or BindingFlags.Instance)
propertyInfo.SetValue(control, True, Nothing)
End Sub
Private Sub frmGame_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeImages()
LoadRoomData()
StartAnimationTimer()
FindPlayerStartPosition()
AddObjectsOnFlippersToMovingObjects()
PlaySelectedMusic()
' Initialize the redraw timer
redrawTimer = New Timer() With {.Interval = 50} ' 20 times a second
AddHandler redrawTimer.Tick, AddressOf OnRedrawTick
redrawTimer.Start()
itemAnimationTimer = New Timer() With {.Interval = 16} ' Approximately 60 FPS
AddHandler itemAnimationTimer.Tick, AddressOf OnItemAnimationTick
itemAnimationTimer.Start()
End Sub
Private Sub InitializeImages()
Try
' Load images into the imageDictionary
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("picStartLeft") = Image.FromFile(Path.Combine(ImagesFolder, "Guy Left.gif"))
imageDictionary("picStartRight") = Image.FromFile(Path.Combine(ImagesFolder, "Guy Right.gif"))
imageDictionary("picBlockStopper1") = Image.FromFile(Path.Combine(ImagesFolder, "Debris1.png"))
imageDictionary("picBaddy1") = Image.FromFile(Path.Combine(ImagesFolder, "Baddy1.gif"))
imageDictionary("picBaddy2") = Image.FromFile(Path.Combine(ImagesFolder, "Baddy2.gif"))
imageDictionary("picBaddy3") = Image.FromFile(Path.Combine(ImagesFolder, "Baddy3.gif"))
imageDictionary("picBaddy4") = Image.FromFile(Path.Combine(ImagesFolder, "Baddy4.gif"))
imageDictionary("picExplosion") = Image.FromFile(Path.Combine(ImagesFolder, "Explosion.gif")) ' Load explosion image
' Extract the first frame of the door image
doorImage = ExtractFirstFrame(imageDictionary("picGate"))
Dim animatedImageKeys As String() = {
"picLazer1", "picLazer2", "picFlipper1", "picFlipper2",
"picFlipper3", "picFlipper4", "picCoin", "picGate",
"picKey", "picFinish", "picBall", "picWarp", "picWarp2", "picStart", "picStartLeft", "picStartRight",
"picBaddy1", "picBaddy2", "picBaddy3", "picBaddy4", "picExplosion" ' Add explosion image to animated images
}
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 Function ExtractFirstFrame(animatedImage As Image) As Image
Dim frameDimensions As New FrameDimension(animatedImage.FrameDimensionsList(0))
animatedImage.SelectActiveFrame(frameDimensions, 0)
Return New Bitmap(animatedImage)
End Function
Private Sub InitializeSoundEffects()
' sfxManager is already initialized in the constructor
End Sub
Private Sub LoadRoomData()
If Not String.IsNullOrEmpty(RoomFilePath) AndAlso File.Exists(RoomFilePath) Then
LoadRoomFromFile(RoomFilePath)
AddBaddiesOnGrid() ' Add this method to place baddies
StartBaddyMovementTimer() ' Start moving baddies
Else
MessageBox.Show("Room file not found.")
Me.Close()
End If
End Sub
Private Sub StartAnimationTimer()
animationTimer = New Timer() With {.Interval = 33} ' Approximately 30 FPS
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
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 ' Ensure the interval is appropriate
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 Sub StartBaddyMovementTimer()
baddyMovementTimer = New Timer() With {.Interval = 250} ' Adjust speed as needed
AddHandler baddyMovementTimer.Tick, AddressOf OnBaddyMovementTick
baddyMovementTimer.Start()
End Sub
Private Sub OnBaddyMovementTick(sender As Object, e As EventArgs)
' Iterate over the baddies list in reverse order to safely remove baddies
For i As Integer = baddies.Count - 1 To 0 Step -1
Try
Dim baddy As Baddy = baddies(i)
' Check if the baddy can move
If Not MoveBaddy(baddy) Then
' Baddy is trapped, remove it from the list
Console.WriteLine($"Removing baddy at index: {i}, Current count: {baddies.Count}") ' Log for debugging
baddies.RemoveAt(i) ' Remove by index
End If
Catch ex As ArgumentOutOfRangeException
Console.WriteLine($"Caught ArgumentOutOfRangeException! Index: {i}, Current count: {baddies.Count}. Message: {ex.Message}")
End Try
Next
picTest.Invalidate() ' Refresh the display to show updated baddy positions
End Sub
Private Function MoveBaddy(baddy As Baddy) As Boolean
Dim nextX As Integer = baddy.X
Dim nextY As Integer = baddy.Y
' Attempt to move in the current direction
Select Case baddy.CurrentDirection
Case "Right"
nextX += 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try down if right is blocked
nextX = baddy.X
nextY += 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try up if down is blocked
nextY = baddy.Y - 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Finally try left
nextX = baddy.X - 1
nextY = baddy.Y
baddy.CurrentDirection = "Left" ' Update direction
Else
baddy.CurrentDirection = "Up" ' Update direction
End If
Else
baddy.CurrentDirection = "Down" ' Update direction
End If
End If
Case "Down"
nextY += 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try left if down is blocked
nextY = baddy.Y
nextX -= 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try right if left is blocked
nextX = baddy.X + 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Finally try up
nextY = baddy.Y - 1
nextX = baddy.X
baddy.CurrentDirection = "Up" ' Update direction
Else
baddy.CurrentDirection = "Right" ' Update direction
End If
Else
baddy.CurrentDirection = "Left" ' Update direction
End If
End If
Case "Left"
nextX -= 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try up if left is blocked
nextX = baddy.X
nextY -= 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try down if up is blocked
nextY = baddy.Y + 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Finally try right
nextX = baddy.X + 1
nextY = baddy.Y
baddy.CurrentDirection = "Right" ' Update direction
Else
baddy.CurrentDirection = "Down" ' Update direction
End If
Else
baddy.CurrentDirection = "Up" ' Update direction
End If
End If
Case "Up"
nextY -= 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try right if up is blocked
nextY = baddy.Y
nextX += 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Try left if right is blocked
nextX = baddy.X - 1
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Finally try down
nextY = baddy.Y + 1
nextX = baddy.X
baddy.CurrentDirection = "Down" ' Update direction
Else
baddy.CurrentDirection = "Left" ' Update direction
End If
Else
baddy.CurrentDirection = "Right" ' Update direction
End If
End If
End Select
' Now perform the move if the next position is valid
If CanBaddyMoveTo(baddy, nextX, nextY) Then
baddy.X = nextX
baddy.Y = nextY
Return True ' Return true to indicate that the baddy is still active
Else
' If baddy cannot move, it might be trapped
If trapped(baddy) Then
Return False ' This indicates the baddy should be removed
End If
End If
Return True ' Return true to indicate that the baddy is still active
End Function
Private Function CanBaddyMoveTo(baddy As Baddy, newX As Integer, newY As Integer) As Boolean
' Check boundaries
If newX < 0 OrElse newX >= SQCOUNTX OrElse newY < 0 OrElse newY >= SQCOUNTY Then
Return False
End If
' Check for walls in the way
If newX > baddy.X Then
' Moving right
If verticalWalls(newX)(newY) Then
Return False
End If
ElseIf newX < baddy.X Then
' Moving left
If verticalWalls(newX + 1)(newY) Then
Return False
End If
End If
If newY > baddy.Y Then
' Moving down
If horizontalWalls(newX)(newY) Then
Return False
End If
ElseIf newY < baddy.Y Then
' Moving up
If horizontalWalls(newX)(newY + 1) Then
Return False
End If
End If
' Check for wall items (lasers and flippers)
If newX > baddy.X Then
' Moving right
If verticalWallItems(newX)(newY) IsNot Nothing Then
Return False
End If
ElseIf newX < baddy.X Then
' Moving left
If verticalWallItems(newX + 1)(newY) IsNot Nothing Then
Return False
End If
End If
If newY > baddy.Y Then
' Moving down
If horizontalWallItems(newX)(newY) IsNot Nothing Then
Return False
End If
ElseIf newY < baddy.Y Then
' Moving up
If horizontalWallItems(newX)(newY + 1) IsNot Nothing Then
Return False
End If
End If
' Check for other baddies occupying the new space
If baddies.Any(Function(b) b.X = newX AndAlso b.Y = newY) Then
Return False
End If
' Check if the new position is clear (no items or other obstacles)
If placedItems(newX)(newY) IsNot Nothing Then
Return False
End If
' If all checks passed, return true
Return True
End Function
Private Function trapped(baddy As Baddy) As Boolean
' Simple definition of trapped
Dim nextX As Integer = baddy.X
Dim nextY As Integer = baddy.Y
Select Case baddy.CurrentDirection
Case "Right"
nextX += 1
Case "Down"
nextY += 1
Case "Left"
nextX -= 1
Case "Up"
nextY -= 1
End Select
If Not CanBaddyMoveTo(baddy, nextX, nextY) Then
' Baddy is trapped
sfxManager.PlaySoundEffect("Explosion") ' Play explosion sound
' Remove the baddy from the list
baddies.Remove(baddy)
' Place a key where the baddy was trapped
placedItems(baddy.X)(baddy.Y) = "picKey"
' Start explosion animation
Dim explosionImage As Image = imageDictionary("picExplosion")
Dim startX As Integer = INDENT + baddy.X * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim startY As Integer = INDENT + baddy.Y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim animationDuration As Integer = 1000 ' 1 second animation
Dim explosionAnimation As New ItemAnimation(explosionImage, startX, startY, startX, startY, animationDuration)
itemAnimations.Add(explosionAnimation)
Return True
End If
Return False
End Function
' Stop the idle timer when a key is pressed
If idleTimer IsNot Nothing Then
idleTimer.Stop()
End If
End Sub
Private Sub frmGame_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
' Start the idle timer immediately when a key is released
idleTimer.Start()
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
lastDirection = "Left"
Case "Right"
deltaX = 1
lastDirection = "Right"
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
' Remove the starting point once the player moves
If placedItems(playerX)(playerY) <> "picBlockStopper1" AndAlso placedItems(playerX)(playerY) <> "picWarp" AndAlso placedItems(playerX)(playerY) <> "picWarp2" Then
placedItems(playerX)(playerY) = Nothing
End If
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
CheckForWarp()
Return True
ElseIf targetItem = "picBlock1" Then
Dim blockMoved As Boolean = AttemptPushBlock(newX, newY, deltaX, deltaY)
If blockMoved Then
' Remove the starting point once the player moves
If placedItems(playerX)(playerY) <> "picBlockStopper1" AndAlso placedItems(playerX)(playerY) <> "picWarp" AndAlso placedItems(playerX)(playerY) <> "picWarp2" Then
placedItems(playerX)(playerY) = Nothing
End If
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem = "picBlockStopper1" Then
' Do not remove the block stopper
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
CheckForWarp()
Return True
ElseIf targetItem = "picBall" Then
Dim ballMoved As Boolean = AttemptPushBall(newX, newY, deltaX, deltaY)
If ballMoved Then
' Remove the starting point once the player moves
If placedItems(playerX)(playerY) <> "picBlockStopper1" AndAlso placedItems(playerX)(playerY) <> "picWarp" AndAlso placedItems(playerX)(playerY) <> "picWarp2" Then
placedItems(playerX)(playerY) = Nothing
End If
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
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")
PlayRandomMoveSound() ' Play one of the move sounds randomly.
UpdateCoinLabel()
' Start coin animation
Dim coinImage As Image = imageDictionary("picCoin")
Dim startX As Integer = INDENT + newX * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim startY As Integer = INDENT + newY * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim endX As Integer = lblCoinCount.Bounds.Left + lblCoinCount.Bounds.Width \ 2 - coinImage.Width \ 2
Dim endY As Integer = lblCoinCount.Bounds.Top + lblCoinCount.Bounds.Height \ 2 - coinImage.Height \ 2
Dim animationDuration As Integer = 1000 ' 1 second animation
Dim coinAnimation As New ItemAnimation(coinImage, startX, startY, endX, endY, animationDuration)
itemAnimations.Add(coinAnimation)
' Remove the starting point once the player moves
If placedItems(playerX)(playerY) <> "picBlockStopper1" AndAlso placedItems(playerX)(playerY) <> "picWarp" AndAlso placedItems(playerX)(playerY) <> "picWarp2" Then
placedItems(playerX)(playerY) = Nothing
End If
CheckForWarp()
Return True
ElseIf targetItem = "picKey" Then
collectedKeys += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key")
PlayRandomMoveSound() ' Play one of the move sounds randomly.
UpdateKeyLabel()
' Start key animation
Dim keyImage As Image = imageDictionary("picKey")
Dim startX As Integer = INDENT + newX * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim startY As Integer = INDENT + newY * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim endX As Integer = lblKeyCount.Bounds.Left + lblKeyCount.Bounds.Width \ 2 - keyImage.Width \ 2
Dim endY As Integer = lblKeyCount.Bounds.Top + lblKeyCount.Bounds.Height \ 2 - keyImage.Height \ 2
Dim animationDuration As Integer = 1000 ' 1 second animation
Dim keyAnimation As New ItemAnimation(keyImage, startX, startY, endX, endY, animationDuration)
itemAnimations.Add(keyAnimation)
' Remove the starting point once the player moves
If placedItems(playerX)(playerY) <> "picBlockStopper1" AndAlso placedItems(playerX)(playerY) <> "picWarp" AndAlso placedItems(playerX)(playerY) <> "picWarp2" Then
placedItems(playerX)(playerY) = Nothing
End If
CheckForWarp()
Return True
ElseIf targetItem = "picGate" Then
If collectedKeys = totalKeys Then
UnlockDoor(newX, newY)
PlayRandomMoveSound() ' Play one of the move sounds randomly.
Return False
Else
Return False
End If
ElseIf targetItem = "picFinish" Then
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
GameWon()
Return True
ElseIf targetItem = "picWarp" Then
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
HandleWarp("picWarp")
Return True
ElseIf targetItem = "picWarp2" Then
playerX = newX
playerY = newY
PlayRandomMoveSound() ' Play one of the move sounds randomly.
HandleWarp("picWarp2")
Return True
Else
Return False
End If
' Remove the starting point once the player moves, if applicable
If placedItems(playerX)(playerY) <> "picBlockStopper1" AndAlso placedItems(playerX)(playerY) <> "picWarp" AndAlso placedItems(playerX)(playerY) <> "picWarp2" Then
placedItems(playerX)(playerY) = Nothing
End If
End Function
Private Sub PlayRandomMoveSound()
Dim moveSounds As String() = {"Move 1", "Move 2", "Move 3"}
Dim randomIndex As Integer = New Random().Next(moveSounds.Length)
Dim selectedSound As String = moveSounds(randomIndex)
sfxManager.PlaySoundEffect(selectedSound)
End Sub
Private Sub UnlockDoor(doorX As Integer, doorY As Integer)
' Store the door position
Me.doorX = doorX
Me.doorY = doorY
' Start the door animation timer
If doorAnimationTimer Is Nothing Then
doorAnimationTimer = New Timer()
AddHandler doorAnimationTimer.Tick, AddressOf OnDoorAnimationTick
doorAnimationTimer.Interval = 50 ' Adjust the interval as needed
End If
doorAnimationTimer.Start()
' Record the start time of the door animation
doorAnimationStartTime = DateTime.Now
' Play the door open sound effect
sfxManager.PlaySoundEffect("Door Open")
End Sub
Private Sub OnDoorAnimationTick(sender As Object, e As EventArgs)
' Update the door animation frame
Dim doorImage As Image = imageDictionary("picGate")
ImageAnimator.UpdateFrames(doorImage)
' Check if one second has passed since the animation started
If (DateTime.Now - doorAnimationStartTime).TotalSeconds >= 1 Then
' Stop the timer
doorAnimationTimer.Stop()
' Remove the door from the grid
placedItems(doorX)(doorY) = Nothing
' No need to invalidate here, the redraw timer will handle it
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
' No need to invalidate here, the redraw timer will handle it
End Sub
Private Function IsObjectOnFlipper(movingObject As MovingObject) As Boolean
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
' Check right flipper
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
Debug.WriteLine($"Object on Flipper1 at ({x + 1}, {y})")
Return True
End If
End If
' Check left flipper
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Debug.WriteLine($"Object on Flipper2 at ({x}, {y})")
Return True
End If
End If
' Check down flipper
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
Debug.WriteLine($"Object on Flipper3 at ({x}, {y + 1})")
Return True
End If
End If
' Check up flipper
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Debug.WriteLine($"Object on Flipper4 at ({x}, {y})")
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
' Check right flipper
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
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check left flipper
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check down flipper
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
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check up flipper
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
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)
' Check for baddies at the new position
If baddies.Any(Function(b) b.X = blockNewX AndAlso b.Y = blockNewY) Then
Return False
End If
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
' Check for walls and lasers based on the direction of movement
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
' Check for moving objects at the new position
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 UpdateCoinLabel()
lblCoinCount.Text = $"{CollectedCoins} of {totalCoins}"
End Sub
Private Sub UpdateKeyLabel()
If totalKeys > 0 Then
lblKeyCount.Text = $"{collectedKeys} of {totalKeys}"
Else
lblKeyCount.Text = "X"
End If
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
' Draw the gradient background if useGradient is true
If useGradient Then
DrawGradientBackground(e.Graphics)
End If
CalculateSquareSizes(picTest.ClientSize.Width, picTest.ClientSize.Height)
e.Graphics.SmoothingMode = SmoothingMode.None
DrawGrid(e.Graphics)
' Draw item animations
For Each itemAnimation In itemAnimations
Dim destRect As New Rectangle(itemAnimation.CurrentX, itemAnimation.CurrentY, itemAnimation.ItemImage.Width, itemAnimation.ItemImage.Height)
e.Graphics.DrawImage(itemAnimation.ItemImage, destRect)
Next
'' Draw baddies
'For Each baddy In baddies
' Dim img As Image = imageDictionary("picBaddy1")
' Dim xPos As Integer = INDENT + baddy.X * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
' Dim yPos As Integer = INDENT + baddy.Y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
' Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
' e.Graphics.DrawImage(img, destRect)
'Next
End Sub
Private Sub InvalidateMovingObjects()
For Each movingObject In movingObjects
Dim rect As New Rectangle(
INDENT + movingObject.X * (SQSizeX + WALL_THICKNESS),
INDENT + movingObject.Y * (SQSizeY + WALL_THICKNESS),
SQSizeX + WALL_THICKNESS,
SQSizeY + WALL_THICKNESS
)
picTest.Invalidate(rect)
Next
End Sub
Private Sub DrawHatchStyleBackground(g As Graphics)
Dim xOrigin As Integer = INDENT
Dim yOrigin As Integer = INDENT
Dim gridWidth As Integer = SQCOUNTX * (SQSizeX + WALL_THICKNESS)
Dim gridHeight As Integer = SQCOUNTY * (SQSizeY + WALL_THICKNESS)
' Calculate the hatch style rectangle for the entire grid
Dim hatchRect As New Rectangle(xOrigin, yOrigin, gridWidth, gridHeight)
' Draw the hatch style background
Using brush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(brush, hatchRect)
End Using
End Sub
Private Sub DrawGradientBackground(g As Graphics)
Dim xOrigin As Integer = INDENT
Dim yOrigin As Integer = INDENT
Dim gridWidth As Integer = SQCOUNTX * (SQSizeX + WALL_THICKNESS)
Dim gridHeight As Integer = SQCOUNTY * (SQSizeY + WALL_THICKNESS)
' Calculate the gradient rectangle for the entire grid
Dim gradientRect As New Rectangle(xOrigin, yOrigin, gridWidth, gridHeight)
' Draw the gradient background
Using brush As New LinearGradientBrush(gradientRect, floorsColor1, floorsColor2, LinearGradientMode.Vertical)
g.FillRectangle(brush, gradientRect)
End Using
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
' Draw the gradient background if useGradient is true
If useGradient Then
DrawGradientBackground(g)
End If
' Draw floor squares with the chosen style only if not using gradient
If Not useGradient Then
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
End If
' Draw wall intersections
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
' Draw vertical walls or floor
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
' Draw wall
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
ElseIf Not useGradient Then
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
' Draw horizontal walls or floor
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
' Draw wall
Using wallBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(wallBrush, wallRect)
End Using
ElseIf Not useGradient Then
Using floorBrush As New HatchBrush(floorsHatchStyle, floorsColor1, floorsColor2)
g.FillRectangle(floorBrush, wallRect)
End Using
End If
End If
Next
Next
' Draw edge squares with the wall hatch style and colors
For x As Integer = 0 To SQCOUNTX - 1
For y As Integer = 0 To SQCOUNTY - 1
If floorsUseEdgeStyle IsNot Nothing AndAlso floorsUseEdgeStyle.Length > x AndAlso
floorsUseEdgeStyle(x) IsNot Nothing AndAlso floorsUseEdgeStyle(x).Length > y AndAlso
floorsUseEdgeStyle(x)(y) Then
Dim edgeRect As New Rectangle(
xOrigin + x * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2,
yOrigin + y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2,
SQSizeX,
SQSizeY
)
Using edgeBrush As New HatchBrush(wallsHatchStyle, wallsColor1, wallsColor2)
g.FillRectangle(edgeBrush, edgeRect)
End Using
End If
Next
Next
' Draw items
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 = Nothing
If imageKey = "picGate" Then
If doorAnimationTimer IsNot Nothing AndAlso doorAnimationTimer.Enabled Then
img = imageDictionary(imageKey) ' Use the animated door image
Else
img = doorImage ' Use the static door image
End If
Else
img = imageDictionary(imageKey)
End If
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)
' Draw the number of remaining keys on the door
If imageKey = "picGate" Then
Dim remainingKeys As Integer = totalKeys - collectedKeys
Dim font As New Font("Arial", 12, FontStyle.Bold)
Dim textSize As SizeF = g.MeasureString(remainingKeys.ToString(), font)
Dim textX As Integer = xPos + (SQSizeX - textSize.Width) \ 2
Dim textY As Integer = yPos + (SQSizeY - textSize.Height) \ 2
g.DrawString(remainingKeys.ToString(), font, Brushes.White, textX, textY)
End If
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
' Draw baddies
For Each baddy In baddies
Dim img As Image = imageDictionary(baddy.ImageKey)
Dim xPos As Integer = INDENT + baddy.X * (SQSizeX + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim yPos As Integer = INDENT + baddy.Y * (SQSizeY + WALL_THICKNESS) + WALL_THICKNESS \ 2
Dim destRect As New Rectangle(xPos, yPos, SQSizeX, SQSizeY)
g.DrawImage(img, destRect)
Next
DrawPlayer(g)
End Sub
Private Sub DrawPlayer(g As Graphics)
Dim img As Image
Select Case lastDirection
Case "Left"
img = imageDictionary("picStartLeft")
Case "Right"
img = imageDictionary("picStartRight")
Case Else
img = imageDictionary("picStart")
End Select
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 OnRedrawTick(sender As Object, e As EventArgs)
picTest.Invalidate()
End Sub
Private Sub OnIdleTick(sender As Object, e As EventArgs)
lastDirection = "Idle"
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)
CountCoinsInGrid(roomData) ' Count the total number of coins available
' Invalidate the picTest control to redraw the grid
picTest.Invalidate()
Catch ex As Exception
MessageBox.Show("Error loading room: " & ex.ToString())
End Try
End Sub
Private Sub CountCoinsInGrid(roomData As RoomData)
totalCoins = 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 = "picCoin" Then
totalCoins += 1
End If
Next
End If
Next
UpdateCoinLabel()
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
UpdateKeyLabel()
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()
' Ensure the useGradient property is restored
useGradient = roomData.useGradient
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
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
Private Sub OnItemAnimationTick(sender As Object, e As EventArgs)
For i As Integer = itemAnimations.Count - 1 To 0 Step -1
Dim itemAnimation = itemAnimations(i)
itemAnimation.UpdatePosition()
If itemAnimation.IsAnimationComplete() Then
itemAnimations.RemoveAt(i)
End If
Next
' No need to invalidate here, the redraw timer will handle it
End Sub
Private Sub btnRetry_Click(sender As Object, e As EventArgs) Handles btnRetry.Click
RestartLevel()
End Sub
Private Sub RestartLevel()
' Reload the room data to reset the placedItems array
LoadRoomData()
' Reset player position
FindPlayerStartPosition()
' Reset collected items
CollectedCoins = 0
collectedKeys = 0
UpdateCoinLabel()
UpdateKeyLabel()
' Reset moving objects
movingObjects.Clear()
AddObjectsOnFlippersToMovingObjects()
' Reset animations
itemAnimations.Clear()
End Sub
Private Sub btnMinimize_Click(sender As Object, e As EventArgs) Handles btnMinimize.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Protected Overrides ReadOnly Property CreateParams() As CreateParams
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or &H2000000 ' WS_EX_COMPOSITED
Return cp
End Get
End Property
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
' Check right flipper
If x + 1 < verticalWallItems.Length AndAlso verticalWallItems(x + 1)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check left flipper
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check down flipper
If y + 1 < horizontalWallItems(x).Length AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check up flipper
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Explanation of Changes:
Added Boundary Checks: Each check now includes boundary conditions to prevent accessing invalid array indices—essential when dealing with array lengths derived from wall counts versus square counts.
Improved Debug and Logging: Ensure logging remains functional to aid in monitoring when a flipper is detected.
Final Notes:
Make sure your implementation accommodates both sets of parameters you're using for flippers. With proper boundary handling, you should avoid instances of exceptions caused by attempting to access array indices that do not exist.
After implementing these changes, test the application again to see if the flippers now get detected properly when scenarios arise with edge boundaries.
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Check right flipper
If x + 1 < verticalWallItems.Length AndAlso verticalWallItems(x + 1) IsNot Nothing Then
Debug.WriteLine($"Checking right flipper at ({x + 1}, {y})")
Dim item As String = verticalWallItems(x + 1)(y)
If item = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Right flipper check exceeded bounds at ({x + 1}, {y})")
End If
' Check left flipper
If x > 0 AndAlso verticalWallItems(x)(y) IsNot Nothing Then
Debug.WriteLine($"Checking left flipper at ({x}, {y})")
Dim item As String = verticalWallItems(x)(y)
If item = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Left flipper check skipped at ({x}, {y})")
End If
' Check down flipper
If y + 1 < horizontalWallItems(x).Length AndAlso horizontalWallItems(x)(y + 1) IsNot Nothing Then
Debug.WriteLine($"Checking down flipper at ({x}, {y + 1})")
Dim item As String = horizontalWallItems(x)(y + 1)
If item = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Down flipper check exceeded bounds at ({x}, {y + 1})")
End If
' Check up flipper
If y > 0 AndAlso horizontalWallItems(x)(y) IsNot Nothing Then
Debug.WriteLine($"Checking up flipper at ({x}, {y})")
Dim item As String = horizontalWallItems(x)(y)
If item = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Up flipper check skipped at ({x}, {y})")
End If
End Sub
Additional Considerations
Use Debug Statements: Any logging statements written to show your logic's path will aid in understanding what's being executed and why certain paths might not yield the expected results.
Check Parameters Passed: Be vigilant about the parameters passed to any methods. Sometimes, unexpected behavior results from unanticipated state changes or incorrect checks.
Audio Handling Exceptions: Since the exception mentions NAudio, ensure there's no other code attempting to play sounds without ensuring that the sound effect actually exists or is correctly referenced.
Testing
After adding comprehensive logging, rerun your tests to capture any relevant outputs. The debug messages will guide you in identifying where the logic might be failing or what inputs might cause issues.
If everything works as expected but exceptions persist, consider isolating sound playback functionality, or examine if other parts of your code are interfering with expected behavior (like multiple accesses to shared resources).
Please update me with new findings or additional outputs generated after incorporating more debugging metrics!
vb
Dim sound = soundEffectsDict.TryGetValue(soundName, sound)
If sound IsNot Nothing Then
sound.Play()
Else
Debug.WriteLine($"Sound effect {soundName} not found.")
End If
Try-Catch Block:
Wrap your audio playback statements in a Try-Catch block to catch and log exceptions that are thrown during sound effect playback without allowing them to propagate uncaught.
Example Code Enhancements
Here are some enhancements on how to play sound safely within your SFXManager class:
vb
Public Sub PlaySoundEffect(soundName As String)
Try
If soundEffectsDict.ContainsKey(soundName) Then
Dim sound As SoundEffect = soundEffectsDict(soundName)
If sound IsNot Nothing Then
sound.Play()
Else
Debug.WriteLine($"Sound effect found in dictionary, but is null: {soundName}")
End If
Else
Debug.WriteLine($"Sound effect not found: {soundName}")
End If
Catch ex As Exception
Debug.WriteLine($"Error playing sound effect '{soundName}': {ex.Message}")
End Try
End Sub
Conclusion
By adding robust checks, logging, and ensuring your sound management is failure-safe, you should be able to diagnose and potentially fix the exceptions you are encountering. If the problems persist, you might want to explore further into the specifics of what sounds are being played and whether or not their corresponding files exist and are accessible.
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Adjust flipper checks based on wall indexing
' Check the right flipper
If (x + 1 < verticalWallItems.Length) AndAlso (y < verticalWallItems(x + 1).Length) Then
Dim rightFlipperItem As String = verticalWallItems(x + 1)(y)
If rightFlipperItem = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1 ' moving towards left
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Right flipper check skipped at ({x + 1}, {y})")
End If
' Check the left flipper
If (x > 0) AndAlso (y < verticalWallItems(x).Length) Then
Dim leftFlipperItem As String = verticalWallItems(x)(y)
If leftFlipperItem = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1 ' moving towards right
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Left flipper check skipped at ({x}, {y})")
End If
' Check down flipper
If (y + 1 < horizontalWallItems(x).Length) AndAlso (x < horizontalWallItems.Length) Then
Dim downFlipperItem As String = horizontalWallItems(x)(y + 1)
If downFlipperItem = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1 ' moving towards up
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Down flipper check skipped at ({x}, {y + 1})")
End If
' Check up flipper
If (y > 0) AndAlso (x < horizontalWallItems.Length) Then
Dim upFlipperItem As String = horizontalWallItems(x)(y)
If upFlipperItem = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1 ' moving downwards
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Up flipper check skipped at ({x}, {y})")
End If
End Sub
Summary of Changes:
Boundary Validation: Each check now ensures that it does not exceed the bounds of the respective wall item arrays.
Detailed Logs: Added more log statements to assist in future troubleshooting and understanding which checks were triggered.
Corrected Logic: The checks against the arrays are adjusted to better suit their intended purpose.
Conclusion
Test this revised flipper detection logic to see if it resolves the discrepancies you are experiencing. The changes should help ensure the flippers are activated correctly based on the position of the moving object. Let me know if the issue persists, and we can delve deeper!
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Check right flipper
If (x + 1 < verticalWallItems.Length) Then
If (y >= 0 AndAlso y < verticalWallItems(x + 1).Length AndAlso verticalWallItems(x + 1)(y) = "picFlipper1") Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check left flipper
If (x > 0) Then
If (y >= 0 AndAlso y < verticalWallItems(x).Length AndAlso verticalWallItems(x)(y) = "picFlipper2") Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check down flipper
If (y + 1 < horizontalWallItems(x).Length) Then
If (y + 1 >= 0 AndAlso x < horizontalWallItems.Length AndAlso horizontalWallItems(x)(y + 1) = "picFlipper3") Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check up flipper
If (y > 0) Then
If (y >= 0 AndAlso x < horizontalWallItems.Length AndAlso horizontalWallItems(x)(y) = "picFlipper4") Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Key Changes:
Increased Robustness: Each flipper check validates against the appropriate array lengths and applies conditions carefully.
Special Cases: Checks for the corresponding indices before accessing to avoid out-of-bounds errors.
Logging: Enhanced debug logging should help ensure that you can trace any additional missed checks.
Conclusion
Implement this revised logic, and run your tests again. Look for logs indicating that a flipper should have been detected but didn’t, as well as checks regarding the specific positions you know are supposed to trigger those flippers (including edge cases). Doing this will help narrow down if the correct items are being checked in your arrays. Let me know how it goes!
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Check right flipper for vertical walls
If (x + 1 < verticalWallItems.Length) AndAlso (y >= 0 AndAlso y < verticalWallItems(x + 1).Length) Then
If verticalWallItems(x + 1)(y) = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check left flipper
If (x > 0) AndAlso (y >= 0 AndAlso y < verticalWallItems(x).Length) Then
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check down flipper for horizontal walls
If (y + 1 < horizontalWallItems(x).Length) AndAlso (x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y + 1) = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Check up flipper
If (y > 0) AndAlso (x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Key Adjustments:
Bounding Conditions: Each If statement checks not only for the necessary wall index but also that the position does fit the wall items in the array.
Clear Logging: Enhanced log statements should help to better visualize where checks succeed and where they might skip.
Consistency: By maintaining consistent checks between the indices of square and wall items, this code aims to avoid any logical inconsistencies.
Testing Again
Run the modified implementation to see if it resolves any inconsistencies in functionality at the border flipper conditions. Keep an eye on your logs, as they should provide insight into which checks are being bypassed and why.
Let me know the results, and we will make further adjustments if needed!
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
Debug.WriteLine($"Vertical wall array length: {verticalWallItems.Length}, Horizontal wall array length: {horizontalWallItems.Length}")
' Check right flipper
If (x + 1 < verticalWallItems.Length) Then
If (y >= 0 AndAlso y < verticalWallItems(x + 1).Length) Then
Debug.WriteLine($"Checking right flipper at ({x + 1}, {y}) - Value: {verticalWallItems(x + 1)(y)}")
If verticalWallItems(x + 1)(y) = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Right flipper check skipped - Out of bounds at ({x + 1}, {y})")
End If
End If
' Check left flipper
If (x > 0) Then
If (y >= 0 AndAlso y < verticalWallItems(x).Length) Then
Debug.WriteLine($"Checking left flipper at ({x}, {y}) - Value: {verticalWallItems(x)(y)}")
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
Else
Debug.WriteLine($"Left flipper check skipped - Out of bounds at ({x}, {y})")
End If
End If
' Check down flipper
If (y + 1 < horizontalWallItems(x).Length) Then
If (x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking down flipper at ({x}, {y + 1}) - Value: {horizontalWallItems(x)(y + 1)}")
If horizontalWallItems(x)(y + 1) = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
Else
Debug.WriteLine($"Down flipper check skipped - Out of bounds at ({x}, {y + 1})")
End If
' Check up flipper
If (y > 0) Then
If (x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking up flipper at ({x}, {y}) - Value: {horizontalWallItems(x)(y)}")
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
Else
Debug.WriteLine($"Up flipper check skipped - Out of bounds at ({x}, {y})")
End If
End Sub
Additional Suggestions:
Inspect Array Values: Pay special attention to the debug output showing the values being checked (Value: {horizontalWallItems(x)(y)}). This will help confirm that you are indeed looking at the correct items.
Wall Boundaries: Ensure that 0, 5 for the vertical wall is indeed a valid index in your verticalWallItems array and that there is no discrepancy in the initialization of your walls.
Summary
Run the updated logic and inspect the debug output closely. With these detailed logs, you should gain insight into whether the indices are correctly hitting the positions where flippers are supposed to be placed. Let’s see if this version captures the flippers as expected!
Debug.WriteLine("Vertical Wall Items:")
For i As Integer = 0 To verticalWallItems.Length - 1
Debug.WriteLine($"VerticalWallItems[{i}]: {String.Join(", ", verticalWallItems(i))}")
Next
Debug.WriteLine("Horizontal Wall Items:")
For i As Integer = 0 To horizontalWallItems.Length - 1
Debug.WriteLine($"HorizontalWallItems[{i}]: {String.Join(", ", horizontalWallItems(i))}")
Next
Example Adjustment in Flipper Check Logic
For clarification, here’s how you might want to structure the flipper checking logic with additional sanity checks:
vb
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Right Flipper Check
If (x + 1 < verticalWallItems.Length) Then
If (y >= 0 AndAlso y < verticalWallItems(x + 1).Length) Then
Debug.WriteLine($"Checking right flipper at ({x + 1}, {y}) - Value: {verticalWallItems(x + 1)(y)}")
If verticalWallItems(x + 1)(y) = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
End If
Else
Debug.WriteLine($"Skip right flipper check - Out of bounds.")
End If
End If
' Left Flipper Check
If (x > 0) Then
If (y >= 0 AndAlso y < verticalWallItems(x).Length) Then
Debug.WriteLine($"Checking left flipper at ({x}, {y}) - Value: {verticalWallItems(x)(y)}")
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
End If
Else
Debug.WriteLine($"Skip left flipper check - Out of bounds.")
End If
End If
' Down Flipper Check
If (y + 1 < horizontalWallItems(x).Length) Then
If (x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking down flipper at ({x}, {y + 1}) - Value: {horizontalWallItems(x)(y + 1)}")
If horizontalWallItems(x)(y + 1) = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
End If
End If
Else
Debug.WriteLine($"Skip down flipper check - Out of bounds.")
End If
' Up Flipper Check
If (y > 0) Then
If (x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking up flipper at ({x}, {y}) - Value: {horizontalWallItems(x)(y)}")
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
End If
End If
Else
Debug.WriteLine($"Skip up flipper check - Out of bounds.")
End If
End Sub
Final Notes
Please make sure to verify your array content after initializing levels to ensure the items are properly assigned.
Run this updated code with enhanced debugging to see what values are present in wall arrays and how they correlate with your expectations with flippers.
If you still have difficulty detecting the flippers, provide more details on how the walls are initialized in relation to your level or room data, and we will continue troubleshooting from there!
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Right Flipper Check
If (x + 1 < verticalWallItems.Length) Then
If (y >= 0 AndAlso y < verticalWallItems(x + 1).Length) Then
If verticalWallItems(x + 1)(y) = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1 ' Flipper pushes left
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
PushBlock(x + 1, y) ' Implement a method to push block
End If
End If
End If
' Left Flipper Check
If (x > 0) Then
If (y >= 0 AndAlso y < verticalWallItems(x).Length) Then
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1 ' Flipper pushes right
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
PushBlock(x - 1, y) ' Implement a method to push block
End If
End If
End If
' Down Flipper Check
If (y + 1 < horizontalWallItems(x).Length) AndAlso (x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y + 1) = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1 ' Flipper pushes up
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
PushBlock(x, y + 1) ' Implement a method to push block
End If
End If
' Up Flipper Check
If (y > 0) Then
If (x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1 ' Flipper pushes down
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
PushBlock(x, y - 1) ' Implement a method to push block
End If
End If
End If
End Sub
Private Sub PushBlock(blockX As Integer, blockY As Integer)
' Check if there is a movable block at (blockX, blockY)
If placedItems(blockX)(blockY) = "picBlock1" Then
' Logic to move the block
Dim newPos As Point = GetNewPositionBasedOnFlipper(blockX, blockY) ' Determine new position after pushing
If CanBlockMoveTo(blockX, blockY, newPos.X - blockX, newPos.Y - blockY) Then
placedItems(blockX)(blockY) = Nothing ' Remove the block from the old position
placedItems(newPos.X)(newPos.Y) = "picBlock1" ' Set the new position
sfxManager.PlaySoundEffect("Push Block") ' Play block push sound
End If
End If
End Sub
Private Function GetNewPositionBasedOnFlipper(blockX As Integer, blockY As Integer) As Point
' Implement logic to check which direction the flipper is set to push blocks
' This should return the new coordinates after pushing
' e.g. For right flipper, add to blockX; for left, subtract
Return New Point(blockX, blockY) ' Adjust based on the flipper action
End Function
Explanation
Flipper Activation:
When a flipper is detected, it will now attempt to push blocks in the appropriate direction.
Push Block Functionality:
The PushBlock method implements checking if a block exists and applies movement logic accordingly.
Block Movement Logic:
The placeholders GetNewPositionBasedOnFlipper and checks for movement ensure proper gameplay mechanics.
Final Steps
Integrate this code and run your game to see if the blocks are now being pushed correctly when the flippers are engaged.
Check thoroughly to see if flippers at all designated positions (especially the border cases) now push items as expected.
If you still encounter issues with the pushing mechanism, please provide detailed behavior descriptions or specific scenarios, and we can further refine our approach!
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Right Flipper Check
If (x + 1 < verticalWallItems.Length) Then
If (y >= 0 AndAlso y < verticalWallItems(x + 1).Length) Then
Debug.WriteLine($"Checking right flipper at ({x + 1}, {y}) - Value: {verticalWallItems(x + 1)(y)}")
If verticalWallItems(x + 1)(y) = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End If
' Left Flipper Check
If (x > 0) Then
If (y >= 0 AndAlso y < verticalWallItems(x).Length) Then
Debug.WriteLine($"Checking left flipper at ({x}, {y}) - Value: {verticalWallItems(x)(y)}")
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End If
' Down Flipper Check
If (y + 1 < horizontalWallItems(x).Length) Then
If (x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking down flipper at ({x}, {y + 1}) - Value: {horizontalWallItems(x)(y + 1)}")
If horizontalWallItems(x)(y + 1) = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End If
' Up Flipper Check
If (y > 0) Then
If (x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking up flipper at ({x}, {y}) - Value: {horizontalWallItems(x)(y)}")
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End If
' Explicitly check for left and top borders
' Top Border Check - Directly assess horizontal wall for possible flippers
If (y = 0 AndAlso x < horizontalWallItems.Length) Then
Debug.WriteLine($"Checking flipper on top border at ({x}, {y}) - Value: {horizontalWallItems(x)(y)}")
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at top border ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Left Border Check - Assess leftmost vertical wall for flippers
If (x = 0 AndAlso y < verticalWallItems.Length) Then
Debug.WriteLine($"Checking flipper on left border at ({x}, {y}) - Value: {verticalWallItems(x)(y)}")
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at left border ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Key Modifications:
Specific Border Checks Added: Two new checks are added for the left and top borders:
The top border checks the first row of horizontal walls for a possible flipper.
The left border checks the first column of vertical walls for a possible flipper.
Retaining Previous Logic: All previous checks remain. This does not disrupt the existing functioning logic but simply adds more checks at the borders.
Conclusion
By implementing these additional border checks, we should ensure flippers placed on the left and at the top of the game grid are acknowledged correctly. Test this implementation to verify that flippers in border positions now work as expected without slipping through the checks. Let me know how this adjustment performs!
Private Sub CheckForFlipper(movingObject As MovingObject)
Dim x As Integer = movingObject.X
Dim y As Integer = movingObject.Y
Debug.WriteLine($"Checking flipper for moving object at ({x}, {y})")
' Right Flipper Check
If (x + 1 < verticalWallItems.Length) AndAlso (y >= 0 AndAlso y < verticalWallItems(x + 1).Length) Then
If verticalWallItems(x + 1)(y) = "picFlipper1" Then
Debug.WriteLine($"Flipper1 detected at ({x + 1}, {y})")
movingObject.DeltaX = -1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Left Flipper Check
If (x > 0) AndAlso (y >= 0 AndAlso y < verticalWallItems(x).Length) Then
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Down Flipper Check
If (y + 1 < horizontalWallItems(x).Length) AndAlso (x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y + 1) = "picFlipper3" Then
Debug.WriteLine($"Flipper3 detected at ({x}, {y + 1})")
movingObject.DeltaX = 0
movingObject.DeltaY = -1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Up Flipper Check
If (y > 0) AndAlso (x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
' Border Checks for Left and Top
If (y = 0 AndAlso x < horizontalWallItems.Length) Then
If horizontalWallItems(x)(y) = "picFlipper4" Then
Debug.WriteLine($"Flipper4 detected at top border ({x}, {y})")
movingObject.DeltaX = 0
movingObject.DeltaY = 1
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
If (x = 0 AndAlso y < verticalWallItems.Length) Then
If verticalWallItems(x)(y) = "picFlipper2" Then
Debug.WriteLine($"Flipper2 detected at left border ({x}, {y})")
movingObject.DeltaX = 1
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
End If
End If
End Sub
Summary of Changes:
Removed unnecessary comments that were self-explanatory or repetitive.
Retained essential debug logging to help diagnose any future issues while keeping the codebase streamlined.
Next Steps
Compile and test this cleaned-up version to ensure that all functionality is still intact. If it works as expected, you’re all set! If you need further adjustments or have other areas to tidy up, just let me know!