Reputation: 33
I have a while loop displaying an array of graphnodes (using a function that returns a char in the graphnodes to display) followed by a 'move' procedure that moves a "Creature" from one node to the other. The creature decides where to go by pressing 'W', 'A', 'S', or 'D' which then deoccupies (using a function called 'deoccupy') the graphnode from the creature and puts that creature into the graphnode in the direction the creature wants to move.
I've tried throwing some errors pretty much everywhere and using trycatch to interrupt code that isn't working and I didn't get any errors. I added a case else to the movement "Select Case" statement.
While True
Try
Console.SetCursorPosition(0, 0)
myMap.ShowMap()
myMap.MoveCreatures()
Catch ex As Exception
Console.Clear()
Console.WriteLine(ex.Message)
Console.ReadKey(True)
End Try
End While
Public Sub MoveCreatures()
For y = 0 To tiles.GetLength(1) - 1
For x = 0 To tiles.GetLength(0) - 1
If tiles(x, y).IsOccupied Then
tiles(x, y).MoveCreature()
End If
Next
Next
Public Sub MoveCreature() Implements ITile.MoveCreature
If Occupied = True Then
Creature.Action(Me)
Else
Throw New Exception("No creature to move here.")
End If
End Sub
Select Case Console.ReadKey(True).KeyChar
Case "w"
If currentTile.North IsNot Nothing Then
currentTile.North.Occupy(currentTile.Deoccupy)
Else
Throw New Exception("Can't go in this direction!")
End If
Case "a"
If currentTile.West IsNot Nothing Then
currentTile.West.Occupy(currentTile.Deoccupy)
Else
Throw New Exception("Can't go in this direction!")
End If
...
The code is the same for 'S' and 'D' minus the directions change. E.g. 'S' has
currentTile.South
When the creature moves in 'W' or 'D', it does not redisplay the map until I press another key, whereas when it moves in 'A' or 'S', it refreshes the map right away. I want it to refresh the map any time I press any of 'W', 'A', 'S', or 'D'.
P.S. Sorry for putting so much code.
Upvotes: 0
Views: 53
Reputation: 3642
While True
is a C# workaround as they cannot create endless loops. In VB simply use Do Loop
instead:
Do
Try
Console.SetCursorPosition(0, 0)
myMap.ShowMap()
myMap.MoveCreatures()
Catch ex As Exception
Console.Clear()
Console.WriteLine(ex.Message)
Console.ReadKey(True)
End Try
Loop
I guess the problem lies in method
Public Sub MoveCreatures()
For y = 0 To tiles.GetLength(1) - 1
For x = 0 To tiles.GetLength(0) - 1
If tiles(x, y).IsOccupied Then
tiles(x, y).MoveCreature()
End If
Next
Next
as you do not exit the function when you have found the occupied cell, depending in what direction you move tiles(x, y).IsOccupied
is true again before the method is finished and myMap.ShowMap()
is called. It also looks quite inefficient to me - why don't you track the current position of the creature(s) instead of looping through the whole grid, e.g. within the creature object?
Upvotes: 2