搜尋
首頁Javajava教程線程如何改進兩人遊戲中的按鍵綁定處理?

How Can Threads Improve Key Binding Handling in a Two-Player Game?

具有鍵綁定的執行緒

在給定的上下文中,您可以使用單獨的執行緒來處理鍵綁定並更新遊戲狀態。這允許玩家使用不同的按鍵獨立控制他們的球拍,並確保兩個玩家可以同時移動他們的球拍。

以下範例示範如何使用執行緒的鍵綁定:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main {
    private static final int WIDTH = 600;
    private static final int HEIGHT = 500;

    public static void main(String[] args) {
        // Create a new game instance
        Game game = new Game(WIDTH, HEIGHT);

        // Create a thread pool to handle key bindings
        ExecutorService keyBindingPool = Executors.newCachedThreadPool();

        // Create key bindings for the two players
        KeyBindings player1Bindings = new KeyBindings(game, "W", "S");
        KeyBindings player2Bindings = new KeyBindings(game, "UP", "DOWN");

        // Install the key bindings using SwingUtilities to ensure they work on the EDT
        SwingUtilities.invokeLater(() -> {
            game.getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "player1Up");
            game.getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "player1Down");
            game.getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "player2Up");
            game.getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "player2Down");
            game.getComponent().getActionMap().put("player1Up", new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) { player1Bindings.up = true; }
            });
            game.getComponent().getActionMap().put("player1Down", new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) { player1Bindings.down = true; }
            });
            game.getComponent().getActionMap().put("player2Up", new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) { player2Bindings.up = true; }
            });
            game.getComponent().getActionMap().put("player2Down", new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) { player2Bindings.down = true; }
            });
        });

        // Add the key bindings to the thread pool
        keyBindingPool.submit(player1Bindings);
        keyBindingPool.submit(player2Bindings);

        // Start the game loop
        game.start();
    }

    private static class Game {
        private final int width;
        private final int height;
        private final Paddle paddle1;
        private final Paddle paddle2;
        private final Thread gameLoopThread;
        private final AtomicBoolean running;

        public Game(int width, int height) {
            this.width = width;
            this.height = height;
            this.paddle1 = new Paddle(0, 100, 10, 100);
            this.paddle2 = new Paddle(width - 10, 200, 10, 100);
            this.running = new AtomicBoolean(false);
            this.gameLoopThread = new Thread(this::gameLoop);
        }

        public void start() {
            running.set(true);
            gameLoopThread.start();
        }

        private void gameLoop() {
            while (running.get()) {
                // Update the game state based on the key bindings
                if (player1Bindings.up) { paddle1.moveUp(); } else if (player1Bindings.down) { paddle1.moveDown(); }
                if (player2Bindings.up) { paddle2.moveUp(); } else if (player2Bindings.down) { paddle2.moveDown(); }

                // Render the game on the screen
                paint();
            }
        }

        public void paint() {
            // Clear the screen
            // Draw the paddles
            // Draw the ball
            // Update the display
        }

        public JComponent getComponent() { return null; }
    }

    private static class KeyBindings implements Runnable {
        private final Game game;
        private final String upKey;
        private final String downKey;
        private final HashSet<string> keysPressed;
        public boolean up;
        public boolean down;
        private AtomicBoolean running;

        public KeyBindings(Game game, String upKey, String downKey) {
            this.game = game;
            this.upKey = upKey;
            this.downKey = downKey;
            this.keysPressed = new HashSet();
            this.running = new AtomicBoolean(false);
        }

        public void start() {
            running.set(true);
        }

        @Override
        public void run() {
            while (running.get()) {
                // Check for key presses
                if (keysPressed.contains(upKey)) { up = true; } else { up = false; }
                if (keysPressed.contains(downKey)) { down = true; } else { down = false; }

                // Sleep for a bit
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {}
            }
        }
    }

    private static class Paddle {
        private int x;
        private int y;
        private int width;
        private int height;

        public Paddle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; }

        public void moveUp() { if (y > 0) { y -= 5; } }
        public void moveDown() { if (y <p>在此範例中:</p>
<ul>
<li>Game 類別管理遊戲狀態並初始化球拍。它還啟動遊戲循環線程。 </li>
<li>KeyBindings 類別用於處理鍵綁定。它監聽按鍵並相應地更新遊戲狀態。 </li>
<li>Paddle 類別代表由玩家控制的槳。 </li>
<li>main 方法建立一個新的遊戲實例並安裝按鍵綁定使用 SwingUtilities。它還會啟動遊戲循環。 </li>
</ul>
<p>此範例可確保兩個玩家都可以使用不同的鍵獨立移動球拍,並且遊戲狀態會平滑且響應迅速地更新。 </p></string>

以上是線程如何改進兩人遊戲中的按鍵綁定處理?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java平台是否獨立,如果如何?Java平台是否獨立,如果如何?May 09, 2025 am 12:11 AM

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

關於Java平台獨立性的真相:真的那麼簡單嗎?關於Java平台獨立性的真相:真的那麼簡單嗎?May 09, 2025 am 12:10 AM

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java平台獨立性:Web應用程序的優勢Java平台獨立性:Web應用程序的優勢May 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM解釋:Java虛擬機的綜合指南JVM解釋:Java虛擬機的綜合指南May 09, 2025 am 12:04 AM

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

Java的主要功能:為什麼它仍然是頂級編程語言Java的主要功能:為什麼它仍然是頂級編程語言May 09, 2025 am 12:04 AM

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java平台獨立性:這對開發人員意味著什麼?Java平台獨立性:這對開發人員意味著什麼?May 08, 2025 am 12:27 AM

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

如何為第一次使用設置JVM?如何為第一次使用設置JVM?May 08, 2025 am 12:21 AM

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

如何查看產品的Java平台獨立性?如何查看產品的Java平台獨立性?May 08, 2025 am 12:12 AM

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中