我的机器人留在原地它应该在障碍物之间远程移动

如何解决我的机器人留在原地它应该在障碍物之间远程移动

机器人不动,虽然我觉得Command的逻辑非常简单明了!应从 Canvas 的上角向下和向右移动到左下角,同时避开障碍物。

这是创造积分的班克特

import java.lang.Math.*;
public class Punkt{ 
private int x;
private int y;
 public Punkt( int x,int y)
    {
        this.x=x;
        this.y=y;
    }
public int getX()
    {
        return x;
    }
public int getY()
    {
        return y;
    }
public void setX(int distance)
    {
        x= x + distance;
    }
public void setY(int distance)
    {
        y= y + distance;
    }
public void bewegeUm(int dx,int dy)
    {
        x= x+ dx;
        y= y+ dy;
    }
    /**
     * method for knowing the distance to another point
     */
    public double gibAbstand (Punkt otherPoint){
       return Math.sqrt((otherPoint.getY() - y) * 
                        (otherPoint.getY()- y) + 
                        (otherPoint.getX() - x) * 
                        (otherPoint.getX() - x));
        
    }
}
import java.awt.Color;
import java.awt.*;

public abstract class Figur{
    protected Punkt position;
    protected Color farbe;
    protected int width;
    protected int length;

 public Figur(){
        position=new Punkt(0,0);
        farbe=Color.red;
        width=50;
        length=40;
    }
public Figur(Punkt position,Color farbe,int width,int length)
      {
        this.position= position;
        this.farbe=farbe;
        this.width=width;
        this.length=length;
    }

    abstract int minX();
    abstract int minY();
    abstract int maxX();
    abstract int maxY();
    abstract public void zeichnen(Graphics g);

Class Kreis(Circle) 是机器人的超类

public class Kreis extends Figur{
public Kreis()
    {
        super();
        D=5;
    }
    public Kreis(Punkt position,int diameter,Color farbe)
    {
        this.position=position;
        this.width=diameter;
        this.length=diameter;
        this.farbe=farbe;
    }
 public int minX()
   {
       return this.position.getX();
    }
   public int minY()
   { 
       return this.position.getY()-this.length;
    }
   public int maxX()
   {
       return this.position.getX()+this.width;
    }
    public int maxY()
   {
       return this.position.getY();
    }
    
    
   public int getD()
    {
        return D;
     }
     
     
        public void zeichnen(Graphics g)
   {
       g.setColor(getFarbe());
       g.drawOval(getPosition().getX(),getPosition().getY(),getWidth(),getLength());
       g.fillOval(getPosition().getX(),getLength());
    }
}

这是 Class Robot,它扩展了 Class Circle。 Circle 类也是 von 抽象类 Figur 的子类。 Robot 类具有布尔方法,可以判断是否有向右或向下方向移动的空间。

public class Robot extends Kreis {



//check if it hits any wall
public boolean atWall(){
        if(minX()==0||maxX()==width||minY()==0||maxY()==Length){
            return true;
        }
        return false;
       
    }
    //check if it arrived at the end
    public boolean atTheEnd()
    {
        if(position.getX()+width>=Spielfeld.getWidth() && position.getY()+Length>=Spielfeld.getLength())
        {return true;
       }
       return false;
    }

  //Check if it hits the right Wall
    boolean atWallRight(){
        if(position.getX()+width>=Spielfeld.getWidth())
        {
            return true;
        }    
        return false;
    }
//check if it hits the Wall below
      boolean atWallBelow(){
        if(position.getY()+Length>=Spielfeld.getLength())
        {
            return true;
        }    
        return false;
    }
//check if it hits the Wall Left
      boolean atWallLeft(){
        if(position.getX()<=0)
        {
            return true;
        }    
        return false;
    }
//check if it hits the upper Wall 
     boolean atWallUp(){
        if(position.getY()<=0)
        {
            return true;
        }    
        return false;
    }

//check if it stucks between figures at the bottom 
    public boolean stucksDown(Figur figur)
    {
         if(figur.minX()<= this.maxX() && figur.maxX()>=this.minX())
            {
                if(figur.minY()==this.maxY()+1)
                    return true;  
       }
       return false;
    }

//check if it stucks between figures in the rightside 
    public boolean stucksright(Figur figur)
    {
          if(figur.minY()<=this.maxY() && figur.maxY()>=this.minY()){
              if(figur.minX()==this.maxX()+1)
              return true; 
        }
        return false;
    }
}

产生障碍物的类 Rechteck(Square)

public class Rechteck extends Figur{

private String bezeichnung;
public Rechteck (Punkt position,int length,String bezeichnung,Color farbe)
   {
        super(position,farbe,width,length);
        
        this.bezeichnung=bezeichnung;
        
    }

public void bewegeUm(Punkt verschiebevektor)
    {
        if (verschiebevektor != null) 
        { 
            position=verschiebevektor;
        }
    }
 //check if they overlapp
   public boolean ueberlappt (Figur r)
     {
         if(r.position.getX()<=this.position.getX()+this.getWidth()&&
            r.position.getX()+r.getWidth()>=this.position.getX()&&
            r.position.getY()<=this.position.getY()+this.getLength()&&
            r.position.getY()+r.getLength()>=this.position.getY())
            {
                return true;
            }
            return false;
   }
   
   public int minX()
   {
       return this.position.getX();
    }
    
   public int minY()
   { 
       return this.position.getY();
    }
    
   public int maxX()
   {
       return this.position.getX() + this.width;
    }
    
    public int maxY()
   {
       return this.position.getY() + this.length;
    }
    
   public void zeichnen(Graphics g)
   {
       g.setColor(getFarbe());
       g.drawRect(getPosition().getX(),getLength());
       g.fillRect(getPosition().getX(),getLength());
    }
}

   

这是 Spielfeld 班级,如果有空间,机器人应该在随机装箱的方格之间移动,否则如果它已经死机或碰到任何墙壁,它应该停止移动

public class Spielfeld{ 
private static final int WIDTH=800;
private static final int LENGTH=800;
private static Roboter robot= new Roboter(new Punkt(0,0),15,Color.black);

static ArrayList<Figur> GerafikSammlung = new ArrayList<>();

static public void hindernislisteErzeugen() {
      try(final Scanner eingabe=new Scanner (System.in);){
         System.out.println("how many barriers do you want?>");
         final int amount=eingabe.nextInt();
         if(amount<1){
             System.out.println("\tInvalid input,aborting...");
             return;
         }
         for(int i=1; i<=amount; i++){
             System.out.println("\tCreating Barrier "+ i + "of" + amount+"...");
             final Rechteck fittingBarrier=createFittingBarrier();
             if(fittingBarrier==null){
                 System.out.println("Problem: Could not insert new item to");
                 return;
             }
             GerafikSammlung.add(fittingBarrier);
         }
         System.out.println("\tAll barriers crated.");
         System.out.println("\nBarriers;");
         for(final Figur figur :GerafikSammlung){
             System.out.println("\t"+figur);
         }
      }
     }
    private static Rechteck createFittingBarrier(){
        //create only one Barrier per call
        final Rechteck barrier = new Rechteck(new Punkt(0,zufallszahl(1,101),"Rechteck"+(GerafikSammlung.size()+1),zufallsfarbe());
        
        //now find a matching location
        for(int i=0; i<MAX_INSERT_TRIES; i++){
            //move them so that they will be in Canvas frame
            final int x=zufallszahl(0,WIDTH- barrier.getWidth());
            final int y=zufallszahl(0,LENGTH- barrier.getLength());
            barrier.bewegeUm(x,y);
            // first check if it can fit
            if(uberschneidet(barrier)) continue; //start with next loop Cycle
            //now we got a valid Location
            return barrier; 
            //we can exit the loop here,because we do not need to find any more Locations
            //we return the object we created to the method outside can handle it and sort it in the right list
            }
        return null;   //signal Caller that we could not find an open location 
    }
       
    
    
    private static boolean uberschneidet(Rechteck square)
      {
       for(Figur figur:GerafikSammlung){
            if(square.ueberlappt(figur))
            {
                return true;
            }
           
       }
       return false;
     }
    
    
    
     //Methode um Zufallszahl erzeugen
    private static int zufallszahl(int von,int bis) 
     {
          int zufallsZahl = (int)(von+Math.random()*(bis-von+1)); // next Int Methode mit Argument
         return zufallsZahl ; //Gib Zufallszahl aus
     }
    
      //Methode um zufallfarbe erzeugen
    private static Color zufallsfarbe()
       {
        return new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
     }
     
    
     //um in Leinwand das abrufen
    public static ArrayList<Figur> get_GerafikSammlung()
     {
         return GerafikSammlung;
        }



   public void goAroundBarriers(){
          generateBarriers(); //some methods that generate Squares

//it Should first change the boolean Varriers right_Is_open and down_Is_open accourdingly
          boolean right_Is_open=true;
          boolean down_Is_open=true;

         while(!robot.atWallRight()){
         for(Figur p:GerafikSammlung){
             if(p instanceof Rechteck){
                right_Is_open=true;
                if(robot.stucksright(p)||robot.atWallRight()){
                    right_Is_open=false;
                }
                if(!right_Is_open)
                break;
             }  
         }
         for(Figur p:GerafikSammlung){
             if(p instanceof Rechteck){
                down_Is_open=true;
                if(robot.stucksDown(p)||robot.atWallBelow()){
                    down_Is_open=false;
                }
                if(!down_Is_open)
                break;
             }  
         }
       
//here is the Code,that I try to write for robot to calculate itself,where to go:       
        if(robot.atWallBelow()){
           if(right_Is_open && down_Is_open ){
               robot.bewegeUm(1,1);
               leinwand.zeichnen(GerafikSammlung);
               leinwand.warte(10);
           }
        else if(right_Is_open && !down_Is_open){
              robot.bewegeUm(1,0);
               leinwand.zeichnen(GerafikSammlung);
               leinwand.warte(10);

         }
          else if(down_Is_open && !right_Is_open){
               robot.bewegeUm(0,1);
               leinwand.zeichnen(GerafikSammlung);
               leinwand.warte(10);
       }
          else if(!right_Is_open && !down_Is_open){
           break;
           }
         }
       }
    
      }

为了完整起见,类 Leinwand :

public class Leinwand{
private static Leinwand leinwandSingleton;

    public static Leinwand gibLeinwand() {
        if (leinwandSingleton == null) {
            leinwandSingleton = new Leinwand(800,800,Color.white,"BlueJ Figuren Demo");
        }
        leinwandSingleton.setzeSichtbarkeit(true);
        return leinwandSingleton;
    }

    private JFrame fenster;
    private Zeichenflaeche zeichenflaeche;
    private Graphics2D graphic;
    private Color hintergrundfarbe;
    private Roboter roboter;
    private Image leinwandImage;

 public Leinwand( int width,Color grundfarbe,String titel) {
        fenster = new JFrame();
        zeichenflaeche = new Zeichenflaeche();
        fenster.setContentPane(zeichenflaeche);
        fenster.setTitle(titel);
        fenster.setLocation(30,30);
        zeichenflaeche.setPreferredSize(new Dimension(width,length));
        hintergrundfarbe = grundfarbe;
        fenster.pack();
        fenster.setVisible(true);
    }
 public void setzeSichtbarkeit(boolean sichtbar) {
        if (graphic == null) {
            // erstmaliger Aufruf: erzeuge das Bildschirm-Image und fülle
            // es mit der Hintergrundfarbe
            Dimension size = zeichenflaeche.getSize();
            leinwandImage = zeichenflaeche.createImage(size.width,size.height);
            graphic = (Graphics2D) leinwandImage.getGraphics();
            graphic.setColor(hintergrundfarbe);
            graphic.fillRect(0,size.width,size.height);
            graphic.setColor(Color.black);
        }
        
    }
private class Zeichenflaeche extends JPanel {
        private static final long serialVersionUID = 20060330L;

       
       
 
       public void paintComponent(Graphics g){
          
            super.paintComponent(g);
            
            for(int j=0; j<Spielfeld.get_GerafikSammlung().size();j++)
            {
              Figur s= Spielfeld.get_GerafikSammlung().get(j);
              s.zeichnen(g);
            }
       }
    
   public void repaintFiguren(ArrayList<Figur> figuren)
        {
           
       for( Figur f: Spielfeld.get_GerafikSammlung()){
          for(int i=i<Spielfeld.get_GerafikSammlung().size();i++)
            {if(f instanceof Rechteck){
              repaint(figuren.get(i).getPosition().getX(),figuren.get(i).getPosition().getY(),figuren.get(i).getWidth(),figuren.get(i).getLength());
                  
              }
        else if(f instanceof Kreis){
               repaint(figuren.get(i).getPosition().getX(),figuren.get(i).getLength());
                  
            }
          }
       }
    }
  }

public void zeichnen(ArrayList<Figur> figur){
          
          zeichenflaeche.repaintFiguren(figur);
          
        }

public void warte(int millisekunden) {
        try {
            Thread.sleep(millisekunden);
        } catch (Exception e) {
            // Exception ignorieren
        }
     }
       
       
}


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-