对于一个学校项目,我们被要求设计一个“教育游戏”,我想到了一个想法,但我对如何在Visual Basic中编码它感到困惑。对于我的游戏,有10个物体以设定的间隔一次一个地从播放屏幕的左侧移动到右侧,并且玩家必须在每个物体到达播放屏幕的末尾之前为每个物体解决一个随机生成的等式。我该如何编程呢?
这是我到目前为止尝试过的代码,一旦snakecount = 0
就更改了级别Public Class frmGame
Dim SnakeCount As Integer
Dim Score As Integer
Dim Lives As Integer
Dim Level As Integer
Dim Objects(9) As Integer
Private Sub frmGame_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
While Level = 1
Objects(0) = Rnd() + Rnd()
Objects(1) = Rnd() - Rnd()
Objects(2) = Rnd() - Rnd()
Objects(3) = Rnd() * Rnd()
Objects(4) = Rnd() + Rnd()
Objects(5) = Rnd() * Rnd()
Objects(6) = Rnd() + Rnd()
Objects(7) = Rnd() - Rnd()
Objects(8) = Rnd() + Rnd()
Objects(9) = Rnd() * Rnd()
End While
End Sub
我目前遇到的最大困难是将随机整数分配给数组的每个元素,并将它们显示为用户查看然后求解的等式
非常感谢任何帮助或建议!! :)
答案 0 :(得分:2)
要生成(伪)随机整数,您不应该依赖Rnd()
来完成工作,而应使用System.Random
中的功能,否则模式会变得可见(并且不设置种子你总是得到相同的数字序列。
可以找到如何创建伪随机数的示例here
基本上,要获得Min
(包括)到Max
(不包括)范围内的随机数,您可以使用以下函数:
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer ' by making Generator static, we preserve the same instance ' ' (i.e., do not create new instances with the same seed over and over) ' ' between calls ' Static Generator As System.Random = New System.Random() Return Generator.Next(Min, Max) End Function
编辑以回复评论:
要生成随机方程式,您可以执行类似
Function randomEquation() As Tuple(Of Integer, String)
Dim op As Integer = GetRandom(0, 3)
Dim a As Integer = GetRandom(1, 10) 'Set range to your liking
Dim b As Integer = GetRandom(1, 10)
Select Case op
Case 0
Return New Tuple(Of Integer, String)(a + b, a & " + " & b)
Case 1
Return New Tuple(Of Integer, String)(a - b, a & " - " & b)
Case 2
Return New Tuple(Of Integer, String)(a * b, a & " * " & b)
Case Else
Throw New NotImplementedException("The value " & op & " is not assigned to an operator.")
End Select
End Function
结果是一个包含等式值和等式本身(作为字符串)的元组,您可以使用该字符串将其显示给脚趾用户,如Label1.Text = randomEquation().Item2
。