帮我写一个用在EXCEL里的VBA贪吃蛇代码
时间: 2023-04-03 18:04:50 浏览: 238
好的,我可以回答这个问题。以下是一个简单的用于 Excel 的 VBA 贪吃蛇代码:
Sub SnakeGame()
Dim Snake() As Variant
Dim Food As Variant
Dim Direction As Integer
Dim Score As Integer
Dim GameOver As Boolean
Dim i As Integer
'初始化贪吃蛇
ReDim Snake(1 To 3, 1 To 2)
Snake(1, 1) = 5: Snake(1, 2) = 5
Snake(2, 1) = 5: Snake(2, 2) = 6
Snake(3, 1) = 5: Snake(3, 2) = 7
'初始化食物
Food = Array(Int(Rnd() * 20) + 1, Int(Rnd() * 20) + 1)
'初始化游戏参数
Direction = 1 '1-上,2-下,3-左,4-右
Score = 0
GameOver = False
'开始游戏循环
Do While Not GameOver
'清空画面
For i = 1 To 20
Range(Cells(i, 1), Cells(i, 20)).Interior.ColorIndex = xlNone
Next i
'绘制贪吃蛇
For i = 1 To UBound(Snake, 1)
Cells(Snake(i, 1), Snake(i, 2)).Interior.ColorIndex = 3
Next i
'绘制食物
Cells(Food(1), Food(2)).Interior.ColorIndex = 4
'等待用户输入
Application.Wait (Now + TimeValue("0:00:01"))
'移动贪吃蛇
Select Case Direction
Case 1 '上
Snake(UBound(Snake, 1), 1) = Snake(UBound(Snake, 1), 1) - 1
Case 2 '下
Snake(UBound(Snake, 1), 1) = Snake(UBound(Snake, 1), 1) + 1
Case 3 '左
Snake(UBound(Snake, 1), 2) = Snake(UBound(Snake, 1), 2) - 1
Case 4 '右
Snake(UBound(Snake, 1), 2) = Snake(UBound(Snake, 1), 2) + 1
End Select
'判断是否吃到食物
If Snake(UBound(Snake, 1), 1) = Food(1) And Snake(UBound(Snake, 1), 2) = Food(2) Then
'生成新的食物
Food = Array(Int(Rnd() * 20) + 1, Int(Rnd() * 20) + 1)
'增加分数
Score = Score + 1
'增加贪吃蛇长度
ReDim Preserve Snake(1 To UBound(Snake, 1) + 1, 1 To 2)
Snake(UBound(Snake, 1), 1) = Snake(UBound(Snake, 2), 1)
Snake(UBound(Snake, 1), 2) = Snake(UBound(Snake, 2), 2)
End If
'判断是否撞墙或撞到自己
If Snake(UBound(Snake, 1), 1) < 1 Or Snake(UBound(Snake, 1), 1) > 20 Or _
Snake(UBound(Snake, 1), 2) < 1 Or Snake(UBound(Snake, 1), 2) > 20 Then
GameOver = True
ElseIf UBound(Filter(Snake, Array(Snake(UBound(Snake, 1), 1), Snake(UBound(Snake, 1), 2)), True)) > 0 Then
GameOver = True
End If
'判断是否按下方向键
If Application.Wait(TimeSerial(0, 0, 1)) Then
Select Case Application.ActiveCell.Value
Case "w"
If Direction <> 2 Then Direction = 1
Case "s"
If Direction <> 1 Then Direction = 2
Case "a"
If Direction <> 4 Then Direction = 3
Case "d"
If Direction <> 3 Then Direction = 4
End Select
End If
Loop
'游戏结束
MsgBox "游戏结束,得分:" & Score
End Sub
阅读全文