Delphi计时器和变量

时间:2015-10-14 00:03:16

标签: delphi

我有一个delphi定时器,可以在200ms执行代码。它将存储一个名为CurrentShots的变量。我需要做的是存储另一个名为OriginalShots的变量来检测CurrentShots是否在同一个计时器中减少了。

这可能吗?如果没有两个变量都是相同的数字,我无法找到一种方法。

UIImage

我意识到我没有初始化OriginalShots,但我不确定如何这样做。基本上开始使用CurrentShots将等于OriginalShots,直到CurrentShots减少1。

所以例如我们从50开始。两个变量都有50.一个镜头被拍摄CurrentShots现在将显示49和OriginalShots仍然有50,因此我知道已经开枪。现在如果另一个镜头被触发,则CurrentShots变为48,OriginalShots变为49。

我正从内存中读取CurrentShots,这意味着也会从内存中读取OriginalShots。

我希望我已经解释过了自己。

1 个答案:

答案 0 :(得分:3)

首先,我想知道使用array of char的值 - 如果你的问题准确说明 - 是简单的整数。

同样,如果值是indeeds char数组,那么直接比较可能无法按预期和意图运行。如果它们是数字的字符串表示,那么我将在任何比较之前转换为实际的整数值,以确保正确的数字比较而不是字符串比较。

我认为这是你的意图。

除此之外,您的问题基本上是您在事件处理程序(即函数)中使用局部变量时,这些值的使用需要独立于事件和函数存在的变量。

只需将 OriginalShot 的声明移动到事件处理程序之外的某个位置,在该位置它可以独立于计时器事件本身中的处理保存值(包含该表单的表单的变量/字段)计时器将是一个很好的候选者)并在启动计时器之前用适当的值初始化它:

TForm1 = class(TForm)
  Timer1: TTimer;
   :
private
  fOriginalShots: Integer;    
   :
end;


procedure TForm1.Create(Sender: TObject);
begin
  fOriginalShots := 100;   // Or as appropriate

  Timer1.Enabled := TRUE;
end;

在您的活动中,您将 CurrentShots 的整数值与表单成员 fOriginalShots 进行比较,并仅在有更改时更新 fOriginalShots

var
  CurrentShots: array[0..MAX_PATH] of Char;
  iCurrentShots: Integer;

 ...

// NOTE: In your actual code you may need to deal with the possibility that
//        CurrentShots (the array of char) is not a valid representation of 
//        an integer

iCurrentShots := StrToInt(String(CurrentShots));

if iCurrentShots < fOriginalShots then
begin
  // Other related processing goes here ....

  // Save new CurrentShots value in OriginalShots for comparison the
  //  next time the event fires:

  fOriginalShots := iCurrentShots;
end;

另外,我注意到你的计时器事件会禁用计时器,但似乎没有重新启用它并想知道这是否是故意的?

相关问题