为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 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 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信