如何将计时器添加到连接四? Java

问题描述 投票:0回答:1

这是一个非常规问题,但是我想知道是否有人对将计时器实现为四人连线游戏(2个玩家)有任何想法。我目前有常规游戏的正常运行代码,但想添加一种方法,使用户有5秒钟的时间进行移动,否则计算机将为他们随机移动。是否有人对如何实现这一目标有任何想法?这是我处理转弯决策的主要功能。

public void handleAction (int x, int y)
    {
    if (gameOver)
    {
        JOptionPane.showMessageDialog (this, "Please Select Game...New to start a new game",
            "Game Over", JOptionPane.WARNING_MESSAGE);
        return;
    }

    int column = (x - BORDER_SIZE) / SQUARE_SIZE + 1;
    int row = findNextRow (board, column);

    if (row <= 0)
    {
        JOptionPane.showMessageDialog (this, "Please Select another Column",
            "Column is Full", JOptionPane.WARNING_MESSAGE);
        return;
    }

    animatePiece (currentPlayer, column, row);
    board [row] [column] = currentPlayer;

    int winner = checkForWinner (board, row, column);


    if (winner == BANANA)
    {
        gameOver = true;
        repaint ();
        backgroundMusic.stop();
        winBanana.play();
        JOptionPane.showMessageDialog (this, "Banana Wins!!!",
            "GAME OVER", JOptionPane.INFORMATION_MESSAGE);

    }
    else if (winner == STRAWBERRY)
    {
        gameOver = true;
        repaint ();
        backgroundMusic.stop();
        winStrawberry.play();
        JOptionPane.showMessageDialog (this, "Strawberry Wins!!!",
            "GAME OVER", JOptionPane.INFORMATION_MESSAGE);
    }
    else {
        currentPlayer *= -1;
        if (currentPlayer == 1)
            addStrawberry.play();
        else
            addBanana.play();

    }   
    currentColumn = 3;

    repaint ();
}
java arrays timer 2d-games
1个回答
0
投票

java.lang.System.currentTimeMillis()方法将帮助您实现这一目标。

要开始在程序中实现这一点,您需要在每次进行新操作时记录当前时间。

然后,您将必须实现一个重复发生的循环以记录从切换到另一台播放器开始的每秒时间,我建议在记录当前时间之前先进行一秒的延迟while循环。

然后,在系统进行随机移动之前,您需要一个if语句来确定计时器何时到达所需的时间。这是一些入门的基本代码:

long start; end, timeElapsed;

start = System.currentTimeMillis();

while(.....){
    Thread.sleep(1000L);
    end = System.currentTimeMillis();

    timeElapsed = (endstart)/1000;
}

if(timeElapsed = ....){
    //enter code here
}
© www.soinside.com 2019 - 2024. All rights reserved.