我正在用 Visual Basic 构建一个迷宫应用程序。游戏依赖于两个变量,X 和 Y,它们是整数。有一个计时器基本上使整个表单无效以进行重绘。现在我的问题是,表格周围点缀着各种正方形和矩形。我将如何创建一个处理程序或类似的东西来检测表单绘制的正方形是否接触这些对象?
代码:
Public Class Form1
Const W As Integer = 35 'Width
Const H As Integer = 35 'Height
Dim X As Integer
Dim Y As Integer
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
'Handles if a key is pressed
Select Case e.KeyCode
Case Keys.Up
Y -= 2
Case Keys.Down
Y += 2
Case Keys.Left
X -= 2
Case Keys.Right
X += 2
Case Keys.Escape
Me.Close()
End Select
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Text = "Maze"
TmrRedraw.Start()
MsgBox("Press ESC to quit")
Cursor.Position = Me.Location
End Sub
Private Sub TmrRedraw_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TmrRedraw.Tick
If CollisionDetect() = False Then
Me.Invalidate()
CheckForWin()
End If
End Sub
Private Function CollisionDetect()
Dim Collision As Boolean = False
'Here is where the problem lies
Return Collision
End Function
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
e.Graphics.FillRectangle(Brushes.Blue, X, Y, W, H)
End Sub
Private Sub CheckForWin()
Dim WinSqX As Integer = WinSquare.Location.X
Dim WinSqY As Integer = WinSquare.Location.Y
If X = WinSqX And Y = WinSqY Then
TmrRedraw.Stop()
MsgBox("Congratulations! You won!")
Me.Close()
End If
End Sub
End Class
哦,是的——玩家必须使用箭头键来改变 X 和 Y,当它重绘时,它会移动。
谢谢