package com.rthoni.uqac.pigeon; import java.util.List; import java.util.Random; /** * Created by ZHAJOR on 30/10/2016. */ public class Pigeon implements Runnable{ private int x; private int y; private String name; private Thread t; private final Game game; private static final int speed = 10; public Pigeon(String name, Game g) { Random r = new Random(); x = r.nextInt(700); y = r.nextInt(700); this.name = name; this.game = g; } @Override public void run() { while (true) { synchronized (game) { List foods = game.getFoods(); Food best = new Food(); int bestFoodX = 0, bestFoodY = 0, distance = -1, bestIndex = -1, index = 0; for (Food food : foods) { if (distance == -1) { distance = computeDistance(food.getX(), food.getY()); bestFoodX = food.getX(); bestFoodY = food.getY(); bestIndex = index; best = food; } else if (distance > computeDistance(food.getX(), food.getY())) { distance = computeDistance(food.getX(), food.getY()); bestFoodX = food.getX(); bestFoodY = food.getY(); bestIndex = index; best = food; } index++; } if (distance != -1 && distance <= Pigeon.speed) { this.x = best.getX(); this.y = best.getY(); foods.remove(best); game.setFoods(foods); System.out.print("Eat by " + this.name + "\n"); } else if (distance != -1){ this.computeNewPosition(best.getX(), best.getY()); } } // Random r = new Random(); // int moveX = r.nextInt(10); // int moveY = r.nextInt(10); // this.x += moveX; // this.y += moveY; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private int computeDistance(int x, int y) { int diffx = this.x > x ? this.x - x : x - this.x; int diffy = this.y > y ? this.y - y : y - this.y; return diffx + diffy; } private void computeNewPosition(int x, int y) { int moves = Pigeon.speed; while (moves > 0 ) { if (this.x > x) { this.x--; moves--; } if (this.x < x) { this.x++; moves--; } if (this.y < y) { this.y++; moves--; } if (this.y > y) { this.y--; moves--; } } } public void start () { System.out.println("Starting " + name ); if (t == null) { t = new Thread (this, name); t.start (); } } public int getX() { return x; } public int getY() { return y; } }