我正在为一个课程作一个游戏,我遇到了一个问题。这是一个非常简单的游戏。一个敌人会产生(图片框)并且你会射击它(左击)使它死亡(消失)。我希望用户每3秒钟就会失去5点生命值。我能想到的唯一方法是使用计时器和文本框。游戏开始时,计时器被禁用。当敌人产生时,计时器变为启用状态,文本框开始每秒增加一个。当用户杀死敌人时,计时器再次被禁用,文本框被重置为0.现在我需要做的就是让用户每3秒钟就会失去生命。以下代码是我目前的代码:
Private Sub timerenabled()
If PicBoxEnemy.Visible = True Then
Timer2.Enabled = True
Else
Timer2.Enabled = False
TxtBox.Text = 0
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
TxtBox.Text = TxtBox.Text + 1
End Sub
Private Sub checkvalue()
Dim x As Integer
x = TxtBox.Text / 3
If CInt(x) Then
Do
health = health - 5
Loop Until health = 0
End If
End Sub
任何其他更有效的方法都可以理解。我希望你明白我要做的事。
答案 0 :(得分:2)
首先,Stack Overflow并不是一个真正的教程网站,但我无法拒绝回答你。
确定您的代码存在一些问题。但首先,问你的问题。而不是使用TextBox,使用标签。文本框可以由用户修改。这让我想到了其中一个问题。
首先,使用控件作为数据存储库是非常糟糕的做法。您对变量Timer2
有正确的想法。
二。在Visual Studio的设置中启用Option Strict。当你在那里时,确保Explicit打开,Compare is Binary,Infer is Off。
更改这些选项意味着您将编写更少的错误代码,但在不利方面,您需要再写一些。
最后花点时间为变量和对象选择有意义的名称,这样可以更容易记住它们的用途。例如,调用TmrGameRunning
类似于TmrGR
的东西 - 在六个月的时间内不像LblHealth
那样你可能不记得这样的名字是什么意思。 : - )
您需要创建一个名为TxtBox
的标签。我假设Public Class Form1
Dim health As Integer
' This will be the variable that note if your player is alive or dead .. True if alive, False if dead
Dim PlayerAlive As Boolean = True
'This is slightly different to your code. In VB, there is an event that will fire when the
'visibility of a textbox changes. The following method will execute when this happens. Just like code
'that you would write when you're handling a button.click event
Private Sub PicBoxEnemy_VisibleChanged(sender As Object, e As EventArgs) Handles PicBoxEnemy.VisibleChanged
If PicBoxEnemy.Visible = True Then
Timer2.Enabled = True
Else
Timer2.Enabled = False
End If
End Sub
'This is a modified version of your timer tick - Don't forget to change the timer .Interval property
'to 3000
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
health = health - 5
'This will change the text of the label to whatever your player's health is and the line below
'will force the label to update
LblHealth.Text = health.ToString
LblHealth.Update()
'Also while the timer is ticking the method below will check the health of your player and decide if
'they are dead or not. If they are, the timer is disabled and the PlayerDead method is called.
AliveOrDead()
End Sub
Private Sub AliveOrDead()
If health <= 0 Then
Timer2.Enabled = False
PlayerDead()
End If
End Sub
'This will be the method that executes when the player is dead. You'll need to add your own code
'for this of course, depending on what you want to do.
Private Sub PlayerDead()
'code here for what happens at the end of the game
End Sub
End Class
控件可以被丢弃,因为它只是计算计时器滴答。你不需要它。还假设您将计时器添加为计时器控件,在计时器的属性中,只需将间隔设置为3000,这是刻度之间的毫秒数= 3秒
查看修改后的代码和解释说明
{{1}}
提示。您可能需要一个按钮控件和一个Button.Click事件处理程序方法来启动游戏,这是一种在游戏运行时使PictureBox可见(可能是随机间隔)的方法,(不要忘记在PictureBox时停止此计时器)是可见的),最后是一个事件处理程序,当你点击图片使其不可见时被调用(并停止减少健康的计时器)