­

零基础VB教程067期:贪吃蛇游戏开发第三节 撞墙会挂的

  • 2020 年 3 月 26 日
  • 筆記
视频讲解

https://v.qq.com/x/page/y0935fiohdf.html

刘金玉的零基础VB教程067期:贪吃蛇游戏开发第三节

撞墙会挂的

规则

贪吃蛇撞到窗体的边缘要游戏结束

界面:

程序源代码:

Private Type Node '每一节蛇身      D As Integer '37左38上39右40下      X As Single 'left      Y As Single 'top  End Type  Dim W As Integer '每一节蛇身宽度  Dim sno() As Node '声明一条蛇,是动态数组  Dim currentDirect As Integer '代表蛇运动的当前方向    Private WithEvents timer1 As Timer  '初始化一条蛇的各个参数  Function init()  AutoRedraw = True '自动重绘  W = 200  currentDirect = 39 '默认向右运动  ReDim sno(5) As Node    '初始化各个坐标点  Dim i As Long  For i = 0 To UBound(sno) Step 1        sno(i).D = currentDirect      sno(i).X = ScaleWidth / 2 + i * W      sno(i).Y = ScaleHeight / 2  Next i      End Function      '画一条蛇  Function drawSnake()  Cls  Dim i As Long    For i = 0 To UBound(sno) Step 1        Line (sno(i).X, sno(i).Y)-(sno(i).X + W, sno(i).Y + W), vbBlue, BF    Next i    End Function    Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)  If Abs(currentDirect - KeyCode) <> 2 Then currentDirect = KeyCode  End Sub    Private Sub Form_Load()  Call init  Call drawSnake    '对时钟控件进行初始化  Set timer1 = Controls.Add("vb.timer", "timer1")  timer1.Interval = 100  timer1.Enabled = True    End Sub    '运动思路:插入头结点,删除尾节点  Function sport()    Dim i As Long  '将每一个节点数据向前移动一位  For i = 1 To UBound(sno) Step 1        sno(i - 1) = sno(i)    Next i    '将头结点,也就是数组的最后一位重新复制  If currentDirect = 37 Then      sno(UBound(sno)).X = sno(UBound(sno)).X - W  ElseIf currentDirect = 38 Then      sno(UBound(sno)).Y = sno(UBound(sno)).Y - W  ElseIf currentDirect = 39 Then      sno(UBound(sno)).X = sno(UBound(sno)).X + W  ElseIf currentDirect = 40 Then      sno(UBound(sno)).Y = sno(UBound(sno)).Y + W  End If    End Function    Private Sub timer1_Timer()  Call sport  Call drawSnake  '判断是否撞到窗体边缘  If isCrashWall Then      If MsgBox("GAME OVER !是否重新开始?", vbYesNo, "游戏结束") = vbYes Then          Call init      Else          End      End If  End If  End Sub    '是否撞到窗体边缘,撞到返回true,否则就是false  Function isCrashWall() As Boolean    isCrashWall = False    If sno(UBound(sno)).X + W > ScaleWidth _    Or sno(UBound(sno)).X < 0 _    Or sno(UBound(sno)).Y < 0 _    Or sno(UBound(sno)).Y + W > ScaleHeight Then      isCrashWall = True '撞到了  End If    End Function  

课堂总结

1、掌握撞墙原理,4面墙4种情况

2、需要掌握and 或 or的在实际项目中的用法

3、自定义函数返回值的使用

4、对返回值的调用与处理

5、提示框,游戏是否继续?判断比较重要