亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 java 乒乓球游戲中使球拍的一側成為機器人?

如何在 java 乒乓球游戲中使球拍的一側成為機器人?

千巷貓影 2023-01-05 17:16:22
我正在制作一個 java 乒乓球游戲,我想把球拍的一側做成機器人,這樣玩家就可以與機器人競爭。我已經輸入了機器人,但我想改進它。我試圖創建一個線程來每隔 x 秒暫停一次機器人,但失敗了。請幫助找出解決方案。我已經對槳和球進行了預編程,包括檢查碰撞之類的東西。游戲可以算是完成了。我只想添加一個機器人,這樣它就會成為 PVE使用二級休眠緩存來緩存所有需要的數據庫查詢。為了在應用程序啟動時緩存,我們可以在任何服務類中使用@PostContruct。這是球代碼:package ball;import processing.core.PApplet;public class Ball {float x, y, diameter, speed;float direction;int color[] = new int [3];public Ball(float x,float y,float diameter,float speed,float direction, int red, int green, int blue) {    this.x = x;    this.y = y;    this.diameter = diameter;    this.speed = speed;    this.direction = direction;    color[0] = red;    color[1] = green;    color[2] = blue;    }    public void draw(PApplet p) {    p.noStroke();    p.fill(color[0],color[1],color[2]);    p.ellipse(x, y, diameter, diameter);    }    public void update() {    x+= speed * PApplet.cos(direction);    y+= speed * PApplet.sin(direction);    speed += 0.01;    }    private void reset() {    y = PongMain.SCR_H/2;    x = PongMain.SCR_W/2;    int n = (int)(Math.random() * 4);    if (n == 0) {        direction = ((float)Math.random()*70 +100);    }else if (n == 1) {        direction = (float)Math.random()*70 +100;    }else if (n == 2) {        direction = (float)Math.random()*70 +190;    }else if (n == 3) {        direction = (float)Math.random()*70 +280;    }    }    public void checkCollision(Paddle lPad, Paddle rPad) {    //if Bleft to the left of LpadRight        //if  Bally <ytop >ybottom     if(x <= diameter/2 ) {         lPad.increScore();            reset();     }     if(x + diameter/2 >= PongMain.SCR_W) {         rPad.increScore();            reset();     }     if (y <= diameter/2 || y+diameter/2 >= PongMain.SCR_H) {        direction = -direction;     }    if(x-diameter/2 <= lPad.getX() + PongMain.PAD_W/2) {        if(y<=lPad.getY()+ PongMain.PAD_H/2 && y>=lPad.getY()-PongMain.PAD_H/2) {                direction = PApplet.PI - direction;            }   }}
查看完整描述

1 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

聽起來你有點過于復雜了。你不需要很多花哨的邏輯來讓你的游戲由機器人控制。像這樣的事情可能會讓你走得很遠:


if(playerTwoY < ballY){

  // player two is above the ball, move player two down

  playerTwoY++;

}

else if(playerTwoY > ballY){

  // player two is below the ball, move player two up

  playerTwoY--;

}

如果您每一幀都運行此代碼,您的播放器 2 將不斷自我更新。

我強烈建議你在嘗試做任何更高級的事情之前先讓這樣的東西工作。但是在你開始工作之后,你可以嘗試一些事情:

  • 每 X 秒只更新槳的運動。這將為機器人提供更現實(更糟糕)的反應時間。

  • 為槳的運動添加一些隨機性。這將使機器人更難預測。

  • 計算球的路徑并用它來控制機器人。(這是非常先進的,可能不需要獲得機器人的工作版本。)



查看完整回答
反對 回復 2023-01-05
  • 1 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號