Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

Imports System.IO Imports System.Text.Json Imports System.Text.Json.Serialization…

  1. User

    Imports System.IO Imports System.Text.Json Imports System.Text.Json.Serialization Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.ComponentModel Imports System.Resources Imports System.Drawing.Imaging Imports System.Reflection

    Public Class frmGame #Region " Variables and Classes " Private baddyMovementTimer As Timer Private triggers As New List(Of Triggers)() 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
    

    #End Region

    #Region " Initialization " Public Sub New() InitializeComponent() resourceManager = New ResourceManager("Enigma.frmGame", GetType(frmGame).Assembly) InitializeSoundEffects()

        ' 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("picBlockSwitch") = Image.FromFile(Path.Combine(ImagesFolder, "BlockSwitch.png"))
            imageDictionary("picBlockSwitch2") = Image.FromFile(Path.Combine(ImagesFolder, "BlockSwitch2.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("picLaser1") = Image.FromFile(Path.Combine(ImagesFolder, "Laser1.gif"))
            imageDictionary("picLaser2") = Image.FromFile(Path.Combine(ImagesFolder, "Laser2.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() = {
    "picLaser1", "picLaser2", "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() ' Load any 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
    

    #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 End If End If Next Next 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
                    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
    

    #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

        ' 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()
            CheckTriggers() ' Check triggers after movement
            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()
                CheckTriggers() ' Check triggers after movement
                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()
            CheckTriggers() ' Check triggers after movement
            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()
                CheckTriggers() ' Check triggers after movement
                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()
            CheckTriggers() ' Check triggers after movement
            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()
            CheckTriggers() ' Check triggers after movement
            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
        ElseIf targetItem = "picBlockSwitch" OrElse targetItem = "picBlockSwitch2" Then
            ' Handle BlockSwitch logic
            HandleBlockSwitch(newX, newY, targetItem)
            playerX = newX
            playerY = newY
            PlayRandomMoveSound() ' Play one of the move sounds randomly.
            CheckForWarp()
            CheckTriggers() ' Check triggers after movement
            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 HandleBlockSwitch(x As Integer, y As Integer, switchType As String)
        ' Implement the logic for handling BlockSwitch
        ' For example, you can toggle walls, open doors, etc.
        If switchType = "picBlockSwitch" Then
            ' Example: Toggle vertical walls
            If x > 0 AndAlso verticalWalls(x - 1)(y) Then
                verticalWalls(x - 1)(y) = False
            ElseIf x < SQCOUNTX - 1 AndAlso verticalWalls(x + 1)(y) Then
                verticalWalls(x + 1)(y) = False
            End If
        ElseIf switchType = "picBlockSwitch2" Then
            ' Example: Toggle horizontal walls
            If y > 0 AndAlso horizontalWalls(x)(y - 1) Then
                horizontalWalls(x)(y - 1) = False
            ElseIf y < SQCOUNTY - 1 AndAlso horizontalWalls(x)(y + 1) Then
                horizontalWalls(x)(y + 1) = False
            End If
        End If
        ' Add more logic as needed
    End Sub
    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
        ElseIf blockTargetItem = "picBlockSwitch" OrElse blockTargetItem = "picBlockSwitch2" Then
            ' Handle BlockSwitch logic
            HandleBlockSwitch(blockNewX, blockNewY, blockTargetItem)
            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 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
    
        CheckTriggers() ' Check triggers after moving objects
    End Sub
    Private Function IsObjectOnFlipper(movingObject As MovingObject) As Boolean
        Dim x As Integer = movingObject.X
        Dim y As Integer = movingObject.Y
    
        ' Left Flipper Check (Flipper2)
        If x >= 0 AndAlso x < verticalWallItems.Length AndAlso
       y >= 0 AndAlso y < verticalWallItems(x).Length AndAlso
       verticalWallItems(x)(y) = "picFlipper2" Then
            Return True
        End If
    
        ' Right Flipper Check (Flipper1)
        If x + 1 < verticalWallItems.Length AndAlso
       y >= 0 AndAlso y < verticalWallItems(x + 1).Length AndAlso
       verticalWallItems(x + 1)(y) = "picFlipper1" Then
            Return True
        End If
    
        ' Up Flipper Check (Flipper4)
        If x >= 0 AndAlso x < horizontalWallItems.Length AndAlso
       y >= 0 AndAlso y < horizontalWallItems(x).Length AndAlso
       horizontalWallItems(x)(y) = "picFlipper4" Then
            Return True
        End If
    
        ' Down Flipper Check (Flipper3)
        If x >= 0 AndAlso x < horizontalWallItems.Length AndAlso
       y + 1 < horizontalWallItems(x).Length AndAlso
       horizontalWallItems(x)(y + 1) = "picFlipper3" Then
            Return True
        End If
    
        Return False
    End Function
    Private Sub CheckForFlipper(movingObject As MovingObject)
        Dim x As Integer = movingObject.X
        Dim y As Integer = movingObject.Y
    
        ' Left Flipper Check (Flipper2)
        If x >= 0 AndAlso x < verticalWallItems.Length AndAlso
       y >= 0 AndAlso y < verticalWallItems(x).Length AndAlso
       verticalWallItems(x)(y) = "picFlipper2" Then
            movingObject.DeltaX = 1 ' Move right
            movingObject.DeltaY = 0
            movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
            movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
            sfxManager.PlaySoundEffect("Flipper")
            Return
        End If
    
        ' Right Flipper Check (Flipper1)
        If x + 1 < verticalWallItems.Length AndAlso
       y >= 0 AndAlso y < verticalWallItems(x + 1).Length AndAlso
       verticalWallItems(x + 1)(y) = "picFlipper1" Then
            movingObject.DeltaX = -1 ' Move left
            movingObject.DeltaY = 0
            movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
            movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
            sfxManager.PlaySoundEffect("Flipper")
            Return
        End If
    
        ' Up Flipper Check (Flipper4)
        If x >= 0 AndAlso x < horizontalWallItems.Length AndAlso
       y >= 0 AndAlso y < horizontalWallItems(x).Length AndAlso
       horizontalWallItems(x)(y) = "picFlipper4" Then
            movingObject.DeltaX = 0
            movingObject.DeltaY = 1 ' Move down
            movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
            movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
            sfxManager.PlaySoundEffect("Flipper")
            Return
        End If
    
        ' Down Flipper Check (Flipper3)
        If x >= 0 AndAlso x < horizontalWallItems.Length AndAlso
       y + 1 < horizontalWallItems(x).Length AndAlso
       horizontalWallItems(x)(y + 1) = "picFlipper3" Then
            movingObject.DeltaX = 0
            movingObject.DeltaY = -1 ' Move up
            movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
            movingObject.NextMoveTime = DateTime.Now.AddMilliseconds(movingObject.MoveInterval)
            sfxManager.PlaySoundEffect("Flipper")
            Return
        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 = "picLaser1") Then
                laserCanBeDestroyed = True
            ElseIf (deltaY <> 0 AndAlso laserType = "picLaser2") 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 Laser")
            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 = "picLaser1" OrElse item = "picLaser2"
        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 = "picLaser1" OrElse item = "picLaser2"
        End If
        Return False
    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
    
        ' Allow movement onto BlockSwitch
        Dim targetItem As String = placedItems(newX)(newY)
        If targetItem = "picBlockSwitch" OrElse targetItem = "picBlockSwitch2" Then
            Return True
        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
    

    #End Region

    #Region " Drawing " Private Sub OnAnimationTick(sender As Object, e As EventArgs) For Each img In animatedImages ImageAnimator.UpdateFrames(img) Next 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
    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
    

    #End Region

    #Region " Triggers " Private Sub CheckTriggers() Dim triggersToRemove As New List(Of Triggers)() Dim triggerExecuted As Boolean = False

        For Each trigger In triggers
            If CheckTriggerCondition(trigger) Then
                ExecuteTriggerAction(trigger)
                triggersToRemove.Add(trigger)
                triggerExecuted = True
            End If
        Next
    
        ' Remove the executed triggers after the iteration
        For Each trigger In triggersToRemove
            triggers.Remove(trigger)
        Next
    End Sub
    
    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        If trigger.TriggerComplete Then
            Return False
        End If
    
        Dim coords As String() = trigger.TriggeringCell.Trim("()".ToCharArray()).Split(",")
        If coords.Length <> 2 Then
            Return False
        End If
    
        Dim triggerX As Integer
        Dim triggerY As Integer
    
        If Not Integer.TryParse(coords(0).Trim(), triggerX) OrElse Not Integer.TryParse(coords(1).Trim(), triggerY) Then
            Return False
        End If
    
        Dim strItemName As String = trigger.TriggeringItem
    
        ' Map TriggeringItem to actual item keys
        Select Case trigger.TriggeringItem
            Case "Block 1"
                strItemName = "picBlock1"
            Case "Player"
                strItemName = "player"
                ' Add more mappings as needed
        End Select
    
        ' Check if the TriggeringItem is in the specified position
        If strItemName.ToLower() = "player" Then
            If playerX = triggerX AndAlso playerY = triggerY Then
                Return True
            End If
        Else
            If placedItems(triggerX)(triggerY) = strItemName Then
                Return True
            End If
        End If
    
        Return False
    End Function
    
    Private Sub ExecuteTriggerAction(trigger As Triggers)
        If trigger.ActionType = "Remove" Then
            Dim coords As String() = trigger.ActionRemove.Trim("()".ToCharArray()).Split(",")
            If coords.Length = 2 Then
                Dim x As Integer
                Dim y As Integer
    
                If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                    RemoveItemAt(x, y) ' Call the method to remove item
                End If
            End If
        ElseIf trigger.ActionType = "Create" Then
            Dim coords As String() = trigger.ActionCell.Trim("()".ToCharArray()).Split(",")
            If coords.Length = 2 Then
                Dim x As Integer
                Dim y As Integer
    
                If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                    CreateItemAt(x, y, trigger.ActionCreate) ' Call the method to create item
                End If
            End If
        End If
    
        ' Set TriggerComplete to True after the action is executed
        trigger.TriggerComplete = True
    End Sub
    Private Sub RemoveItemAt(x As Integer, y As Integer)
        If IsWithinBounds(x, y) Then
            placedItems(x)(y) = Nothing ' Clear the cell
        End If
    End Sub
    
    Private Sub CreateItemAt(x As Integer, y As Integer, typeToCreate As String)
        If IsWithinBounds(x, y) Then
            Select Case typeToCreate
                Case "Baddy 1"
                    Dim newBaddy As New Baddy(x, y, "picBaddy1") ' Adjust the image key as needed
                    baddies.Add(newBaddy)
                    placedItems(x)(y) = "picBaddy1" ' Record creation on the grid
                Case "Coin"
                    placedItems(x)(y) = "picCoin" ' Record creation on the grid
            End Select
        End If
    End Sub
    
    Private Function IsWithinBounds(x As Integer, y As Integer) As Boolean
        Return x >= 0 AndAlso x < SQCOUNTX AndAlso y >= 0 AndAlso y < SQCOUNTY
    End Function
    

    #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

    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

    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
    
            ' Initialize triggers from room data
            If roomData.Triggers IsNot Nothing Then
                triggers = roomData.Triggers
            End If
    
            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
    

    #End Region

    End Class

    Public Class DoubleBufferedPictureBox Inherits PictureBox

    Public Sub New()
        Me.DoubleBuffered = True
    End Sub
    

    End Class

    Public Class NoBorderToolStripRenderer Inherits ToolStripRenderer

    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

    Public Class Triggers Public Property TriggeringItem As String Public Property TriggeringCell As String Public Property ActionType As String Public Property ActionCell As String Public Property ActionRemove As String Public Property ActionCreate As String Public Property FullTrigger As String Public Property TriggerComplete As Boolean

    Public Overrides Function ToString() As String
        UpdateFullTrigger()
        Return FullTrigger
    End Function
    
    Private Sub UpdateFullTrigger()
        If ActionType = "Remove" Then
            FullTrigger = $"When {TriggeringItem} enters cell {TriggeringCell}, remove {ActionRemove} at {ActionCell} from the game."
        Else
            FullTrigger = $"When {TriggeringItem} enters cell {TriggeringCell}, create a {ActionCreate} at cell {ActionCell}."
        End If
    End Sub
    

    End Class

    I need you to look at Region " Triggers "

    I've created some triggers to test them out in a test level to get them working. The triggers loaded into the test level are...

    #1, FullTrigger: "When Block 1 enters cell (6, 4), remove BlockStopper at (6, 5) from the game." Translated: "When TriggeringItem enters cell TriggeringCell, ActionType ActionRemove at ActionCell from the game." This trigger isn't working. The Blockstopper is not removed.

    #2 FullTrigger: "When Block 1 enters cell (5, 4), create a Baddy 1 at cell (5, 5)." Translated: "When TriggeringItem enters cell TriggeringCell, ActionType a ActionCreate at ActionCell." This triggers. Kind of works. However, it creates 2 baddies. 1 baddy starts moving. The other remains static.

    I ran a few triggers to create a coin and that worked perfectly. Though I suspect 2 coins were created, but since they are on the same square they overwrite each other.

  2. Assistant

    The issues you're experiencing with the triggers in your game can arise from various factors. Let’s address each one specifically.

    Issue #1: BlockStopper Not Being Removed

    For the first trigger, which is meant to remove a BlockStopper at position (6, 5), it seems that the "trigger condition" may not be met, hence the action is not executed. You should verify a few key areas:

    1. Trigger Condition Check: Ensure that the CheckTriggerCondition method correctly matches the player's position against the trigger's TriggeringCell. If Block 1 is entering (6, 4), but the condition that checks for the player's position is perhaps looking for the player instead. The condition should be:

      If strItemName.ToLower() = "block 1" Then
          If playerX = triggerX AndAlso playerY = triggerY Then
              Return True
          End If
      ElseIf strItemName.ToLower() = "player" Then
          If playerX = triggerX AndAlso playerY = triggerY Then
              Return True
          End If
      End If
      

      It appears that you are currently mapping "Block 1" directly to the placed items currently on the grid. Thus, it is important to ensure that Block 1 itself could be identified and moved to trigger the action.

    2. RemoveAction Implementation: In the ExecuteTriggerAction method, verify that the RemoveItemAt function successfully clears the designated cell without any out-of-bounds handling issues.

    Issue #2: Two Baddies Being Created

    The second issue with two baddies being created suggests that the trigger condition for creating the baddies was met multiple times in the same game tick. This can happen if:

    1. Trigger Checking Logic: If it checks the position of the player or the moving object that triggers the condition twice in a single game tick, due to multiple references to the same trigger, it might execute the action twice.

      Make sure that after executing the trigger action, it gets removed from the triggers list as it currently is done in your loop to avoid it being executed again in the same tick:

      If CheckTriggerCondition(trigger) Then
          ExecuteTriggerAction(trigger)
          triggersToRemove.Add(trigger) ' Ensure this is called so that the trigger doesn't execute again
          triggerExecuted = True
      End If
      
    2. Routine for Creating Baddies: When creating a new baddy, ensure that you’re not accidentally adding the same baddy multiple times if the trigger was checked more than once. This would also happen if you have a history of items that trigger each time a player enters a cell.

      As you confirm the execution of triggers, ensure you encapsulate the adding of baddies in the correct sequence without duplication.

    3. Debugging: Use debug logs or Console.WriteLine statements within both CheckTriggerCondition and ExecuteTriggerAction to track when these functions are executed and what actions are taken. This would help identify how often those functions are called and where duplication might occur.

    Conclusion

    Reviewing and refining the trigger conditions and ensuring that each action is processed correctly in sequence (with appropriate state management) governs how triggers should behave.

    By following these suggested steps, you should be able to address your current issues with the trigger system effectively! If there are still problems after these adjustments, it might require a deeper dive into how movements and state changes are managed within your game loop.

  3. User

    This can be removed... triggerExecuted = True

    We have this in the class.. Public Property TriggerComplete As Boolean

    So triggers.TriggerComplete = True is all round better. However. The game doesn't like my line :(

  4. Assistant

    It sounds like you're on the right track by using the TriggerComplete property to manage the state of your triggers. This approach is good for tracking whether a trigger has already been executed, thus avoiding duplicate actions, and it's a more robust solution than using triggerExecuted.

    Given your context, if you are having trouble with the line triggers.TriggerComplete = True, it’s likely due to how the property is being accessed or updated. Here are some pointers to resolve potential issues:

    Ensuring Proper Access to TriggerComplete

    1. Ensure Correct Access: Make sure that you are accessing the TriggerComplete property correctly for the specific Trigger instance you are working with. If you're using something like triggers.TriggerComplete, it should be:

      trigger.TriggerComplete = True
      

      Here, trigger represents the current instance of your Triggers class you are iterating over, rather than a list or collection of triggers.

    2. Modify the ExecuteTriggerAction: In your ExecuteTriggerAction method, ensure that you’re marking the specific trigger instance as complete:

      Private Sub ExecuteTriggerAction(trigger As Triggers)
          If trigger.ActionType = "Remove" Then
              Dim coords As String() = trigger.ActionRemove.Trim("()".ToCharArray()).Split(",")
              If coords.Length = 2 Then
                  Dim x As Integer
                  Dim y As Integer
                  If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                      RemoveItemAt(x, y) ' Call method to remove item
                  End If
              End If
          ElseIf trigger.ActionType = "Create" Then
              Dim coords As String() = trigger.ActionCell.Trim("()".ToCharArray()).Split(",")
              If coords.Length = 2 Then
                  Dim x As Integer
                  Dim y As Integer
                  If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                      CreateItemAt(x, y, trigger.ActionCreate) ' Call method to create item
                  End If
              End If
          End If
      
          ' Setting TriggerComplete to True for the executed trigger
          trigger.TriggerComplete = True
      End Sub
      

    Checking the Implementation of Trigger Property

    Make sure the TriggerComplete property is properly defined within the Triggers class. Here’s a sample definition for clarity:

    Public Class Triggers
        Public Property TriggeringItem As String
        Public Property TriggeringCell As String
        Public Property ActionType As String
        Public Property ActionCell As String
        Public Property ActionRemove As String
        Public Property ActionCreate As String
        Public Property FullTrigger As String
        Public Property TriggerComplete As Boolean = False ' Ensure it's initialized
    
        ' Other methods and logic...
    End Class
    

    Troubleshooting

    1. Debugging: If you're still facing issues, add some debug statements to ensure that:

      • You are correctly iterating over the triggers list.
      • You are accessing the correct instance of the Triggers class.
      • The ExecuteTriggerAction is being called as expected.
    2. Check for Exceptions: If there's an exception thrown when you assign TriggerComplete, check your output or debugger to find out what the message is, as it could give clues about what’s going wrong.

    By ensuring the above adjustments and checks, you should be better equipped to implement the completion state for your triggers successfully. If you continue to experience issues or errors, please provide more details about the specific error messages or behaviors you’re encountering, and I'll be happy to assist further!

  5. User

    'TriggerComplete' is not a member of 'List(Of Triggers)'.

    :(

    Private Sub CheckTriggers()
        Dim triggersToRemove As New List(Of Triggers)()
        For Each trigger In triggers
            If CheckTriggerCondition(trigger) Then
                ExecuteTriggerAction(trigger)
                triggersToRemove.Add(trigger)
                triggers.TriggerComplete = True
            End If
        Next
    
        ' Remove the executed triggers after the iteration
        For Each trigger In triggersToRemove
            triggers.Remove(trigger)
        Next
    End Sub
    

    Doesn't work there...

    But works here???

    Private Sub ExecuteTriggerAction(trigger As Triggers)
        If trigger.ActionType = "Remove" Then
            Dim coords As String() = trigger.ActionRemove.Trim("()".ToCharArray()).Split(",")
            If coords.Length = 2 Then
                Dim x As Integer
                Dim y As Integer
                If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                    RemoveItemAt(x, y) ' Call method to remove item
                End If
            End If
        ElseIf trigger.ActionType = "Create" Then
            Dim coords As String() = trigger.ActionCell.Trim("()".ToCharArray()).Split(",")
            If coords.Length = 2 Then
                Dim x As Integer
                Dim y As Integer
                If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                    CreateItemAt(x, y, trigger.ActionCreate) ' Call method to create item
                End If
            End If
        End If
    
        ' Setting TriggerComplete to True for the executed trigger
        trigger.TriggerComplete = True
    End Sub
    
  6. Assistant

    The issue you're encountering is due to a misunderstanding in how you're trying to access the TriggerComplete property.

    In your CheckTriggers method, the line:

    triggers.TriggerComplete = True
    

    is incorrect because triggers is a list of Triggers, and you can't directly call a property on a collection object. Instead, you should be referencing the specific trigger object that you're iterating over in the For Each loop.

    Correcting Your CheckTriggers Method

    Here's the corrected code for your CheckTriggers method:

    Private Sub CheckTriggers()
        Dim triggersToRemove As New List(Of Triggers)()
        For Each trigger In triggers
            If CheckTriggerCondition(trigger) Then
                ExecuteTriggerAction(trigger)
                triggersToRemove.Add(trigger)
                trigger.TriggerComplete = True ' Set the TriggerComplete for the specific trigger
            End If
        Next
    
        ' Remove the executed triggers after the iteration
        For Each trigger In triggersToRemove
            triggers.Remove(trigger)
        Next
    End Sub
    

    Explanation

    1. Using trigger:

      • In the loop For Each trigger In triggers, trigger is a single instance of the Triggers class. Therefore, you can access its properties, including TriggerComplete.
    2. Marking as Complete:

      • When you successfully execute an action for a specific trigger, set trigger.TriggerComplete = True. This tells the system that this trigger has already been executed.

    Additional Considerations

    • Initialization: Ensure that the TriggerComplete property in the Triggers class is initialized properly (it should default to False, which it looks like you have already done).

    • Consistent State Change: By setting TriggerComplete to True inside the loop, it maintains functional clarity. In your execution logic (in this case, ExecuteTriggerAction), you're encapsulating the logic without modifying external state unnecessarily.

    • List Manipulation: You're correctly maintaining a separate list (triggersToRemove) for triggers that need to be removed. It's a good approach to avoid modifying the collection while iterating over it directly, which can lead to exceptions.

    Final Thoughts

    This adjustment should fix the issue you were facing. If triggers are still not functioning as expected after this change, consider logging or debugging each step in the CheckTriggers and ExecuteTriggerAction methods to track down what might be going wrong. This could include logging the state of each trigger when checked, whether the condition is met, and whether actions are executed correctly.

  7. User

    We don't need this part now do we?

    ' Remove the executed triggers after the iteration For Each trigger In triggersToRemove triggers.Remove(trigger) Next

  8. Assistant

    You are correct in your assumption! If you are setting TriggerComplete to True and ensuring that triggers won’t be executed again in their next checks, you may indeed not need to explicitly remove executed triggers from the collection in your CheckTriggers method.

    Here’s why you might avoid the removal step:

    1. Trigger Completeness: By marking triggers as complete with TriggerComplete = True, you can prevent them from being executed again in future checks without needing to remove them from the list. This is a simpler approach and can enhance performance by avoiding the overhead of modifying the list (which involves reallocation and re-indexing).

    2. Future Expansions: Keeping the triggers in the list could allow for easier debugging or future feature expansions. If you ever need to inspect completed triggers for logging or gameplay mechanics, having them in the list will make this easier.

    Updated CheckTriggers Method

    Here's your updated CheckTriggers method without the removal logic:

    Private Sub CheckTriggers()
        For Each trigger In triggers
            If CheckTriggerCondition(trigger) Then
                ExecuteTriggerAction(trigger)
                trigger.TriggerComplete = True ' Set the TriggerComplete for the specific trigger
            End If
        Next
    End Sub
    

    When to Consider Removal

    You might still consider removing triggers from the list if:

    • Memory Usage: If the list of triggers becomes large, you may want to clean it up by removing used triggers if they are no longer needed.
    • Complex State Management: If your game logic inherently requires a clean state (e.g., resetting levels, re-initializing triggers, etc.), having a distinct removal might be justified.

    In conclusion, for your current needs, it's completely fine to leave the removal logic out and simply track completion using the TriggerComplete property! It streamlines your code and enhances its readability.

  9. User

    GAH still creates 2 baddies :( :(

    1 of them is buggy and doesn't move. It must be an issue elsewhere?

  10. Assistant

    If you're still encountering the issue of two baddies being created when you only expect one, along with one of them being stationary, it suggests that the trigger responsible for creating the baddy is being executed multiple times. Let's troubleshoot and enhance your code step-by-step.

    Steps to Diagnose and Resolve the Issue

    1. Review Trigger Checking Logic: Ensure that the CheckTriggerCondition is not being called multiple times for the same state in the same update frame. You can use logging to confirm how many times the trigger is being executed.

      Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
          ' Log when this function is called
          Console.WriteLine($"Checking trigger condition: {trigger.FullTrigger}")
      
          If trigger.TriggerComplete Then
              Return False
          End If
          ' Insert code to check trigger conditions...
      End Function
      
    2. Check for Duplicate Triggers: It is possible that you may have multiple instances of the same trigger in the triggers list. Print out the contents of the list before you start checking conditions to see if duplicates exist.

      Console.WriteLine("Current Triggers:")
      For Each t In triggers
          Console.WriteLine(t.FullTrigger)
      Next
      
    3. Debug Create Logic: Inside your ExecuteTriggerAction, ensure you are creating a single new baddy properly and using the correct logic. Introduce logging to confirm that the number of creations of baddies is as expected.

      Private Sub ExecuteTriggerAction(trigger As Triggers)
          If trigger.ActionType = "Create" Then
              Dim coords As String() = trigger.ActionCell.Trim("()".ToCharArray()).Split(",")
              If coords.Length = 2 Then
                  Dim x As Integer
                  Dim y As Integer
                  If Integer.TryParse(coords(0).Trim(), x) AndAlso Integer.TryParse(coords(1).Trim(), y) Then
                      ' Log the creation
                      Console.WriteLine($"Creating Baddy at ({x}, {y})")
                      CreateItemAt(x, y, trigger.ActionCreate) ' Call method to create item
                  End If
              End If
          End If
          ' Set TriggerComplete to True for the executed trigger
          trigger.TriggerComplete = True
      End Sub
      
    4. Check the CreateItemAt Logic: Ensure that the logic in your CreateItemAt method is correctly handling the creation of baddies, and make sure it doesn't create a second instance inadvertently.

    Private Sub CreateItemAt(x As Integer, y As Integer, typeToCreate As String)
        If IsWithinBounds(x, y) Then
            Select Case typeToCreate
                Case "Baddy 1"
                    ' Check for existing baddies before adding a new one
                    Dim alreadyExists = baddies.Any(Function(b) b.X = x AndAlso b.Y = y)
                    If Not alreadyExists Then
                        Dim newBaddy As New Baddy(x, y, "picBaddy1") ' Adjust the image key as needed
                        baddies.Add(newBaddy)
                        placedItems(x)(y) = "picBaddy1" ' Record creation on the grid
                    End If
                    Console.WriteLine("Baddy created successfully")
                Case "Coin"
                    placedItems(x)(y) = "picCoin" ' Record creation on the grid
            End Select
        End If
    End Sub
    
    1. Confirm Movement Logic: Make sure that when you add a new baddy, it is being added to the game loop for movement.

      • If there's an issue in how you handle baddy movement, debug the movement logic to ensure each baddy behaves properly.
    2. Logging and Observations: Use console logging throughout the relevant sections (check conditions, executing actions, and adding movement logic for baddies) to observe how many times these sections are reached.

      This should give you insights into whether the trigger’s creation is firing twice and why.

    Synthesis

    If you go through these checks, you should be able to pinpoint the root of the issue causing multiple baddies to be created. Ensure that you have effective guards against duplicates in the creation logic, and keep careful track of the conditions under which each trigger is activated. Always log relevant data to get insights into the internal state upon execution. If any specific parts of your logic seem unclear or need further clarification, feel free to ask!

  11. User

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean ' Log when this function is called Console.WriteLine($"Checking trigger condition: {trigger.FullTrigger}")

    If trigger.TriggerComplete Then
        Return False
    End If
    ' Insert code to check trigger conditions...
    

    End Function

    No idea what that means... You may aswell of said " Purple"

    I think using debug.writeline is a great idea to identify if the trigger is indeed firing off twice

  12. Assistant

    My apologies for the confusion! Let's break down what the suggested code means in simpler terms and then also incorporate your feedback about using Debug.WriteLine.

    Explanation of the Function

    The CheckTriggerCondition function is intended to verify whether a trigger's action should execute or not.

    Here's an annotated breakdown of the function:

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        ' Log when this function is called to see what trigger is being checked
        Debug.WriteLine($"Checking trigger condition: {trigger.FullTrigger}")
    
        ' If the trigger has already been executed (TriggerComplete is True), return False
        If trigger.TriggerComplete Then
            Return False ' This means don't execute the trigger again
        End If
    
        ' Insert your existing logic here to check if the trigger condition should be met,
        ' like checking if the player is in the right position.
        ' This could involve checking the player's coordinates against the coordinates defined in the trigger.
    End Function
    

    Using Debug.WriteLine

    In VB.NET, Debug.WriteLine is commonly used to output messages to the debug output window, which can be helpful during development and debugging.

    Step-by-Step Action:

    1. Add the Debug.WriteLine Statement: Replace the console log with Debug.WriteLine for better integration in a Visual Studio environment. It will help you see when the function is called and provide context.

    2. Complete the Function: You must complete the part where you check the conditions. Here’s an example of how you might implement condition checks:

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        ' Log when this function is called to see what trigger is being checked
        Debug.WriteLine($"Checking trigger condition: {trigger.FullTrigger}")
    
        ' If the trigger has already been executed (TriggerComplete is True), return False
        If trigger.TriggerComplete Then
            Return False
        End If
    
        ' Example condition check (adapt this to your actual logic)
        Dim coords As String() = trigger.TriggeringCell.Trim("()".ToCharArray()).Split(",")
        If coords.Length <> 2 Then Return False
    
        Dim triggerX As Integer, triggerY As Integer
        If Not Integer.TryParse(coords(0).Trim(), triggerX) OrElse Not Integer.TryParse(coords(1).Trim(), triggerY) Then
            Return False
        End If
    
        ' For this example, we assume you have a method to get the player's position
        If playerX = triggerX AndAlso playerY = triggerY Then
            Return True ' Trigger condition met
        End If
    
        Return False ' Condition not met
    End Function
    

    Additional Debugging Steps

    • Log Every Trigger Check: Place Debug.WriteLine throughout relevant areas of your trigger checking and action execution logic. This lets you see how many times these functions are being hit and under what conditions:

      Debug.WriteLine($"Executing action for trigger: {trigger.FullTrigger}")
      
    • Check for Duplicates: If you identify that a trigger condition is firing multiple times, also log when triggers are added to the list. This helps you understand how the game state is being managed.

    Conclusion

    Using Debug.WriteLine is a great way to troubleshoot your issue related to multiple baddies being created. By implementing these logging statements, you'll have a clearer picture of the internal code execution flow and can investigate the source of the duplication more effectively. If you need further assistance or have other questions, please don't hesitate to ask!

  13. User

    Can you give me the complete sub please Private Function CheckTriggerCondition(trigger As Triggers) As Boolean

  14. Assistant

    Certainly! Below is a complete implementation of the CheckTriggerCondition function that checks whether a given trigger condition is met based on the player’s position in relation to the triggering cell defined in the trigger.

    Complete CheckTriggerCondition Function

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        ' Log when this function is called to see what trigger is being checked
        Debug.WriteLine($"Checking trigger condition: {trigger.FullTrigger}")
    
        ' If the trigger has already been executed (TriggerComplete is True), return False
        If trigger.TriggerComplete Then
            Debug.WriteLine($"Trigger already completed: {trigger.FullTrigger}")
            Return False ' This means don't execute the trigger again
        End If
    
        ' Parse the triggering cell coordinates from the trigger
        Dim coords As String() = trigger.TriggeringCell.Trim("()".ToCharArray()).Split(",")
        If coords.Length <> 2 Then Return False ' Return false if the coordinates are malformed
    
        Dim triggerX As Integer
        Dim triggerY As Integer
    
        ' Try to parse the coordinates; return false if it fails
        If Not Integer.TryParse(coords(0).Trim(), triggerX) OrElse Not Integer.TryParse(coords(1).Trim(), triggerY) Then
            Debug.WriteLine($"Invalid coordinates in trigger: {trigger.TriggeringCell}")
            Return False
        End If
    
        ' Check if the player's position matches the trigger's position
        If playerX = triggerX AndAlso playerY = triggerY Then
            Debug.WriteLine($"Trigger condition met for: {trigger.FullTrigger}")
            Return True ' Trigger condition met
        End If
    
        ' If none of the conditions were met, return false
        Debug.WriteLine($"Trigger condition not met for: {trigger.FullTrigger}")
        Return False 
    End Function
    

    Function Breakdown

    1. Logging: The function begins by logging the trigger condition check, which can help understand how often and when triggers are checked.

    2. Check TriggerComplete: The first condition checks if the trigger has already been executed. If it has, the function logs this and returns False.

    3. Coordinate Parsing: It attempts to parse the triggering cell's coordinates from the TriggeringCell string. If parsing fails (i.e., the format is incorrect), it logs an error and returns False.

    4. Position Comparison: It compares the player's current position (playerX, playerY) against the parsed trigger coordinates (triggerX, triggerY). If they match, it logs that the condition is met and returns True.

    5. Final Log and Return: If none of the conditions are satisfied, it logs that the trigger condition is not met and returns False.

    Conclusion

    This function should work within your existing trigger mechanism, allowing you to properly control when triggers should execute based on player movements. Implement this within your game logic, and monitor the debug output to better understand trigger behavior. If you need more help or any modifications, feel free to ask!

  15. User

    THIS

    is the complete sub... YOURS is not...

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        If trigger.TriggerComplete Then
            Return False
        End If
    
        Dim coords As String() = trigger.TriggeringCell.Trim("()".ToCharArray()).Split(",")
        If coords.Length <> 2 Then
            Return False
        End If
    
        Dim triggerX As Integer
        Dim triggerY As Integer
    
        If Not Integer.TryParse(coords(0).Trim(), triggerX) OrElse Not Integer.TryParse(coords(1).Trim(), triggerY) Then
            Return False
        End If
    
        Dim strItemName As String = trigger.TriggeringItem
    
        ' Map TriggeringItem to actual item keys
        Select Case trigger.TriggeringItem
            Case "Block 1"
                strItemName = "picBlock1"
            Case "Player"
                strItemName = "player"
                ' Add more mappings as needed
        End Select
    
        ' Check if the TriggeringItem is in the specified position
        If strItemName.ToLower() = "player" Then
            If playerX = triggerX AndAlso playerY = triggerY Then
                Return True
            End If
        Else
            If placedItems(triggerX)(triggerY) = strItemName Then
                Return True
            End If
        End If
    
        Return False
    End Function
    
  16. Assistant

    Thank you for your patience, and I apologize for the oversight. Let's integrate your complete implementation of the CheckTriggerCondition function with some added logging for debugging purposes.

    Complete CheckTriggerCondition Function with Debugging

    Here’s the full implementation that includes logging to help you track the conditions being checked:

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        ' If the trigger has already been executed (TriggerComplete is True), return False
        If trigger.TriggerComplete Then
            Debug.WriteLine($"Trigger already completed: {trigger.FullTrigger}")
            Return False
        End If
    
        ' Parse the triggering cell coordinates from the trigger
        Dim coords As String() = trigger.TriggeringCell.Trim("()".ToCharArray()).Split(",")
        If coords.Length <> 2 Then
            Debug.WriteLine($"Invalid coordinates in trigger: {trigger.TriggeringCell}")
            Return False ' Return false if the coordinates are malformed
        End If
    
        Dim triggerX As Integer
        Dim triggerY As Integer
    
        ' Try to parse the coordinates; return false if it fails
        If Not Integer.TryParse(coords(0).Trim(), triggerX) OrElse Not Integer.TryParse(coords(1).Trim(), triggerY) Then
            Debug.WriteLine($"Failed to parse coordinates: {coords(0).Trim()}, {coords(1).Trim()}")
            Return False
        End If
    
        Dim strItemName As String = trigger.TriggeringItem
    
        ' Map TriggeringItem to actual item keys (additional mappings can be added here)
        Select Case trigger.TriggeringItem
            Case "Block 1"
                strItemName = "picBlock1"
            Case "Player"
                strItemName = "player"
            ' Add more mappings as needed
        End Select
    
        ' Log the mapping for debugging
        Debug.WriteLine($"Checking condition for item: {strItemName} at ({triggerX}, {triggerY})")
    
        ' Check if the TriggeringItem is in the specified position
        If strItemName.ToLower() = "player" Then
            If playerX = triggerX AndAlso playerY = triggerY Then
                Debug.WriteLine($"Trigger condition met for Player at ({triggerX}, {triggerY})")
                Return True
            End If
        Else
            If placedItems(triggerX)(triggerY) = strItemName Then
                Debug.WriteLine($"Trigger condition met for {strItemName} at ({triggerX}, {triggerY})")
                Return True
            End If
        End If
    
        ' If none of the conditions were met, return false
        Debug.WriteLine($"Trigger condition not met for: {trigger.FullTrigger}")
        Return False 
    End Function
    

    Breakdown of Additions

    1. Logging Statements:

      • Added Debug.WriteLine statements before and after key checks to log the internal state and decisions, making it easier to identify when triggers are checked and what the conditions are.
    2. Mapping of Triggering Items:

      • The function now includes a mapping for Block 1 and Player, which helps relate the trigger's action to actual game entities.
    3. Condition Checks:

      • The logic checks if the player or the specified item is at the trigger coordinates. If the conditions are met, it logs which condition was satisfied.

    Usage

    1. Debugging:

      • Compile and run your game, then monitor the output window in Visual Studio (or wherever you direct your debug output) for messages. This will help you see if the function is checked multiple times and when an item fulfills the triggers.
    2. Integrate in Game Logic:

      • Place this code in your trigger-checking mechanism where needed, and ensure it fits within your overall design.

    If you continue to experience issues related to trigger execution, observing the debug output will be invaluable for diagnosing where and why things are not functioning as intended. If you need further modifications or explanations, feel free to ask!

  17. User

    No output?

  18. Assistant

    If you're not seeing any output from Debug.WriteLine in your Visual Studio output window, here are some steps to troubleshoot the issue:

    1. Ensure the Output Window is Visible

    In Visual Studio:

    • Go to the View menu.
    • Click on Output to ensure the output window is open.
    • Make sure that in the "Show output from" dropdown, you have "Debug" selected.

    2. Check Debug Configuration

    Make sure you're running your project in Debug mode rather than Release mode:

    • In the top menu (the toolbar), you will see Debug or Release. Ensure it is set to Debug.

    3. Properly Use Debug.WriteLine

    Debug.WriteLine only outputs messages while the debugger is attached. Ensure the code behind is actually executed. If the code is not running in the context where it can hit your checks, the messages won’t appear.

    4. Confirm That the Function is Being Called

    Add some output at the very beginning of the CheckTriggerCondition function to confirm whether the function is reached:

    Private Function CheckTriggerCondition(trigger As Triggers) As Boolean
        Debug.WriteLine("CheckTriggerCondition function called") ' Confirm invocation
    
        If trigger.TriggerComplete Then
            Debug.WriteLine($"Trigger already completed: {trigger.FullTrigger}")
            Return False
        End If
        
        ' ... rest of the code remains the same
    

    5. Check if Triggers are Actually Being Checked

    Make sure that the CheckTriggerCondition function is truly being called during the game loop. If there are conditions that prevent it from being invoked, you won't see the output.

    6. Add Additional Debugging Output

    You can add more Debug.WriteLine statements in various parts of the relevant game loop to get visibility on what parts of your code are executing:

    ' Just before your trigger checking loop
    Debug.WriteLine("About to check triggers...")
    
    For Each trigger In triggers
        Debug.WriteLine($"Checking trigger: {trigger.FullTrigger}")
        If CheckTriggerCondition(trigger) Then
            Debug.WriteLine("Trigger condition passed.")
            ExecuteTriggerAction(trigger)
        Else
            Debug.WriteLine("Trigger condition not met.")
        End If
    Next
    

    7. Verify Trigger Population

    Make sure your triggers list is populated before this function is called. If the list is empty, the function won't be executed and you won't see any output.

    • You can log the triggers list's count before checking conditions:
    Debug.WriteLine($"Number of triggers to check: {triggers.Count}")
    

    8. Check the Trigger Execution Logic

    If you have conditions around when the trigger checks occur, make sure that they are satisfied so that CheckTriggerCondition runs.

    Example of Complete Trigger Check Logic

    Here’s how you might integrate the overall trigger checking in your method:

    Private Sub CheckTriggers()
        Debug.WriteLine("Checking triggers...")
    
        Debug.WriteLine($"Number of triggers to check: {triggers.Count}")
    
        For Each trigger In triggers
            Debug.WriteLine($"Checking trigger: {trigger.FullTrigger}")
            If CheckTriggerCondition(trigger) Then
                Debug.WriteLine("Trigger condition passed.")
                ExecuteTriggerAction(trigger)
            Else
                Debug.WriteLine("Trigger condition not met.")
            End If
        Next
    End Sub
    

    Conclusion

    By ensuring output is set to the correct window, adding sufficient debug messages, and confirming the execution flow, you should be able to identify where things are going awry. If you’re still having trouble, or the output remains elusive, there may be a larger issue at play in the broader context of your game logic that might require additional review. Feel free to share more details, and we can diagnose further!

  19. User

    The output window works fine :)

    There's just no output fromt eh code :)

  20. Assistant

    If the output window in Visual Studio is functioning properly but you are seeing no output from the Debug.WriteLine statements within your CheckTriggerCondition function or anywhere else in your code, it typically indicates that the code is not being executed as expected. Here’s a step-by-step approach to troubleshoot this issue:

    1. Ensure the Function is Invoked

    Check that CheckTriggerCondition is being called within your game logic. Place a debug line in the code that invokes this function to confirm it’s executing:

    Debug.WriteLine("About to check triggers...")
    CheckTriggerCondition(trigger)
    

    2. Verify Trigger State

    Confirm that your triggers list is not empty before entering the loop that checks the triggers. If triggers has no items, the loop will not be executed and therefore no output will be generated. Log the count of triggers right before the loop to make sure it's populated:

    Debug.WriteLine($"Number of triggers: {triggers.Count}")
    

    3. Check for Conditions to see if they are met

    In the CheckTriggers method, ensure the following structure is confirmed:

    Private Sub CheckTriggers()
        Debug.WriteLine("Checking triggers...")
    
        For Each trigger In triggers
            Debug.WriteLine($"Checking trigger: {trigger.FullTrigger}")
            Dim conditionMet As Boolean = CheckTriggerCondition(trigger)
            If conditionMet Then
                Debug.WriteLine("Trigger condition met.")
                ExecuteTriggerAction(trigger)
            Else
                Debug.WriteLine("Trigger condition not met.")
            End If
        Next
    End Sub
    

    4. Output Within the ExecuteTriggerAction Method

    Also, verify if ExecuteTriggerAction is running correctly by adding output statements within this method:

    Private Sub ExecuteTriggerAction(trigger As Triggers)
        Debug.WriteLine($"Executing action for trigger: {trigger.FullTrigger}")
        If trigger.ActionType = "Remove" Then
            ' Logic for removing items
        ElseIf trigger.ActionType = "Create" Then
            ' Logic for creating items
        End If
    
        ' Set TriggerComplete to True for the executed trigger
        trigger.TriggerComplete = True
        Debug.WriteLine("Trigger marked as complete.")
    End Sub
    

    5. Add Checks to Other Functions

    You should also add debug statements in other related functions, such as those that modify the game state like CreateItemAt, to ensure that they are being executed properly:

    Private Sub CreateItemAt(x As Integer, y As Integer, typeToCreate As String)
        Debug.WriteLine($"Attempting to create item: {typeToCreate} at ({x}, {y})")
        ' Existing logic to create item...
    End Sub
    

    6. Check for Exceptions

    Use a try-catch block around the areas of your game logic where you suspect execution might halt. Any runtime exceptions could prevent your code from reaching the debug statements:

    Try
        CheckTriggers()
    Catch ex As Exception
        Debug.WriteLine($"Exception occurred: {ex.Message}")
    End Try
    

    Conclusion

    By following these steps, you should be able to isolate where in your code flow things are breaking down. If, after all of this, you’re still not getting any output from Debug.WriteLine, there might be an issue at a higher level in your program logic, and it would be useful to trace how control flows through your game’s structure. Make sure that every potential path to executing triggers is logged to help in debugging. If you find anything specific, feel free to share, and I can help further!