读取一个以前没有读过的随机excel单元格
我的程序给用户一个基于Excel文件的测验。 问题以随机顺序出现。 在Excel文件(n,3-7)的每一行中有5个可能的问题,答案总是在该行的第二个单元格(n,2)中。 有135行,但前两行与问题无关。 用户可以正确地回答问题,他们应该尽量在时限内回答尽可能多的问题,所以当时间到了时,用户将永远不会看到未经询问的问题。 我需要帮助的问题是有一个难得的机会(665中的1)可以重复一个问题。 我怎样才能防止这个? (另外,我对编程非常陌生)
问题生成代码
Private Sub newquestion() 'New Question Randomize() row = CInt(rnd.Next(3, 135)) key = CInt(rnd.Next(3, 7)) lblgametype.Text = "Guess the answer from the hint" lblquestion.Text = worksheet.Cells(row, key).Value End Sub
检查答案的代码
Private Sub OnKeyDownHandler(ByVal sender As Object, ByVal e As KeyEventArgs) Handles txtanswer.KeyDown 'Prevent that annoying ass windows ding sound If e.KeyCode = Keys.Enter Then e.SuppressKeyPress = True End If If e.KeyCode = Keys.Escape Then e.SuppressKeyPress = True End If If e.KeyCode = Keys.Enter Then 'If the user presses Enter while txtanswer is selected... userguess = txtanswer.Text 'Assign the text the user enters to the global userguess variable If userguess.ToUpper = worksheet.Cells(row, 2).Value.ToString.ToUpper Then 'User answers a question correct lblcorrect.ForeColor = Color.Green lblcorrect.Text = "Correct. +1" txtanswer.Text = "" userguess = "" abilityscore += 1 lblscore.Text = "Score: " & abilityscore If abilityscore > abilityhighscore Then abilityhighscore = abilityscore End If newquestion() Else 'User answers a question incorrectly lblcorrect.ForeColor = Color.Red lblcorrect.Text = "incorrect." txtanswer.Text = "" End If End If If e.KeyCode = Keys.Escape Then 'If the user presses escape while txtanswer is selected... btnskip.PerformClick() 'Treat it as if they pressed skip End If End Sub
代码为跳过问题
Private Sub btnskip_Click(sender As Object, e As EventArgs) Handles btnskip.Click Me.TargetDT = Me.TargetDT.Subtract(TimeSpan.FromSeconds(15)) 'Subtract 15 seconds from the timer txtanswer.Focus() 'Reset focus back to the textbox newquestion() End Sub
每行132个行有5个候选问题是一种奇怪的存储方式。 我猜测,基本上是把5个方法放在同一个问题上,或者至less有相同的正确答案。
我无法确定,但看来每次肯定会select不同的行就足够了。
Public Class frmQuizzer ' form level variables Private RNG As New Random() Private rowNums As Int32() Private rowIndex As Int32
我会猜测一个游戏或一轮将是10个问题。 所以,在一个NewGame
方法中(所以你可以在不重新启动应用程序的情况下再次运行它):
' which row to use this turn rowIndex = 0 rowNums = Enumerable.Range(3, 135). OrderBy(Function(r) RNG.Next()). Take(10). ToArray()
这是你的10个不同的XL行使用。 您也可以使用RNG对象选取单元格:
key = RNG.Next(3,8) ' the MAX is exclusive! row = rowNums(rowIndex) ' "move" to next question rowIndex += 1 lblquestion.Text = worksheet.Cells(row, key).Value
就个人而言,我可能会使用一个像“甲板鞋”一样的“使用”行号的Stack
,而不是跟踪可能会搞砸的rowIndex
Private rowNums As Stack(Of Int32)
从创build的数组中填充它:
Dim nums = Enumerable.Range(3, 135). OrderBy(Function(r) RNG.Next). Take(10). ToArray() rowNums = New Stack(Of Int32)(nums)
得到一个并使用它:
' Pop gets the next value and removes it from the list lblquestion.Text = worksheet.Cells(rowNums.Pop(), key).Value
没有索引器跟踪,也没有机会脱离同步。
更多
- select唯一的随机数字
- 对于不那么随意的事情,而不是重新sorting/随机化arrays,使用实际的洗牌