# 如何在 java 乒乓球游戏中使球拍的一侧成为机器人？

2023-01-05 17:16:22

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;

}

}

//if Bleft to the left of LpadRight

//if  Bally <ytop >ybottom

if(x <= diameter/2 ) {

reset();

}

if(x + diameter/2 >= PongMain.SCR_W) {

reset();

}

if (y <= diameter/2 || y+diameter/2 >= PongMain.SCR_H) {

direction = -direction;

}

direction = PApplet.PI - direction;

}

}

}

## 1 回答

TA贡献1552条经验 获得超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--;

}

• 每 X 秒只更新桨的运动。这将为机器人提供更现实（更糟糕）的反应时间。

• 为桨的运动添加一些随机性。这将使机器人更难预测。

• 计算球的路径并用它来控制机器人。（这是非常先进的，可能不需要获得机器人的工作版本。）

• 1 回答
• 0 关注
• 11 浏览

0/150