admin 管理员组

文章数量: 887021


2024年3月1日发(作者:nativecode是什么)

迷宫游戏源代码

Const row = 22, col = 30

Dim grid(row + 1, col + 1)

Private Sub dmg_Click()

= 400 '初始化图片位置

= 400

d = True '启动时钟

End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) '键盘控制图片移动

l = 400

t = 400

Line (l * 400, t * 400)-(400 * (l + 1), 400 * (t + 1)), vbGreen, BF '显示走过的路径

Select Case KeyCode '随着键盘的动作来移动

Case vbKeyLeft

If - 400 >= 400 Then

If grid(t, l - 1) = 0 Then

= - 400

=

End If

End If

Case vbKeyRight

If + 400 <= 400 * col Then

If grid(t, l + 1) = 0 Then

= + 400

=

End If

End If

Case vbKeyDown

If + 400 <= 400 * row Then

If grid(t + 1, l) = 0 Then

=

= + 400

End If

End If

Case vbKeyUp

If - 400 >= 400 Then

If grid(t - 1, l) = 0 Then

=

= - 400

End If

End If

End Select

If 400 = row And 400 = col - 1 Then

d = False

MsgBox ("恭喜你,成功走出迷宫!") '显示成功信息

End If

End Sub

Private Sub Form_Load()

Open "迷宫矩阵.txt" For Input As #1 '读取迷宫矩阵,绘制迷宫图

For i = 0 To row + 1

For j = 0 To col + 1

If 1 <= i And i <= row And 1 <= j And j <= col Then

Input #1, grid(i, j)

If grid(i, j) = 1 Then '值为1则表示障碍或墙,0则表示通道,即可行路径

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbBlue, BF

End If

Else

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbBlue, BF

End If

Next

Next

Close #1

End Sub

Private Sub mig_Click() '随机获取迷宫矩阵

= 400

= 400

Randomize

m = row * Int(20 * Rnd)

Open "迷宫矩阵.txt" For Input As #1 '读取事先设计好的迷宫矩阵,随机读取一种矩阵

Do While n <> m

Line Input #1, temp

n = n + 1

Loop

For i = 1 To row

For j = 1 To col

Input #1, grid(i, j)

If grid(i, j) = 1 Then

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbBlue, BF

Else

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbWhite, B

End If

Next

Next

Close #1

End Sub

Private Sub start_Click()

= 400

= 400

Open "迷宫矩阵.txt" For Input As #1 '初始化迷宫矩阵

For i = 1 To row

For j = 1 To col

Input #1, grid(i, j)

If grid(i, j) = 1 Then

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbBlue, BF

Else

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbWhite, B

End If

Next

Next

Close #1

End Sub

Private Sub Timer1_Timer() '使迷宫矩阵动态变化,随机生成的迷宫可能是走不通的

X = 1: Y = 1

For i = 1 To row

For j = 1 To col

Randomize

grid(i, j) = Int(2 * Rnd)

If grid(i, j) = 1 Then

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbBlue, BF

Else

Line (j * 400, i * 400)-(400 * (j + 1), 400 * (i + 1)), vbWhite, B

End If

Next

Next

End Sub

设计时,只需3个picture控件和1个timer控件即可,故还是比较简单的。

如下图所示:

“迷宫矩阵.txt”中的内容如下所示(自己设计一个即可):

程序最终运行效果如下所示:


本文标签: 迷宫 矩阵 键盘 移动 显示