Public Class ItemInfo
Public Property ImageKey As String ' Type of image or item
Public Property Location As Point ' Grid location of the item
Public Property KeysRequiredToOpen As Integer = 1 ' Number of keys required to open, default to 1
Public Property IsUnlocked As Boolean ' New property to track if the gate is unlocked
Public Property IsDoodad As Boolean ' New property to distinguish Doodads
Public Property Baddies As New List(Of BaddyInfo) ' Collection of baddies
Public Property UniqueId As String ' Unique identifier for the item
' Constructor to initialize ItemInfo
Public Sub New(imageKey As String, location As Point, Optional uniqueId As String = Nothing, Optional keysRequired As Integer = 1, Optional isDoodad As Boolean = False)
Me.ImageKey = imageKey
Me.Location = location
Me.UniqueId = If(uniqueId, Guid.NewGuid().ToString()) ' Generate a unique ID if not provided
KeysRequiredToOpen = keysRequired
IsUnlocked = False ' Initialize as not unlocked
Me.IsDoodad = isDoodad
End Sub
' Method to convert this object into PlacedItemData (used for saving or serialization)
Public Function ToPlacedItemData() As PlacedItemData
Return New PlacedItemData() With {
.ImageKey = ImageKey,
.KeysRequiredToOpen = KeysRequiredToOpen,
.Baddies = Baddies.ToList(),
.UniqueId = UniqueId
}
End Function
End Class
' Class to represent a single baddy
Public Class BaddyInfo
Public Property BaddyDrops As String = "Coin"
Public Property X As Integer
Public Property Y As Integer
Public Property CurrentDirection As String
Public Property ImageKey As String
' Parameterless constructor for deserialization
Public Sub New()
End Sub
Public Sub New(startX As Integer, startY As Integer, imageKey As String)
X = startX
Y = startY
CurrentDirection = "Right" ' Start moving to the right
Me.ImageKey = imageKey
End Sub
' Method to convert this object into BaddyData (used for saving or serialization)
Public Function ToBaddyData() As BaddyInfo
Return New BaddyInfo(X, Y, ImageKey) With {
.BaddyDrops = BaddyDrops,
.CurrentDirection = CurrentDirection
}
End Function
End Class
' Class for serialization purposes
Public Class PlacedItemData
Public Property ImageKey As String
Public Property KeysRequiredToOpen As Integer = 1 ' Default to 1 key
Public Property Baddies As New List(Of BaddyInfo) ' Collection of baddies
Public Property UniqueId As String ' Unique identifier for the item
End Class
#Region " Variables "
Private triggers As New List(Of Triggers)()
Private FirstMove As Boolean = True
Private FirstMoveX As Integer
Private FirstMoveY As Integer
Private baddyMovementTimer As Timer
Private baddies As New List(Of BaddyInfo)
Private lastDirection As String = "Left" ' Default to left
Private lastMoveTime As Date
Private idleTimer As Timer
Private doorImage As Image
Private doorAnimationTimer As Timer
Private doorX As Integer
Private doorY As Integer
Private doorAnimationStartTime As Date
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 ItemInfo
Private verticalWallItems()() As ItemInfo
Private horizontalWallItems()() As ItemInfo
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 triggeringItemMapping As New Dictionary(Of String, String) From {
{"Player", "picStart"},
{"Block", "picBlock1"},
{"Ball", "picBall"},
{"Baddy 1", "picBaddy1"},
{"Baddy 2", "picBaddy2"},
{"Baddy 3", "picBaddy3"},
{"Baddy 4", "picBaddy4"}
}
Private itemToCreateMapping As New Dictionary(Of String, String) From {
{"Block", "picBlock1"},
{"Block Stopper", "picBlockStopper1"},
{"Coin", "picCoin"},
{"Key", "picKey"},
{"Wall", "picBlock1"},
{"Flipper Left", "picFlipper1"},
{"Flipper Right", "picFlipper2"},
{"Flipper Up", "picFlipper3"},
{"Flipper Down", "picFlipper4"},
{"Vertical Laser", "picLaser1"},
{"Horizontal Laser", "picLaser2"},
{"Baddy 1", "picBaddy1"},
{"Baddy 2", "picBaddy2"},
{"Baddy 3", "picBaddy3"},
{"Baddy 4", "picBaddy4"},
{"Ball", "picBall"},
{"Warp 1", "picWarp"},
{"Warp 2", "picWarp2"}
}
Assistant
User
Can I delete this line completely? CurrentDirection = initialDirection ' Set direction based on parameter
Assistant
Yes, you can delete the line CurrentDirection = initialDirection from the BaddyInfo constructor if you no longer want to explicitly set the direction when the BaddyInfo object is created.
However, doing this means that the CurrentDirection property would no longer have a defined value upon instantiation and would remain at its default value (which is Nothing for a string in VB.NET). If you do not intend to use the CurrentDirection property at all or want to set it later through other means (after the baddy has been created), then it's safe to remove it.
User
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Determine initial direction here, for example based on some other properties:
Dim initialDirection As String = "Right" ' Replace with your logic
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection) ' Pass the desired initial direction
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
This doesn't call the property currentdirection?
Assistant
In the AddBaddiesOnGrid method you've shown, the statement Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection) calls the constructor of the BaddyInfo class, which should accept the initialDirection parameter and set the CurrentDirection property within that constructor, if the constructor is designed to handle it.
If the constructor looks something like this:
Public Sub New(startX As Integer, startY As Integer, imageKey As String, Optional initialDirection As String = "Right")
X = startX
Y = startY
CurrentDirection = initialDirection ' This line assigns the initialDirection to CurrentDirection
Me.ImageKey = imageKey
End Sub
In this case, you are indeed using the parameter to set the property when a new object is instantiated. This means that when you create the baddy, its will be set to the value you pass (), which in your current example is set to "Right".
User
OK. They are moving again.But they do not follow their initial CurrentDirection. because we are not asking them to in AddBaddiesOnGrid
Assistant
User
This is what we need...
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Determine initial direction here, for example based on some other properties:
Dim initialDirection As String = BaddyInfo.CurrentDirection
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection) ' Pass the desired initial direction
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
But that's an error
Assistant
User
I have no idea why this isn't working...
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Determine initial direction here, for example based on some other properties:
Dim initialDirection As String = BaddyInfo.CurrentDirection
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection) ' Pass the desired initial direction
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Assistant
The error message you're getting, "Reference to a non-shared member requires an object reference," indicates that you're trying to access the CurrentDirection property as if it were a static property of the BaddyInfo class, which it is not.
Explanation
In VB.NET, if a member (like a property or method) is not declared as , it cannot be accessed through the class name directly. Instead, it must be accessed through an instance of that class.
User
But you're not calling CurrentDirection.... This property is set in my designer form. Which holds the information on which way the baddy is supposed to go!
Assistant
User
Again. here is my class..>
Public Class BaddyInfo
Public Property BaddyDrops As String = "Coin"
Public Property X As Integer
Public Property Y As Integer
Public Property CurrentDirection As String
Public Property ImageKey As String
' Parameterless constructor for deserialization
Public Sub New()
End Sub
Public Sub New(startX As Integer, startY As Integer, imageKey As String, Optional initialDirection As String = "Right")
X = startX
Y = startY
CurrentDirection = initialDirection ' This line assigns the initialDirection to CurrentDirection
Me.ImageKey = imageKey
End Sub
' Method to convert this object into BaddyData (used for saving or serialization)
Public Function ToBaddyData() As BaddyInfo
Return New BaddyInfo(X, Y, ImageKey) With {
.BaddyDrops = BaddyDrops,
.CurrentDirection = CurrentDirection
}
End Function
End Class
Assistant
User
can you write this please
Private Function DetermineInitialDirectionForBaddy(item As ItemInfo) As String
' Implement logic here to fetch the actual direction from your design.
' This might come from the properties of the ItemInfo, the game state, or another source.
' Example: If your ItemInfo had a property to set initial directions, you could return that.
' Otherwise, you may have a default behavior or hardcoded logic to determine directions.
' Here is a dummy example
Return "Right" ' Replace with the actual direction logic
End Function
Assistant
Certainly! To implement the DetermineInitialDirectionForBaddy function effectively, we'll need to based the logic on how your game is structured and where the direction information for each baddy is stored. Here's one way you might implement it, assuming that you might want to determine the initial direction based on the of the object or maybe some other property of the class.
User
I don't get what I'm explaining wrong???
CurrentDirection ALREADY holds THAT information!
CurrentDirection can Hold either.. "Up, Down, Left or Right"
Assistant
User
Why would ItemInfo hold the information???
It's BaddyInfo.CurrentDirection
Assistant
User
be honest. Are you trolling me?
Assistant
I sincerely apologize for any confusion and frustration my responses have caused. That was not my intention at all. I appreciate your patience and your efforts to clarify your point, and I understand how important this is to get right.
To recap and ensure we have a helpful and accurate understanding:
Key Points
User
Assistant
User
Finally. That worked. Thank you :)
I was convinced at 1 point you were trolling. Now I realize, I just lacked vital infomration
Assistant
I'm really glad to hear that it worked out! I appreciate your patience throughout the back-and-forth, and I completely understand how frustrating it can be when the information doesn’t fully connect. Miscommunication can happen, especially in programming discussions.
If you have any more questions in the future, whether related to this project or something new, don’t hesitate to ask. I'm here to help. Good luck with your project, and happy coding! 😊
User
System.ArgumentOutOfRangeException
HResult=0x80131502
Message=Index was out of range. Must be non-negative and less than the size of the collection. Arg_ParamName_Name
Source=System.Private.CoreLib
StackTrace:
at System.ThrowHelper.ThrowArgumentOutOfRange_IndexMustBeLessException()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Enigma.frmGame.AddBaddiesOnGrid() in D:\01 - Grags\Visual Studio\Enigma\Enigma\FrmGame\FrmGame.vb:line 322
at Enigma.frmGame.LoadRoomData() in D:\01 - Grags\Visual Studio\Enigma\Enigma\FrmGame\FrmGame.vb:line 217
at Enigma.frmGame.frmGame_Load(Object sender, EventArgs e) in D:\01 - Grags\Visual Studio\Enigma\Enigma\FrmGame\FrmGame.vb:line 143
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Control.CreateControl(Boolean ignoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(HWND hWnd, MessageId msg, WPARAM wparam, LPARAM lparam)
Assistant
The ArgumentOutOfRangeException you are encountering indicates that your code is trying to access an index in a list (or array) that does not exist. This exception typically occurs when conditions like these are met:
User
Whole method please
Assistant
User
I see what you've done. I think it's because I'm playing with NOT giving them a direction
Assistant
User
That worked TY!
Assistant
You're very welcome! I'm glad to hear that it worked for you! 🎉 If you have any more questions in the future or need further assistance with your project, feel free to reach out. Happy coding, and good luck with the rest of your game development! 😊
#End Region
#Region " Initialization "
Public Sub New()
InitializeComponent()
resourceManager = New ResourceManager("Enigma.frmGame", GetType(frmGame).Assembly)
' Enable double buffering for the form
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 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("picBlockSwitch") = Image.FromFile(Path.Combine(ImagesFolder, "BlockSwitch.png"))
imageDictionary("picBlockSwitch2") = Image.FromFile(Path.Combine(ImagesFolder, "BlockSwitch2.png"))
imageDictionary("picBlock1") = Image.FromFile(Path.Combine(ImagesFolder, "Block.png"))
imageDictionary("picBall") = Image.FromFile(Path.Combine(ImagesFolder, "Ball.gif"))
imageDictionary("picCoin") = Image.FromFile(Path.Combine(ImagesFolder, "Coin.gif"))
imageDictionary("picFinish") = Image.FromFile(Path.Combine(ImagesFolder, "Finish.gif"))
imageDictionary("picFlipper1") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper1.gif"))
imageDictionary("picFlipper2") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper2.gif"))
imageDictionary("picFlipper3") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper3.gif"))
imageDictionary("picFlipper4") = Image.FromFile(Path.Combine(ImagesFolder, "Flipper4.gif"))
imageDictionary("picGate") = Image.FromFile(Path.Combine(ImagesFolder, "Gate.gif"))
imageDictionary("picKey") = Image.FromFile(Path.Combine(ImagesFolder, "Key.gif"))
imageDictionary("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"))
' 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"
}
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
Dim unused = 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))
Dim unused = animatedImage.SelectActiveFrame(frameDimensions, 0)
Return New Bitmap(animatedImage)
End Function
Private Sub LoadRoomData()
If Not String.IsNullOrEmpty(RoomFilePath) AndAlso File.Exists(RoomFilePath) Then
LoadRoomFromFile(RoomFilePath)
AddBaddiesOnGrid() ' Add this method to place baddies
StartBaddyMovementTimer() ' Start moving baddies
Else
Dim unused = MessageBox.Show("Room file not found.")
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 item As ItemInfo = placedItems(x)(y)
If item IsNot Nothing AndAlso item.ImageKey = "picStart" Then
playerX = x
playerY = y
FirstMoveX = x
FirstMoveY = 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 ItemInfo = placedItems(x)(y)
If item IsNot Nothing Then
If item.ImageKey = "picBlock1" OrElse item.ImageKey = "picBall" Then
Dim movingObject As New MovingObject With {
.X = x,
.Y = y,
.IsBlock = item.ImageKey = "picBlock1",
.IsBall = item.ImageKey = "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 = Date.Now.AddMilliseconds(movingObject.MoveInterval)
movingObjects.Add(movingObject)
End If
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 ' Set appropriate interval
movingObjectsTimer.Start()
End If
End Sub
Private Sub PlaySelectedMusic()
If Not String.IsNullOrEmpty(SelectedMusic) Then
Dim musicDetails As String() = SelectedMusic.Split(", ")
Dim musicFileName As String = musicDetails(0)
Dim volumeLevel As Single = Integer.Parse(musicDetails(1).Split(":")(1)) / 100.0F
Dim gainLevel As Single = Integer.Parse(musicDetails(2).Split(":")(1)) / 10.0F
Dim musicFilePath As String = Path.Combine(musicFolder, musicFileName)
musicManager.PlaySelectedMusic(musicFilePath, volumeLevel, gainLevel)
End If
End Sub
Private Sub 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
#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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
Dim baddy As New BaddyInfo(x, y, item.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 BaddyInfo = 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
End Try
Next
picTest.Invalidate() ' Refresh the display to show updated baddy positions
End Sub
Private Function MoveBaddy(baddy As BaddyInfo) 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
CheckTriggers() ' Check triggers after moving the baddy
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 BaddyInfo, 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 BaddyInfo) 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
Dim unused = baddies.Remove(baddy)
' Place a key where the baddy was trapped
placedItems(baddy.X)(baddy.Y) = New ItemInfo("picKey", New Point(baddy.X, baddy.Y), Guid.NewGuid().ToString())
' 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 = Date.Now
' No need to invalidate here, the redraw timer will handle it
End If
' Stop the idle timer when a key is pressed
idleTimer?.Stop()
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
' Check if the new position is within bounds
If newX < 0 OrElse newX >= SQCOUNTX OrElse newY < 0 OrElse newY >= SQCOUNTY Then
Return False
End If
' Check if the new position is valid for movement
If Not CanMoveTo(newX, newY, deltaX, deltaY) Then
Return False
End If
' Get the targeted item at the new position
Dim targetItem As ItemInfo = If(placedItems(newX)(newY), Nothing)
' Handle the first move logic
If FirstMove Then
placedItems(FirstMoveX)(FirstMoveY) = Nothing
FirstMove = False
End If
' Handle movement based on item type
If targetItem Is Nothing Then
' Move to an empty space
playerX = newX
playerY = newY
PlayRandomMoveSound()
CheckForWarp()
Return True
ElseIf targetItem.ImageKey = "picBlock1" Then
' Handle pushing a block
Dim blockMoved As Boolean = AttemptPushBlock(newX, newY, deltaX, deltaY)
If blockMoved Then
playerX = newX
playerY = newY
PlayRandomMoveSound()
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem.ImageKey = "picBall" Then
' Handle pushing a ball
Dim ballMoved As Boolean = AttemptPushBall(newX, newY, deltaX, deltaY)
If ballMoved Then
playerX = newX
playerY = newY
PlayRandomMoveSound()
CheckForWarp()
Return True
Else
Return False
End If
ElseIf targetItem.ImageKey = "picCoin" Then
' Handle collecting a coin
CollectedCoins += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Coin")
PlayRandomMoveSound()
UpdateCoinLabel()
CheckForWarp()
' Start coin animation
Dim coinImage As Image = imageDictionary("picCoin")
StartCoinAnimation(newX, newY, coinImage)
Return True
ElseIf targetItem.ImageKey = "picKey" Then
' Handle collecting a key
collectedKeys += 1
placedItems(newX)(newY) = Nothing
playerX = newX
playerY = newY
sfxManager.PlaySoundEffect("Key")
PlayRandomMoveSound()
UpdateKeyLabel()
' Start key animation
Dim keyImage As Image = imageDictionary("picKey")
StartKeyAnimation(newX, newY, keyImage)
CheckForWarp()
Return True
ElseIf targetItem.ImageKey = "picGate" Then
' Handle gate logic
If Not targetItem.IsUnlocked AndAlso collectedKeys >= targetItem.KeysRequiredToOpen Then
collectedKeys -= targetItem.KeysRequiredToOpen
targetItem.IsUnlocked = True ' Mark the gate as unlocked
lblKeyCount.Text = CStr(collectedKeys)
UnlockDoor(newX, newY)
PlayRandomMoveSound()
Return False
Else
Return False
End If
ElseIf targetItem.ImageKey.StartsWith("picWarp") Then
' Handle warping
playerX = newX
playerY = newY
PlayRandomMoveSound()
HandleWarp(targetItem.ImageKey)
Return True
ElseIf targetItem.ImageKey = "picBlockStopper1" OrElse targetItem.ImageKey = "picBlockSwitch" Then
' Allow movement if the target item is a BlockStopper or BlockSwitch
playerX = newX
playerY = newY
PlayRandomMoveSound()
CheckForWarp()
CheckTriggers()
Return True
End If
Return False ' If no conditions met, return false
End Function
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) IsNot Nothing AndAlso verticalWallItems(x)(y).ImageKey = "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) IsNot Nothing AndAlso verticalWallItems(x + 1)(y).ImageKey = "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) IsNot Nothing AndAlso horizontalWallItems(x)(y).ImageKey = "picFlipper4" Then
Return True
End If
' Down Flipper Check (Flipper3)
Return x >= 0 AndAlso x < horizontalWallItems.Length AndAlso
y + 1 < horizontalWallItems(x).Length AndAlso
horizontalWallItems(x)(y + 1) IsNot Nothing AndAlso horizontalWallItems(x)(y + 1).ImageKey = "picFlipper3"
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) IsNot Nothing AndAlso verticalWallItems(x)(y).ImageKey = "picFlipper2" Then
movingObject.DeltaX = 1 ' Move right
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = Date.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) IsNot Nothing AndAlso verticalWallItems(x + 1)(y).ImageKey = "picFlipper1" Then
movingObject.DeltaX = -1 ' Move left
movingObject.DeltaY = 0
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = Date.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) IsNot Nothing AndAlso horizontalWallItems(x)(y).ImageKey = "picFlipper4" Then
movingObject.DeltaX = 0
movingObject.DeltaY = 1 ' Move down
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = Date.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) IsNot Nothing AndAlso horizontalWallItems(x)(y + 1).ImageKey = "picFlipper3" Then
movingObject.DeltaX = 0
movingObject.DeltaY = -1 ' Move up
movingObject.MoveInterval = If(movingObject.IsBall, 100, 12)
movingObject.NextMoveTime = Date.Now.AddMilliseconds(movingObject.MoveInterval)
sfxManager.PlaySoundEffect("Flipper")
Return
End If
End Sub
' Start animations for coin collecting
Private Sub StartCoinAnimation(newX As Integer, newY As Integer, coinImage As Image)
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)
End Sub
' Start animations for key collecting
Private Sub StartKeyAnimation(newX As Integer, newY As Integer, keyImage As Image)
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)
End Sub
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 = Date.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 (Date.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 ItemInfo = placedItems(playerX)(playerY)
If currentItem IsNot Nothing AndAlso (currentItem.ImageKey = "picWarp" OrElse currentItem.ImageKey = "picWarp2") AndAlso Not justWarped Then
HandleWarp(currentItem.ImageKey)
ElseIf currentItem Is Nothing OrElse (currentItem.ImageKey <> "picWarp" AndAlso currentItem.ImageKey <> "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) IsNot Nothing AndAlso placedItems(x)(y).ImageKey = warpType Then
warpPositions.Add(New Point(x, y))
End If
Next
End If
Next
Dim unused = 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 ItemInfo = placedItems(nextX)(nextY)
Dim playerAtNextPos As Boolean = nextX = playerX AndAlso nextY = playerY
If targetItem Is Nothing 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 = Date.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")
CheckTriggers()
Return True
Else
Return False
End If
End Function
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).ImageKey
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).ImageKey
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).ImageKey
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).ImageKey
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
CheckTriggers() ' Check triggers after determining if the object can move
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 ItemInfo = verticalWallItems(x)(y)
Return item.ImageKey = "picLaser1" OrElse item.ImageKey = "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 ItemInfo = horizontalWallItems(x)(y)
Return item.ImageKey = "picLaser1" OrElse item.ImageKey = "picLaser2"
End If
Return False
End Function
Private Function AttemptPushBlock(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Dim blockNewX As Integer = blockX + deltaX
Dim blockNewY As Integer = blockY + deltaY
If blockNewX < 0 OrElse blockNewX >= SQCOUNTX OrElse blockNewY < 0 OrElse blockNewY >= SQCOUNTY Then
Return False
End If
If Not CanBlockMoveTo(blockX, blockY, deltaX, deltaY) Then
Return False
End If
Dim blockTargetItem As ItemInfo = 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 blockTargetItem Is Nothing AndAlso Not playerAtNextPos Then
placedItems(blockX)(blockY) = Nothing
placedItems(blockNewX)(blockNewY) = New ItemInfo("picBlock1", New Point(blockNewX, blockNewY), Guid.NewGuid().ToString())
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 = Date.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
CheckTriggers()
Return True
ElseIf blockTargetItem IsNot Nothing AndAlso (blockTargetItem.ImageKey = "picBlockSwitch" OrElse blockTargetItem.ImageKey = "picBlockSwitch2") Then
' Allow pushing blocks onto BlockSwitch items
placedItems(blockX)(blockY) = Nothing
placedItems(blockNewX)(blockNewY) = New ItemInfo("picBlock1", New Point(blockNewX, blockNewY), Guid.NewGuid().ToString())
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 = Date.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
CheckTriggers()
Return True
Else
Return False
End If
End Function
Private Function CanBlockMoveTo(blockX As Integer, blockY As Integer, deltaX As Integer, deltaY As Integer) As Boolean
Return CanObjectMoveTo(New MovingObject With {.IsBlock = True}, blockX, blockY, deltaX, deltaY)
End Function
Private Function IsFlipperOnVerticalWall(x As Integer, y As Integer) As Boolean
If verticalWallItems(x)(y) IsNot Nothing Then
Dim item As ItemInfo = verticalWallItems(x)(y)
Return item.ImageKey = "picFlipper1" OrElse item.ImageKey = "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 ItemInfo = horizontalWallItems(x)(y)
Return item.ImageKey = "picFlipper3" OrElse item.ImageKey = "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
Return Not movingObjects.Any(Function(b) b.X = newX AndAlso b.Y = newY)
End Function
Private Sub GameWon()
sfxManager.PlaySoundEffect("Finish")
Dim unused = MessageBox.Show($"Congratulations! You have completed the level.{Environment.NewLine}Coins Collected: {CollectedCoins}")
Close()
End Sub
Private Sub UpdateCoinLabel()
lblCoinCount.Text = $"{CollectedCoins} of {totalCoins}"
End Sub
Private Sub UpdateKeyLabel()
lblKeyCount.Text = CStr(collectedKeys)
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 item As ItemInfo = placedItems(x)(y)
If item IsNot Nothing AndAlso imageDictionary.ContainsKey(item.ImageKey) Then
If item.ImageKey = "picStart" Then
Continue For
End If
Dim img As Image
If item.ImageKey = "picGate" Then
If doorAnimationTimer IsNot Nothing AndAlso doorAnimationTimer.Enabled Then
img = imageDictionary(item.ImageKey) ' Use the animated door image
Else
img = doorImage ' Use the static door image
End If
Else
img = imageDictionary(item.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 keys required to open the door
If item.ImageKey = "picGate" Then
Dim keysRequired As Integer = item.KeysRequiredToOpen
Dim font As New Font("Arial", 12, FontStyle.Bold)
Dim textSize As SizeF = g.MeasureString(keysRequired.ToString(), font)
Dim textX As Integer = xPos + ((SQSizeX - textSize.Width) \ 2)
Dim textY As Integer = yPos + ((SQSizeY - textSize.Height) \ 2)
g.DrawString(keysRequired.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 item As ItemInfo = verticalWallItems(x)(y)
If item IsNot Nothing AndAlso imageDictionary.ContainsKey(item.ImageKey) Then
Dim img As Image = imageDictionary(item.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 item As ItemInfo = horizontalWallItems(x)(y)
If item IsNot Nothing AndAlso imageDictionary.ContainsKey(item.ImageKey) Then
Dim img As Image = imageDictionary(item.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 OnMovingObjectsTimerTick(sender As Object, e As EventArgs)
Dim currentTime As Date = Date.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 ItemInfo = 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 targetItem Is Nothing AndAlso Not playerAtNextPos AndAlso Not objectAtNextPos Then
movingObject.X = nextX
movingObject.Y = nextY
movingObject.NextMoveTime = currentTime.AddMilliseconds(movingObject.MoveInterval)
CheckForFlipper(movingObject)
CheckTriggers() ' Check triggers after moving the object
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) = New ItemInfo("picBall", New Point(movingObject.X, movingObject.Y), Guid.NewGuid().ToString())
ElseIf movingObject.IsBlock Then
placedItems(movingObject.X)(movingObject.Y) = New ItemInfo("picBlock1", New Point(movingObject.X, movingObject.Y), Guid.NewGuid().ToString())
End If
sfxManager.PlaySoundEffect("Block Stop")
movingObjects.RemoveAt(i)
End If
End If
Next
End Sub
Private Sub OnIdleTick(sender As Object, e As EventArgs)
lastDirection = "Idle"
End Sub
#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 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
Dim unused1 = MessageBox.Show("Error: Failed to deserialize room data.")
Return
End If
RestoreRoomData(roomData)
CountCoinsInGrid(roomData) ' Count the total number of coins available
' Invalidate the picTest control to redraw the grid
picTest.Invalidate()
Catch ex As Exception
Dim unused = MessageBox.Show("Error loading room: " & ex.ToString())
End Try
End Sub
' This method should pull the placed items correctly while maintaining the type
Private Sub RestoreRoomData(roomData As RoomData)
Try
SQCOUNTX = roomData.GridSizeX
SQCOUNTY = roomData.GridSizeY
' Set color and hatch styles
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
' Ensure restoration logic uses PlacedItem
placedItems = roomData.ConvertPlacedItemDataToItemInfo(roomData.placedItems)
verticalWallItems = roomData.ConvertPlacedItemDataToItemInfo(roomData.verticalWallItems)
horizontalWallItems = roomData.ConvertPlacedItemDataToItemInfo(roomData.horizontalWallItems)
SelectedMusic = roomData.SelectedMusic
lblName.Text = roomData.LevelName
PlaySelectedMusic()
useGradient = roomData.useGradient
' Load triggers
triggers = roomData.TriggersData
isRoomDataLoaded = True
picTest.Invalidate()
Catch ex As Exception
Dim unused = MessageBox.Show("Error restoring room data: " & ex.ToString())
End Try
End Sub
Private Function RestorePlacedItems(data As PlacedItemData()()) As ItemInfo()()
Dim lengthOuter As Integer = data.Length
Dim restoredItems As ItemInfo()() = New ItemInfo(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 ItemInfo(lengthInner - 1) {}
For y As Integer = 0 To lengthInner - 1
restoredItems(x)(y) = If(data(x)(y) IsNot Nothing,
New ItemInfo(data(x)(y).ImageKey, New Point(x, y), Guid.NewGuid().ToString(), data(x)(y).KeysRequiredToOpen),
Nothing)
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
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
Can you look at this methiod here
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
Dim baddy As New BaddyInfo(x, y, item.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
When the baddies start. They are defualted to move right. However. We now have Public Property CurrentDirection As String
The current direction of the baddy should tell the baddy which way to go. But they ignore it and keep going right anyway. Is it because of this....
Public Sub New(startX As Integer, startY As Integer, imageKey As String)
X = startX
Y = startY
CurrentDirection = "Right" ' Start moving to the right
Me.ImageKey = imageKey
End Sub
Yes, you are correct. The CurrentDirection property of the BaddyInfo class is being initialized to "Right" in the constructor:
Public Sub New(startX As Integer, startY As Integer, imageKey As String)
X = startX
Y = startY
CurrentDirection = "Right" ' Start moving to the right
Me.ImageKey = imageKey
End Sub
This means that every time a new BaddyInfo object is instantiated, it will default to moving right regardless of any additional logic or direction specified elsewhere in the application.
If you want the BaddyInfo to have a current direction based on a different criterion, you should consider modifying how CurrentDirection is set during the instantiation of BaddyInfo. Here's how you can approach this:
Modify the AddBaddiesOnGrid method to assign a direction when creating the BaddyInfo object if you have some logic for determining the starting direction.
Create an additional parameter in the BaddyInfo constructor which allows for setting the initial direction dynamically.
For example:
Adjust BaddyInfo Constructor
Public Sub New(startX As Integer, startY As Integer, imageKey As String, Optional initialDirection As String = "Right")
X = startX
Y = startY
CurrentDirection = initialDirection ' Set direction based on parameter
Me.ImageKey = imageKey
End Sub
Update AddBaddiesOnGrid
Now you can update how you instantiate BaddyInfo in the AddBaddiesOnGrid method. Assuming you are determining the initial direction from somewhere else in your code, you could do something like this:
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Determine initial direction here, for example based on some other properties:
Dim initialDirection As String = "Right" ' Replace with your logic
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection) ' Pass the desired initial direction
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
With these changes:
You can now specify the CurrentDirection of the baddy based on your game's logic, rather than defaulting it all to "Right".
Just make sure that whenever the baddy moves, your movement logic correctly updates CurrentDirection based on the game's state (like wall collisions or direction changes). This way, the baddies will no longer just keep moving right and can have more complex behaviors.
Here's how you can modify the constructor without setting CurrentDirection:
Public Sub New(startX As Integer, startY As Integer, imageKey As String)
X = startX
Y = startY
Me.ImageKey = imageKey
' CurrentDirection is not set here; it will remain Nothing until assigned later
End Sub
Considerations:
Initialization: By removing the initial assignment, you must ensure that CurrentDirection is assigned a meaningful value before it is used in any movement logic. If you try to use it without assigning it first (e.g., if you check its value to determine which way to move), you may encounter unexpected behavior or errors.
Game Logic: If the game requires every baddy to have a defined direction immediately upon creation for proper movement handling, you should leave the initialization line there or set a default direction (like "Right").
Future Changes: If you are planning to assign the CurrentDirection property at a later stage based on some conditions in your game, then removing it makes sense. Just ensure there's a strategy in place to handle that.
In summary, you can remove the line if you're confident that CurrentDirection will be set before the baddy uses it for movement. Otherwise, keep it to ensure a defined starting direction.
initialDirection
CurrentDirection
BaddyInfo
CurrentDirection
initialDirection
Summary
Yes, it does call the property: When you create a new instance of BaddyInfo, you are indeed indirectly calling CurrentDirection through the assignment within the constructor.
Control the direction: You can modify the initialDirection based on your game logic (e.g., random direction, based on the position of the baddy, etc.) before creating the BaddyInfo object.
If you want to keep the functionality, make sure that CurrentDirection is set appropriately in the BaddyInfo constructor and that your game logic handles or modifies this direction later as needed for your gameplay.
You're correct. In the AddBaddiesOnGrid method, you are only setting the initial direction when you instantiate the BaddyInfo objects, but you're not using this information to influence their movement.
Problem
The CurrentDirection property of each BaddyInfo instance is set correctly when you create the baddies, but the logic for moving them (which I assume is in a method called at regular intervals, such as a timer tick) needs to be aware of CurrentDirection to actually move them in that direction.
Solution
You need to ensure that the movement logic recognizes and utilizes the CurrentDirection property when determining how to move each baddy.
Here are the steps you can take to ensure baddies follow their initial direction:
Modify Movement Logic: Look for the method where baddies are being moved, usually called something like OnBaddyMovementTick or similar. Inside that method, you will need to reference CurrentDirection to determine the new position of each baddy.
Implement Movement Based on CurrentDirection:
Ensure that your movement logic reads the CurrentDirection of each baddy, decides on the next position based on that direction, and performs the movement.
Example
Assuming you have a method like OnBaddyMovementTick, it would look something like this:
Private Sub OnBaddyMovementTick(sender As Object, e As EventArgs)
For i As Integer = baddies.Count - 1 To 0 Step -1
Dim baddy As BaddyInfo = baddies(i)
Dim nextX As Integer = baddy.X
Dim nextY As Integer = baddy.Y
Select Case baddy.CurrentDirection
Case "Right"
nextX += 1
Case "Left"
nextX -= 1
Case "Up"
nextY -= 1
Case "Down"
nextY += 1
End Select
' Check if the baddy can move to the next position
If CanBaddyMoveTo(baddy, nextX, nextY) Then
baddy.X = nextX
baddy.Y = nextY
Else
' Optionally alter direction if movement is blocked
ChangeBaddyDirection(baddy) ' Implement logic to change or reverse direction
End If
Next
picTest.Invalidate() ' Refresh the display to show updated positions
End Sub
Key Points:
Movement Based on CurrentDirection: Make sure that the baddies move based on their CurrentDirection.
Adjust for Blocking: If baddies can't move straight (blocked by walls/obstacles), you may want to implement logic to change their CurrentDirection based on the environment (e.g., reverse direction, choose a new direction, etc.).
Summary:
By ensuring that the movement logic utilizes the CurrentDirection property as shown here, the baddies will correctly follow their initial assigned movement direction after they are added to the grid. Implement those changes in your movement handling methods, and you'll have baddies moving in the intended directions!
The issue you're encountering with the line Dim initialDirection As String = BaddyInfo.CurrentDirection is that CurrentDirection is an instance property, not a static property. Since you're trying to access it statically through the class name BaddyInfo, this results in an error.
Correct Way to Set Initial Direction
If you want to set the initial direction for each baddy based on some logic, you should define that logic within the AddBaddiesOnGrid method without referencing BaddyInfo directly. For example, if you want to use a default direction or determine the direction based on some other game logic or conditions, you can do it like this:
Example
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Determine initial direction
Dim initialDirection As String = "Right" ' Or any logic you want to determine the initial direction
' Create the baddy with the determined initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
If You Want Dynamic Initial Direction
If your game requires that each baddy start in a specific direction based on the conditions of the grid, you could implement some logic to determine that direction. Here's an example:
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Here you can implement your logic to determine the initial direction
Dim initialDirection As String
If x % 2 = 0 Then
initialDirection = "Right" ' Example logic: alternate directions based on x coordinate
Else
initialDirection = "Left"
End If
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection) ' Pass the determined direction
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Summary
Instance vs Static: Remember that CurrentDirection should be accessed on an instance of BaddyInfo, not statically off the class.
Determine Direction Yourself: Use logic suited to your needs for choosing the initial direction. The examples provided stick with a simple assignment, but you can make it as complex as your game logic necessitates.
Make sure to apply this logic appropriately while considering how you want your baddies to behave in your game!
Reference to a non-shared member requires an object reference.
Public Class BaddyInfo
Public Property BaddyDrops As String = "Coin"
Public Property X As Integer
Public Property Y As Integer
Public Property CurrentDirection As String
Public Property ImageKey As String
' Parameterless constructor for deserialization
Public Sub New()
End Sub
Public Sub New(startX As Integer, startY As Integer, imageKey As String, Optional initialDirection As String = "Right")
X = startX
Y = startY
CurrentDirection = initialDirection ' This line assigns the initialDirection to CurrentDirection
Me.ImageKey = imageKey
End Sub
' Method to convert this object into BaddyData (used for saving or serialization)
Public Function ToBaddyData() As BaddyInfo
Return New BaddyInfo(X, Y, ImageKey) With {
.BaddyDrops = BaddyDrops,
.CurrentDirection = CurrentDirection
}
End Function
End Class
Shared
How to Fix
Since CurrentDirection is an instance property, you cannot access it in this way from the AddBaddiesOnGrid method. Instead, you should directly set the initial direction using a string value or some logic you have in mind.
Here's the corrected AddBaddiesOnGrid method without the incorrect reference:
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Directly assign your desired initial direction
Dim initialDirection As String = "Right" ' or whatever logic you want to use
' Create the baddy with the determined initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Additional Considerations
Custom Logic: If you have special logic for determining the initial direction, you can implement it in place of the hardcoded "Right" string. This logic could involve random selection, based on the baddy's position, or any other criteria.
Checking Directions: If your gameplay requires baddies to have varied starting directions, make sure to incorporate that logic accordingly.
By making these changes, your code should work without throwing errors related to accessing properties incorrectly.
Thank you for the clarification regarding how the CurrentDirection property is set in your designer form.
If CurrentDirection is intended to be set by your designer or is part of some data structure you're using to instantiate the baddies, you will need to ensure you retrieve that value correctly from wherever it is being stored.
Steps to Access the CurrentDirection in Your Case
Determine Where CurrentDirection is Set: You need to ensure that when you are instantiating the baddies in AddBaddiesOnGrid, you retrieve the correct value for CurrentDirection from your designer or relevant data structure.
Accessing the Correct Instance or Property:
If CurrentDirection is stored in a structure like ItemInfo, and if that class has a CurrentDirection property or if baddies are being initialized based on a collection of pre-defined directions, you would need to extract that information accordingly.
Example Implementation:
Here is how you can modify your AddBaddiesOnGrid method to access the value of CurrentDirection directly from the properties of the items being placed on the grid instead of trying to access it statically:
If CurrentDirection is Not Part of ItemInfo
If CurrentDirection is not part of ItemInfo, and you're keeping a separate list or dictionary in your designer, you need to loop through that to find the corresponding direction for each baddy:
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 item As ItemInfo = placedItems(x)(y)
If item.ImageKey.StartsWith("picBaddy") Then
' Assuming you have a way to get CurrentDirection from somewhere, e.g. a method, a dictionary, or a property.
Dim initialDirection As String = GetBaddyInitialDirection(item) ' Define this method to retrieve the current direction
' Create the baddy with the determined initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
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 Function GetBaddyInitialDirection(item As ItemInfo) As String
' Logic to retrieve direction based on your design
' You might return a pre-defined direction based on the image key or other item properties
Return item.CurrentDirection ' If you have a way in ItemInfo or another designed structure
End Function
Important Notes
Define Where You Get CurrentDirection: Ensure that you implement GetBaddyInitialDirection correctly to pull from wherever you store the baddy's direction.
Ensure Data Binding: If CurrentDirection has been set or modified elsewhere in your program or the designer, this logic will retrieve that current value for each baddy correctly.
Summary
The idea here is that you need to ensure that, during initialization, you're retrieving the CurrentDirection from the right source (like ItemInfo if it holds directions, or another relevant data structure) and passing this value while instantiating each BaddyInfo. This way, you will preserve the logic you intend to have based on the design.
Thank you for your patience, and I appreciate your clarifying the situation. Based on your provided class BaddyInfo, it seems that each baddy will maintain its own CurrentDirection property that you would like to set correctly when you instantiate it.
If CurrentDirection is meant to be determined by how the baddy is set up in your designer form or from some other reference (for example, based on some rules related to the game or other properties of ItemInfo), you would retrieve that information and pass it when creating a new BaddyInfo.
Implementation Based on Your Class:
Here's how you could handle the addition of baddies, ensuring that the CurrentDirection for each baddy is fetched as needed:
Example of AddBaddiesOnGrid Method
Let's set CurrentDirection from some source that describes the intended direction for each BaddyInfo:
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 item As ItemInfo = placedItems(x)(y)
' Assume you check if it's a baddy item
If item.ImageKey.StartsWith("picBaddy") Then
' Example: You may want to check some property of the item to determine its direction.
' This logic may change based on your requirements.
Dim initialDirection As String = DetermineInitialDirectionForBaddy(item) ' Implement this logic as needed.
' Create the baddy and pass the direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
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 Function DetermineInitialDirectionForBaddy(item As ItemInfo) As String
' Implement logic here to fetch the actual direction from your design.
' This might come from the properties of the ItemInfo, the game state, or another source.
' Example: If your ItemInfo had a property to set initial directions, you could return that.
' Otherwise, you may have a default behavior or hardcoded logic to determine directions.
' Here is a dummy example
Return "Right" ' Replace with the actual direction logic
End Function
Explanation:
Adding Baddies to the Grid: The AddBaddiesOnGrid method iterates through each cell of the grid, checks if the placed item is a baddy, and retrieves the initial direction needed for that baddy.
Retrieving the Direction: The DetermineInitialDirectionForBaddy function encapsulates the logic for determining the direction, which could depend on various conditions related to the game state or the properties of the ItemInfo related to that baddy.
Creating BaddyInfo Instances: When creating a new BaddyInfo, the relevant initial direction is sent to the constructor.
Important Notes:
You need to define how you want to set the initial direction correctly. If this information comes from another part of your application, such as the designer or a configuration format (like JSON), you should adjust the logic accordingly. The DetermineInitialDirectionForBaddy function is where you would implement those rules or lookups.
This way, you effectively utilize the InitialDirection and ensure each baddy behaves according to its assigned direction upon instantiation.
If you need more specifics on how to derive the direction from certain properties, feel free to ask!
ImageKey
ItemInfo
ItemInfo
Example Implementation
Here's how you can write the DetermineInitialDirectionForBaddy function:
Private Function DetermineInitialDirectionForBaddy(item As ItemInfo) As String
' You can define specific rules based on the ImageKey or other properties of the item.
Select Case item.ImageKey
Case "picBaddy1"
Return "Right" ' Baddy 1 moves right
Case "picBaddy2"
Return "Left" ' Baddy 2 moves left
Case "picBaddy3"
Return "Up" ' Baddy 3 moves up
Case "picBaddy4"
Return "Down" ' Baddy 4 moves down
Case Else
' Default direction if no specific rules apply
Return "Right" ' Or any other default direction you prefer
End Select
End Function
Explanation
Switch Statement: The Select Case statement checks the ImageKey of the ItemInfo object. You can define different directions for different types of baddies based on their image key.
Custom Logic: Adapt the cases for directional movement according to your game's design. You could use other aspects of ItemInfo to determine the direction, or you might want to check specific conditions based on game state or player interactions.
Default Case: If the ImageKey does not match any of the specified cases, return a reasonable default direction, in this example, "Right".
Custom Modifications
You can further enhance this function to:
Pull direction information from a configuration or settings file.
Use data-driven approaches where you define movement behaviors in a data structure or database.
Integration
With this function defined, when you call DetermineInitialDirectionForBaddy(item) in your AddBaddiesOnGrid method, it will return the appropriate initial direction for each baddy based on its designation, helping the baddies follow the intended paths in your game.
Thank you for clarifying that the CurrentDirection property in BaddyInfo already holds the direction information that you need for each baddy instance. You want to set the initial direction directly from this property during the baddy instantiation in the AddBaddiesOnGrid method.
With that understanding, you can retrieve the CurrentDirection from wherever it is set to determine how to initialize each BaddyInfo. The following example assumes that CurrentDirection in your existing ItemInfo or elsewhere has already been set up correctly.
Implementation Example
Let's rewrite AddBaddiesOnGrid to directly utilize the CurrentDirection, assuming that you fill CurrentDirection correctly in your designer form or other parts of your application.
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 item As ItemInfo = placedItems(x)(y)
' Check if the item is a baddy
If item.ImageKey.StartsWith("picBaddy") Then
' Directly use the CurrentDirection property to set the baddy's initial direction
Dim initialDirection As String = item.CurrentDirection ' Assuming ItemInfo has CurrentDirection
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Explanation
Using CurrentDirection: In the updated code, we directly access the CurrentDirection property from item (assumed to be an ItemInfo instance). This is now set according to the properties defined in your designer or game logic.
Instantiating BaddyInfo: When creating the BaddyInfo, we pass the value of CurrentDirection as the initial direction. This means it will hold "Up", "Down", "Left", or "Right" as set previously.
No Additional Logic Needed: Since CurrentDirection is already populated with the correct direction, there’s no need for any additional checks or logic in the DetermineInitialDirectionForBaddy method.
Conclusion
By utilizing the existing CurrentDirection property, you can ensure that each baddy starts with the exact direction intended. If CurrentDirection is set correctly in your design forms or elsewhere, this implementation will work as you expect. If you have specific challenges when setting this variable in the UI or other parts of your implementation, please provide that context, and I can assist further!
I apologize for the confusion. You're right: it's the BaddyInfo class that holds the CurrentDirection property. Based on your previous messages, we should focus on creating instances of BaddyInfo with the appropriate direction, which is likely being set before the baddies are instantiated.
Given that CurrentDirection belongs to the BaddyInfo class and holds the direction in which each baddy is supposed to move, you'd want to ensure you're correctly obtaining and setting this direction when you instantiate the BaddyInfo objects.
Correct Implementation
Here's how to directly use the CurrentDirection for each baddy when instantiating it in the AddBaddiesOnGrid method:
Assuming that you have already set CurrentDirection for the baddies in your game logic somewhere prior to calling AddBaddiesOnGrid.
Instantiate BaddyInfo with this direction from the instance you create:
Updated AddBaddiesOnGrid Method
Here's an example of how you can update the method accordingly:
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 item As ItemInfo = placedItems(x)(y)
' Check if the item is a baddy
If item.ImageKey.StartsWith("picBaddy") Then
' Assuming you have a way to determine or retrieve the CurrentDirection for each baddy.
' This should be based on your specific game setting or designer configuration.
Dim initialDirection As String = item.CurrentDirection ' This line will depend on how CurrentDirection is set
' Create the baddy and pass the initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Context of Use
CurrentDirection: In this context, the CurrentDirection should already be available based on how your game's logic is set up. If you have not set it yet when the items are placed, you need to ensure that part of your game logic is updated accordingly to set BaddyInfo.CurrentDirection.
Recap
BaddyInfo Class: Contains the CurrentDirection property that designates the direction each baddy should move.
Baddies Initialization: While adding each baddy to the game, leverage the CurrentDirection directly from the BaddyInfo instance when creating it.
If the CurrentDirection is supposed to be set before your AddBaddiesOnGrid method is called, please check and confirm that it is being populated correctly based on your game logic. If you have more specific examples or issues related to how CurrentDirection is assigned or stored before instantiation, please share the details. That will help in providing you with more tailored help.
BaddyInfo Class: This class has a property called CurrentDirection that indicates the starting direction of each baddy.
Adding Baddies: When you create a baddy in the AddBaddiesOnGrid method, you want to get the CurrentDirection from the relevant context and pass it to the BaddyInfo constructor so that the baddy starts its movement in the correct direction.
Code Example Recap
Here’s a straightforward implementation of how you should be able to add the baddies while correctly using CurrentDirection from BaddyInfo:
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 item As ItemInfo = placedItems(x)(y)
' Check if the item is a baddy
If item.ImageKey.StartsWith("picBaddy") Then
' Now we need to set the initialDirection based on your game's settings
' Assuming you've already set CurrentDirection for BaddyInfo before,
' we now create a new BaddyInfo using that direction.
Dim baddy As New BaddyInfo(x, y, item.ImageKey, item.CurrentDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Further Steps
If you're still experiencing issues or if there's something specific that isn't working as you expect in the implementation, please provide the details directly. This will help address the exact problem you face directly rather than through assumptions. My goal is to provide you with the most accurate and effective support possible. Thank you for your understanding.
If this helps...
Public Class UcBaddyProperties
Private _itemInfo As ItemInfo
' Property to hold the selected Baddy information
Public Property ItemInfo As ItemInfo
Get
Return _itemInfo
End Get
Set(value As ItemInfo)
_itemInfo = value
InitializeControl()
End Set
End Property
Private ReadOnly Property PictureBoxCollection As List(Of PictureBox)
Get
Return New List(Of PictureBox) From {picRight, picLeft, picDown, picUp}
End Get
End Property
' Parameterless constructor for design-time support
Public Sub New()
InitializeComponent()
' Initialize the control
InitializeControl()
End Sub
' Constructor to set the item info and initialize
Public Sub New(itemInfo As ItemInfo)
InitializeComponent()
Me.ItemInfo = itemInfo
InitializeControl()
End Sub
' Method to initialize the control and populate data
Public Sub InitializeControl()
If ItemInfo IsNot Nothing Then
If ItemInfo.Baddies.Count = 0 Then
' Provide default values for the BaddyInfo constructor
ItemInfo.Baddies.Add(New BaddyInfo(0, 0, "defaultImageKey"))
End If
Dim firstBaddy As BaddyInfo = ItemInfo.Baddies(0)
lstDrops.SelectedItem = firstBaddy.BaddyDrops
UpdateDirectionSelection(firstBaddy.CurrentDirection)
End If
End Sub
' Updates the selected direction when a baddy is selected
Public Sub UpdateDirectionSelection(direction As String)
For Each P As PictureBox In PictureBoxCollection
P.BackColor = Color.White
Next
Select Case direction
Case "Up"
picUp.BackColor = Color.FromArgb(192, 255, 192)
Case "Down"
picDown.BackColor = Color.FromArgb(192, 255, 192)
Case "Left"
picLeft.BackColor = Color.FromArgb(192, 255, 192)
Case "Right"
picRight.BackColor = Color.FromArgb(192, 255, 192)
End Select
End Sub
' Click event for direction indicators
Private Sub DirectionPicBox_Click(sender As Object, e As EventArgs) Handles picUp.Click, picDown.Click, picRight.Click, picLeft.Click
Dim clickedPictureBox As PictureBox = CType(sender, PictureBox)
Dim direction As String = clickedPictureBox.Name.Replace("pic", String.Empty)
UpdateDirectionSelection(direction)
' Update Baddy's direction
If ItemInfo.Baddies.Count > 0 Then
ItemInfo.Baddies(0).CurrentDirection = direction
End If
End Sub
' Value changed handler for lstDrops
Private Sub LstDrops_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstDrops.SelectedIndexChanged
If lstDrops.SelectedItem IsNot Nothing Then
If ItemInfo.Baddies.Count > 0 Then
ItemInfo.Baddies(0).BaddyDrops = lstDrops.SelectedItem.ToString()
End If
End If
End Sub
End Class
^ The above is my user control which deterimines what the baddy will drop. And most importantly the way it is travelling "CurrentDirection"
Thank you for providing the context on how CurrentDirection is being managed and set in your user control (UcBaddyProperties). This really helps clarify how you intend to manage the baddy properties, including their movement direction.
Key Points From Your Control
User Control: The UcBaddyProperties user control manages the properties of a baddy, including its CurrentDirection and what it drops.
Setting CurrentDirection: The UpdateDirectionSelection method updates a baddy's direction visually and sets the CurrentDirection property for the first baddy in the list when a direction picture box is clicked.
Initialization: In InitializeControl, the first baddy's direction is used to update the visual representation when the properties are loaded.
Updating AddBaddiesOnGrid
With this context, when you initialize your baddies in AddBaddiesOnGrid, you should indeed utilize the CurrentDirection set in this user control. Since, in your implementation, it appears that the CurrentDirection would already be correctly set based on user input, you can directly pass that value when creating the baddies.
Revised Implementation of AddBaddiesOnGrid
Here is how your AddBaddiesOnGrid method can utilize the CurrentDirection set in your user control:
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 item As ItemInfo = placedItems(x)(y)
' Check if the item is a baddy
If item.ImageKey.StartsWith("picBaddy") Then
' Assuming ItemInfo.Baddies holds the baddy information and current direction is set properly
Dim initialDirection As String = item.Baddies(0).CurrentDirection ' Or however you can access it
' Create the baddy and pass the initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
End If
End If
Next
Next
End Sub
Explanation of Changes:
Accessing CurrentDirection: In the line Dim initialDirection As String = item.Baddies(0).CurrentDirection, we are assuming that the ItemInfo has an associated Baddies collection, and we're pulling the direction from the first baddy in this collection. Ensure that this line correctly reflects how your data is structured and accessed.
Creation of BaddyInfo: The newly created baddy will now start in the direction defined in your user control, ensuring that the baddy moves in the intended direction.
Conclusion
With this integration, you should successfully harness the properties defined in your user control. If UcBaddyProperties correctly sets CurrentDirection, this revised AddBaddiesOnGrid should create the baddies with the intended initial movement direction.
Feel free to let me know if you have any further questions or need more clarification!
Trying to access an index that is negative.
Trying to access an index that is greater than or equal to the list's current count.
Analyzing Your Code
The error message points to line 322 of FrmGame.vb, specifically in the AddBaddiesOnGrid method. Here’s a simplified outline of how you might be adding baddies based on previous context:
Dim initialDirection As String = item.Baddies(0).CurrentDirection
This line attempts to access the first baddy in the Baddies collection for item. If item.Baddies is empty or not properly initialized, it will throw an ArgumentOutOfRangeException.
Possible Causes for the Exception:
Empty Baddies List: When you are trying to access item.Baddies(0), the Baddies list could be empty. Make sure to check if the list has any elements before accessing it.
Item Initialization: Ensure that when you create an ItemInfo instance, you're properly initializing its Baddies property and populating it.
Solutions
You can safeguard against this error by adding checks before you attempt to access the list:
If item.Baddies.Count > 0 Then
Dim initialDirection As String = item.Baddies(0).CurrentDirection
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
placedItems(x)(y) = Nothing ' Clear the starting point
Else
' Handle the case where Baddies is empty
' For example, log a warning or assign a default direction
Console.WriteLine("Warning: No baddies available for this item.")
End If
Follow-Up Stock Checks
Ensure Baddies are Added: Where do you populate ItemInfo.Baddies? Make sure these lists are populated correctly in your game logic or user interface.
Count Before Access: Always check the count of lists or arrays before accessing their elements to prevent out-of-range errors.
Conclusion
By implementing these checks, you should be able to prevent the ArgumentOutOfRangeException and ensure that your game logic can handle scenarios where baddies might not be available. If you continue to face issues, please share the relevant sections of code, and I can assist further.
Certainly! Below is the revised AddBaddiesOnGrid method with the added check to prevent the ArgumentOutOfRangeException by ensuring that the Baddies list is not empty before attempting to access it.
Revised AddBaddiesOnGrid Method
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 item As ItemInfo = placedItems(x)(y)
' Check if the item is a baddy
If item.ImageKey.StartsWith("picBaddy") Then
' Check if there are any baddies associated with this item
If item.Baddies.Count > 0 Then
' Access the direction only if there is at least one baddy
Dim initialDirection As String = item.Baddies(0).CurrentDirection
' Create the baddy and pass the initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
Else
' Handle the case where Baddies is empty (optional)
Console.WriteLine($"Warning: No baddies available for item at ({x}, {y}).")
End If
' Clear the starting point regardless of baddy status
placedItems(x)(y) = Nothing
End If
End If
Next
Next
End Sub
Key Changes and Explanations
Check Count Before Access:
Before accessing the first baddy in item.Baddies, we first check if item.Baddies.Count > 0. This ensures that we only try to access the list if it actually has elements, preventing ArgumentOutOfRangeException.
Warning for Empty Baddies:
The console message (Console.WriteLine()) will log a warning if there are no baddies available for the current item. You could also choose to handle this case differently, such as setting a default direction or taking specific actions based on your game mechanics.
Clearing the Starting Point:
The line placedItems(x)(y) = Nothing is executed in any case to clear that position on the grid since it's part of your game logic.
Ensure Proper Initialization
Make sure the ItemInfo class initializes the Baddies list appropriately wherever items are created. If any ItemInfo object sets Baddies properties, ensure they are initialized to prevent accessing ItemInfo.Baddies that is Nothing.
Feel free to let me know if you need further assistance or additional modifications for specific scenarios!
If you're experimenting with not giving baddies a direction, that might indeed lead to accessing empty collections or encountering issues in your game logic.
Understanding the Implications
Empty Baddy List: If you do not set any baddies or do not assign their direction when creating items, your AddBaddiesOnGrid method will attempt to access a baddy that doesn't exist, which results in the ArgumentOutOfRangeException.
Default Initialization: If you want to have some baddies that don't have specific directions set initially, you must ensure that your logic can handle those cases gracefully when accessing CurrentDirection or other properties related to their movement.
Solutions for Handling Undefined Directions
To handle baddies without defined directions effectively:
Default Direction: Consider setting a default direction for baddies in case you don't provide a specific one. This way, they will always have a valid direction to start moving in.
Conditional Handling: Update your code logic to specifically account for baddies that might not have an assigned direction. Here’s how you might adjust the AddBaddiesOnGrid method again, allowing for an optional default direction:
Updated AddBaddiesOnGrid Method
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 item As ItemInfo = placedItems(x)(y)
' Check if the item is a baddy
If item.ImageKey.StartsWith("picBaddy") Then
Dim initialDirection As String
' Check if there are any baddies associated with this item
If item.Baddies.Count > 0 Then
' Access the direction if there is at least one baddy
initialDirection = item.Baddies(0).CurrentDirection
Else
' Set a default direction if there are no baddies
initialDirection = "Right" ' Use a sensible default or handle as needed
Console.WriteLine($"Warning: No baddies available for item at ({x}, {y}). Defaulting to {initialDirection}.")
End If
' Create the baddy and pass the initial direction
Dim baddy As New BaddyInfo(x, y, item.ImageKey, initialDirection)
baddies.Add(baddy) ' Add baddy to the list
' Clear the starting point
placedItems(x)(y) = Nothing
End If
End If
Next
Next
End Sub
Explanation of Changes
Default Direction Handling: If item.Baddies.Count == 0, it assigns a default direction like "Right". This prevents the baddy instantiation from trying to reference an undefined direction.
Logging a Warning: The console message informs you that a default direction is being used, helping with debugging.
Conclusion
By implementing a sensible default direction and ensuring your game logic can handle cases where directions may not be set, you’ll avoid errors related to accessing empty collections. It's important to make sure that the logic for your game remains robust and can adapt to various scenarios regarding baddy initialization.
If you have further questions or specific situations you need help with, let me know!