首页 \ 问答 \ C#在另一个计时器内使用计时器?(C# using a timer within another timer?)

C#在另一个计时器内使用计时器?(C# using a timer within another timer?)

我正在编写一个俄罗斯方块游戏。 到目前为止,我已经实现了一个间隔很短,大约50毫秒的定时器。 当前下降的tetromino在游戏矩阵中向下移动一个位置。 然后游戏检查是否有碰撞,如果是这样,tetromino被标记为“落地”并且产生了新的tetromino。

不,我有这个问题,我想让玩家有机会将tetromino向左或向右移动,让我们说它降落后0.5秒,以便有可能将tetromino移动到悬垂的已落地的tetromino下面。

但是使用我当前的代码,我遇到的问题是,一旦检测到碰撞,计时器就会继续并产生下一个tetromino。 我现在的想法是尝试实现第二个计时器,每次检测到碰撞时都会激活0.5秒,以便在主计时器继续运行时允许额外的键盘输入。 因此,基本上暂停主计时器0.5秒,并允许程序在此期间检测键盘输入,然后继续主计时器。

到目前为止我尝试的所有东西都没有真正起作用。 看起来第一个计时器总是继续运行,而我有第二个计时器处于活动状态。

这是我的第一个计时器的样子:

private void TimerBrick_Tick(object sender, EventArgs e)
        {
            ResetGameBoard(jaggedTetrisBricks[rnd-1][rotation], _brickX, _brickY, xLengthBrick, yLengthBrick);
            _brickX++;
            CollisionCheck(jaggedTetrisBricks[rnd - 1][rotation], _brickX, _brickY, xLengthBrick, yLengthBrick);
            LineCheck();

            Invalidate();
        }

现在我需要在我的CollisionCheck()方法中实现一种在代码继续使用LineCheck()之前等待0.5秒的方法。

或者还有另一种我现在没有看到的方式?


I'm programming a tetris game. So far I have implemented a timer with a very short interval of around 50 ms. Every tick the current falling tetromino gets moved one position in the game matrix downwards. Then the game checks if there is a collision, if so the tetromino gets marked as "landed" and new tetromino is spawned.

No I have the problem that I want to give the player the chance to move the tetromino to the left or right for let's say 0.5 seconds after it landed to have the possibility to move the tetromino underneath an overhanging already landed tetromino.

But with my current code I have the problem that as soon as there is a collision detected the timer continues and spawns the next tetromino. My idea now was to try to implement a second timer that gets activated for 0.5 seconds everytime a collision is detected to allow for additional keyboard input bevore the main timer continues. So basically pausing the main timer for 0.5 seconds and allow the program to detect keyboard input during that time and then continue with the main timer.

Everything I tried so far didn't really work. It seems like the first timer always continues running while I have a second timer active.

This is how my first timer looks like:

private void TimerBrick_Tick(object sender, EventArgs e)
        {
            ResetGameBoard(jaggedTetrisBricks[rnd-1][rotation], _brickX, _brickY, xLengthBrick, yLengthBrick);
            _brickX++;
            CollisionCheck(jaggedTetrisBricks[rnd - 1][rotation], _brickX, _brickY, xLengthBrick, yLengthBrick);
            LineCheck();

            Invalidate();
        }

Now I somehow need to implement inside my CollisionCheck() method a way to wait for 0.5 seconds before the code continues with LineCheck().

Or is there another way that I'm not seeing right now?


原文:https://stackoverflow.com/questions/39001634
更新时间:2022-06-28 20:06

最满意答案

下面的代码是一个Xamarin.Forms谷歌材料设计,如入门方法。 总xaml +一点编码:)

第1步:在PCL项目中创建一个类

public class CustomEntry : Entry
    {

    }

第2步:在App.xaml中创建一个控件模板

<ControlTemplate x:Key="MyControlTemplate">
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
      </Grid.RowDefinitions>
      <controls:CustomEntry x:Name="myEntry" Text="{TemplateBinding Text, Mode=TwoWay}" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Start" IsPassword="{TemplateBinding IsPassword}" MinimumHeightRequest="25"/>
      <BoxView Grid.Row="1" BackgroundColor="#D2D2D2" HeightRequest="1" HorizontalOptions="FillAndExpand" VerticalOptions="Start">
        <BoxView.Triggers>
          <DataTrigger TargetType="BoxView" Binding="{Binding Source={x:Reference myEntry}, Path=IsFocused}" Value="true">
            <Setter Property="BackgroundColor" Value="Black" />
            <Setter Property="HeightRequest" Value="2"/>
          </DataTrigger>
        </BoxView.Triggers>
      </BoxView>
    </Grid>
  </ControlTemplate>  

第3步:创建超级材料设计入口类

public class MyMaterialDesignEntry : ContentView, INotifyPropertyChanged
    {
        public static readonly BindableProperty TextProperty =
        BindableProperty.Create("Text", typeof(string), typeof(ContentPage), "");
        public static readonly BindableProperty IsPasswordProperty =
        BindableProperty.Create("IsPassword", typeof(bool), typeof(ContentPage), false);

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, (string)value); }
        }       

        public bool IsPassword => (bool)GetValue(IsPasswordProperty);

        public MyMaterialDesignEntry()
        {
            ControlTemplate = (ControlTemplate)Application.Current.Resources.FirstOrDefault(x => x.Key == "MyControlTemplate").Value;
        }      
    }

第4步:在xaml中使用超级材质设计条目

<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
            <Label Text="Login"/>
            <controls:MyMaterialDesignEntry Text="{Binding Login, Mode=TwoWay}"/>
          </StackLayout>

不要忘记在页面xaml中添加适当的命名空间。 无论如何它会告诉你的。


Below code is a Xamarin.Forms google material design like entry approach. Total xaml + a little coding :)

Step1: Create a class in PCL project

public class CustomEntry : Entry
    {

    }

Step2: Create a control template in App.xaml

<ControlTemplate x:Key="MyControlTemplate">
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
      </Grid.RowDefinitions>
      <controls:CustomEntry x:Name="myEntry" Text="{TemplateBinding Text, Mode=TwoWay}" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Start" IsPassword="{TemplateBinding IsPassword}" MinimumHeightRequest="25"/>
      <BoxView Grid.Row="1" BackgroundColor="#D2D2D2" HeightRequest="1" HorizontalOptions="FillAndExpand" VerticalOptions="Start">
        <BoxView.Triggers>
          <DataTrigger TargetType="BoxView" Binding="{Binding Source={x:Reference myEntry}, Path=IsFocused}" Value="true">
            <Setter Property="BackgroundColor" Value="Black" />
            <Setter Property="HeightRequest" Value="2"/>
          </DataTrigger>
        </BoxView.Triggers>
      </BoxView>
    </Grid>
  </ControlTemplate>  

Step 3: Create a super material design entry class

public class MyMaterialDesignEntry : ContentView, INotifyPropertyChanged
    {
        public static readonly BindableProperty TextProperty =
        BindableProperty.Create("Text", typeof(string), typeof(ContentPage), "");
        public static readonly BindableProperty IsPasswordProperty =
        BindableProperty.Create("IsPassword", typeof(bool), typeof(ContentPage), false);

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, (string)value); }
        }       

        public bool IsPassword => (bool)GetValue(IsPasswordProperty);

        public MyMaterialDesignEntry()
        {
            ControlTemplate = (ControlTemplate)Application.Current.Resources.FirstOrDefault(x => x.Key == "MyControlTemplate").Value;
        }      
    }

Step 4: Use your super material design entry in xaml

<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
            <Label Text="Login"/>
            <controls:MyMaterialDesignEntry Text="{Binding Login, Mode=TwoWay}"/>
          </StackLayout>

Don't forget to add appropriate namespaces to your page xaml. It will tell you anyway.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)