嗨我想延迟代码执行一段时间但是点击我的一个名为chance()的func .. 在图片box.image改变之后被调用... bt图像没有改变nd func chance()开始...我希望在图片更改后偶然延迟()因此帮助我...
码
Private Sub p11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles p11.Click
row = 1
col = 1
chck() 'function which returns hit var value
p11.Enabled = False
If hit = 1 Then
p11.Image = Image.FromFile("G:\visual progs\BATTLESHIP\hit.png")
ElseIf hit = 0 Then
p11.Image = Image.FromFile("G:\visual progs\BATTLESHIP\miss.png")
lblstatus.Text = "COMPUTER's TURN ... PLEASE WAIT ... "
chance() ' func begins
End If
End Sub
Function chance()
***'here i want a pause for 2 sec***
Dim z As Int16 = 1
While z = 1
row = mnw.Next(9) + 1
col = mnw.Next(9) + 1
If c(row, col) = False Then
c(row, col) = True
z = 0
End If
End While
chck1() ' checks for hit or miss for computer
changepic() 'changes pic hit or miss for computer
Return 0
End Function
答案 0 :(得分:1)
要暂停2秒,您只需要执行以下操作暂停该线程:
Thread.Sleep(2000)
答案 1 :(得分:1)
尽管您可以使用Thread.Sleep来引入延迟,但它通常会产生不良副作用,特别是表单及其控件变得无法响应。更好的方法是使用计时器 - 这样表单仍然是响应式的(例如,您可以移动它)。
此外,您似乎不确定在何处使用Sub以及在何处使用Function。 Sub执行某些操作,并使用Function返回值,理想情况下使用 no 副作用。
您可以尝试使用新的Windows窗体项目,只使用名为p11
的PictureBox和名为lblStatus
的标签:
Imports System.IO
Public Class Form1
Dim tim As Windows.Forms.Timer
Const GAMEPATH As String = "G:\visual progs\BATTLESHIP\"
Dim HitImgFile As String = Path.Combine(GAMEPATH, "hit.png")
Dim MissImgFile As String = Path.Combine(GAMEPATH, "miss.png")
Private Sub SetUpTimer()
tim = New Timer
tim.Interval = 2000 ' milliseconds
tim.Enabled = False
AddHandler tim.Tick, AddressOf Chance
End Sub
Private Sub Chance(sender As Object, e As EventArgs)
tim.Enabled = False
' your code for the computer's turn goes here
lblStatus.Text = "Your turn"
p11.Enabled = True
End Sub
Private Function IsHitByUser() As Boolean
' placeholder code for the actual check
If Rnd() < 0.5 Then
Return True
End If
Return False
End Function
Private Sub DoComputerTurn()
lblStatus.Text = "COMPUTER's TURN ... PLEASE WAIT ... "
p11.Enabled = False
tim.Enabled = True
End Sub
Private Sub p11_Click(sender As Object, e As EventArgs) Handles p11.Click
If IsHitByUser() Then
p11.Image = Image.FromFile(HitImgFile)
lblStatus.Text = "HIT"
Else
p11.Image = Image.FromFile(MissImgFile)
DoComputerTurn()
End If
End Sub
Private Sub StartGame()
lblStatus.Text = "Your turn"
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetUpTimer()
StartGame()
End Sub
End Class