java 试着让耐力随着计时器的上升而下降,我希望它每10秒下降2

niknxzdl  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(123)

我正在尝试做一个基于文本的游戏,其中涉及一个计时器在屏幕的中心。
这个想法是每10秒,你的力量(耐力)消耗-2.一旦你达到0%的力量,你就死了。
到目前为止,我有一个工作计时器,还没有转换成分钟:秒,只是一个基本的秒计时器,然而,我的力量从0%而不是100%开始,数字不会改变
我尝试过在while循环中嵌套一个if循环。
我的思考过程包括:
当强度大于0%时,如果第二个%10 == 0,则消耗-2并将新强度设置为新值
否则,如果秒%10!= 0,则秒++
我真的很感激任何帮助,因为这是我的A级课程

b0zn9rqh

b0zn9rqh1#

不确定这将如何适合您的设计,但这里有一种方法来安排倒计时计时器。
首先,创建一个类,作为TimerTask的子类。

class MyTask extends TimerTask {
     int strength;
     int decrement;

     public MyTask(int initialStrength, int decrement) {
         this.strength = initialStrength;
         this.decrement = decrement;
     }

     public void run() {
         strength -= decrement;
         System.out.println(strength);
     }

     public int getStrength() {
          return strength;
     }
 }

你可以启动一个定时器来提供任务、初始延迟和持续时间。这里的持续时间是2秒。

Timer t = new Timer("MyTimer");
MyTask myTask = new MyTask(1000, 2);
t.schedule(myTask, 0, TimeUnit.SECONDS.toMillis(2));

每两秒钟打印一次

98
96
94
92
90
88
...
...
ffscu2ro

ffscu2ro2#

我建议你关注 * 耐力 * 水平而不是累积时间计数。* 耐力 * 水平才是真正驱动你游戏的因素,而不是消耗的时间。我想你的游戏最终可能会获得一个 * 耐力 * 可以增加也可以减少的特性。

一个月

scheduled executor service可以在经过指定的时间后运行任务。

ScheduledExecutorService ses = Executors. newSingleThreadScheduledExecutor() ;

将你的任务定义为实现RunnableCallable。在检查我们是否有剩余的"耐力"之后,该任务将做"三件事":

  • 降低AtomicInteger中的 * 耐力 * 等级。
  • 回调用户界面以记录 * permature * 状态的变化。Vaadin、JavaFX和Swing等GUI框架为线程安全回调提供了一个钩子。
  • 使用计划的执行器服务重新计划自身。

请确保在应用结束前关闭执行器服务。请参阅Javadoc for ExecutorService上给出的样板代码。

示例代码

我们的任务课。

package work.basil.example.threading;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

public class StaminaWaning implements Runnable
{
    private final AtomicInteger stamina;
    private final Duration duration;

    private final ScheduledExecutorService ses;
    private final IntUnaryOperator unaryOperatorSubtraction = ( int x ) -> ( x - 2 );

    public StaminaWaning ( final AtomicInteger stamina , final Duration interval , final ScheduledExecutorService scheduledExecutorService )
    {
        this.stamina = stamina;
        this.duration = interval;

        this.ses = scheduledExecutorService;
    }

    @Override
    public void run ( )
    {
        int remainingStamina = this.stamina.updateAndGet( this.unaryOperatorSubtraction );
        System.out.println( "Stamina reduced to " + remainingStamina + " at " + Instant.now() );
        // … make thread-safe callback to UI …
        if ( remainingStamina > 0 )
        {
            // Still alive, continuing the game, so schedule this task to continue waning of stamina.
            this.ses.schedule( this , this.duration.toNanos() , TimeUnit.NANOSECONDS );
        }
    }
}

我们的应用程序示例化并运行该任务。

package work.basil.example.threading;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Game
{
    private final AtomicInteger stamina;
    private final ScheduledExecutorService ses;

    public Game ( )
    {
        this.stamina = new AtomicInteger( 100 );
        this.ses = Executors.newSingleThreadScheduledExecutor();
    }

    public static void main ( String[] args )
    {
        Game game = new Game();
        game.demo();
    }

    private void demo ( )
    {
        System.out.println( "stamina = " + stamina + " at " + Instant.now() );

        Runnable staminaWaning = new StaminaWaning( this.stamina , Duration.ofSeconds( 10 ) , this.ses );
        this.ses.schedule( staminaWaning , 10 , TimeUnit.SECONDS ); // Get the task started running. It will then schedule itself for further runs.
        // … other stuff happening … we simulate by sleeping this main thread
        try { Thread.sleep( Duration.ofMinutes( 10 ).toMillis() ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); }
        // then app ends
        if ( ! this.ses.isShutdown() )
        {
            this.shutdownAndAwaitTermination( this.ses );
        }
        System.out.println( "Done running `demo`. " + Instant.now() );
    }

    private void shutdownAndAwaitTermination ( ExecutorService executorService )
    {
        executorService.shutdown(); // Disable new tasks from being submitted
        try
        {
            // Wait a while for existing tasks to terminate
            if ( ! executorService.awaitTermination( 60 , TimeUnit.SECONDS ) )
            {
                executorService.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if ( ! executorService.awaitTermination( 60 , TimeUnit.SECONDS ) )
                { System.err.println( "Executor service did not terminate. " + Instant.now() ); }
            }
        }
        catch ( InterruptedException ex )
        {
            // (Re-)Cancel if current thread also interrupted
            executorService.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
}

运行时:

stamina = 100 at 2023-01-06T23:15:03.663213Z
Stamina reduced to 98 at 2023-01-06T23:15:13.676322Z
Stamina reduced to 96 at 2023-01-06T23:15:23.687932Z
Stamina reduced to 94 at 2023-01-06T23:15:33.694538Z
Stamina reduced to 92 at 2023-01-06T23:15:43.700024Z
…
Stamina reduced to 10 at 2023-01-06T23:22:33.874121Z
Stamina reduced to 8 at 2023-01-06T23:22:43.875564Z
Stamina reduced to 6 at 2023-01-06T23:22:53.878463Z
Stamina reduced to 4 at 2023-01-06T23:23:03.884400Z
Stamina reduced to 2 at 2023-01-06T23:23:13.887652Z
Stamina reduced to 0 at 2023-01-06T23:23:23.889939Z
Done running `demo`. 2023-01-06T23:25:03.680419Z

相关问题