2015-12-27 15 views
6

Java konusunda yeni yeniliklerim var. Şu anda bir proje ile meşgulüm. Amaç, canlı varlıklar (insanlar) ve canlı olmayan haklar (örneğin vulcanos) ile sanal bir 2D dünya yaratmaktır. İnsanlar her zaman adımını (sadece komşu hücrelere) taşıyabilmeli ve canlı olmayan varlıklar tarafından başka şekillerde öldürülmeli veya etkilenebilmelidir.2 boyutlu ızgaraya kişi nesnelerini ekleme

Bir insan sınıfı oluşturmaya başlamak ve onları ızgaraya koymak iyi bir fikir olduğunu düşündüm. Bunlar şu ana kadar benim derslerim. Bununla birlikte, insanları ızgarada saklamakla uğraşıyorum (Tek bir hücrede birden fazla kişiyi saklamak mümkün olmalıdır).

Bu benim kişi sınıftır: Bu benim arazi sınıfı

public void setName (String name) {//give the person a name 
     this.name = name; 
    } 

    public int getAge() { 
     return age; 
    } 
    public void setAge(int age) {// give the person an age 

     this.age = age; 
    } 

    public String getGender() { 
     return gender; 
    } 
    public void setGender(String gender) { // set gender of the person 
     this.gender = gender; 
    } 
    public String getSexualPreference() { 
     return sexualPreference; 
    } 
    public void setSexualPreference(String sexualPreference) { // set sexual preference of the person 
     this.sexualPreference = sexualPreference; 
    } 
    public String getLifeGoals() { 
     return lifeGoals; 
    } 
    public void setLifeGoals(String lifeGoals) { // set lifegoals of the person 
     this.lifeGoals = lifeGoals; 
    } 
    public boolean isMarried() { 
     return isMarried; 
    } 
    public void setMarried(boolean isMarried) { 
     this.isMarried = isMarried; 
    } 
    public int getAgressionLevel() { 
     return agressionLevel; 
    } 
    public void setAgressionLevel(int agressionLevel) { 
     this.agressionLevel = agressionLevel; 
    } 
    public Terrain get_terrain(){// specify terrain in which the person lives. 
     return (Terrain) get_terrain(); 
    } 
    public Person(boolean randomAge){ //creates a person with a random age and a agression level. 
     if(randomAge==true){ 
      setAge(ThreadLocalRandom.current().nextInt(0,max_age +1));// this gives the person a random age between 0 and the chosen maximum age. 
      setAgressionLevel(ThreadLocalRandom.current().nextInt(0,max_agressionLevel +1));//this gives the person a random agression level, scaled from 0-10. 
     }else{ 
      setAge(0); 
     } 
    } 
    public void act(){ // this method specifies what a person can do all the time 
     increaseAge(); 
     if(isAlive() == true) 
     { 
      int births = reproduce(); 

      for(int b = 0; b < births; b++) 
      { 
       Location place = get_terrain().random_space(getX(), getY()); 
       if(place != null) 
       { 
        Person newpers = new Person(false); 
        get_terrain().addObject(newpers, place.getX(), place.getY()); 
       } 
      } 
     } 
    } 
    private int reproduce(){ 
     int births = 0; 
     if(canReproduce() && isMarried() && Math.random()*100 <= reproducing_prob){ 
      births +=1; 

     } return births; 
    } 
    private void increaseAge(){// increases the person's age, this can result in its dead 
     setAge(getAge() + 1); 
     if(getAge() > max_age) 
     { 
      setDead(); 
     } 
    } 
    private boolean canReproduce(){ 
     return getAge() >= adultAge; 
    } 
    public String toString() 
    { 
     return "Person, age " + getAge(); 

olduğunu. Öğeleri rastgele yerleştirmeye çalışıyorum.

import java.util.ArrayList; 
import java.util.concurrent.ThreadLocalRandom; 

public class Terrain { 
    private static int width; 
    private static int height; 
    private final static int nrOfPersons = 200; 

    public Terrain() 
    {  
     addPerson(null, null, null); 
    } 
    public static void addPerson(Person p, Location x){ //adds the persons to the terrain 
     ArrayList<Person> listOfPersons = new ArrayList<Person>(); 
     Terrain.addPerson(p, x);  

    } 
    public Location random_space(int x, int y){ 
     int x1 = ThreadLocalRandom.current().nextInt(0, width +1); 
     int y1 = ThreadLocalRandom.current().nextInt(0, height +1); 


     if(x1 < 0 || x1 >= width || y1 < 0 || y1 >= height) //check if the location is within the terrain 
     { 
      System.out.println("Your location is not within the boundaries of the world"); 
     } 
     return random_space(x1, y1); 

    } 

Ve bu benim lovation sınıftır:

public class Location { //corresponds to a place on the terrain 

    private int x; //horizontal coordinate 
    private int y; //vertical coordinate 

    /** 
    * Constructor for objects of class place 
    */ 
    public Location(int x, int y) 
    { 
     this.x = x; 
     this.y = y; 
    } 

    public boolean equals(Object obj) 
    { 
     if(obj instanceof Location) 
     { 
      Location other = (Location)obj; 
      return x == other.getX() && y == other.getY(); 
     } 

     else 
     { 
      return false; 
     } 
    } 

    public int getX() //return x coordinate 
    { 
     return x; 
    } 

    public int getY() //return y cordinate 
    { 
     return y; 
    } 
} 
+0

yüzden, ne işe etmez, tam olarak sorun nedir? –

+0

Kılavuzuma nesne eklemeyi bilmiyorum – StievieG

+0

"ızgara" nedir? Halihazırda bir araziniz var, public statik void addPerson –

cevap

2

Bu kesinlikle yanlıştır:

public static void addPerson(Person p, Location x){ //adds the persons to the terrain 
     ArrayList<Person> listOfPersons = new ArrayList<Person>(); 
     Terrain.addPerson(p, x);  

    } 

Sen listOfPersons her seferinde yeniden olmamalı: Silinene ve sonunda onu yok: o Hiçbir şey saklamıyorsun.

1 Yapıcınızda Do it:

List<Person> listOfPersons = new ArrayList<Person>(); 

public Terrain() 
{ 
// WHAT ? 
// addPerson(null, null, null); 
} 

2 addPerson => addPerson sonsuz döngüye

yapar Sen de bu bilgileri tutmak gerekir.

basit yolu Haritası: Yer => kişi böyle koymak

Map<Location,Person> grid=new HashMap<Location,Person>(); 

:

grid.put(one_location,one_person); 

böyle sınamak:

grid.contains(one_location); => get true/false 

böyle olsun :

grid.get(one_location); => get one_person 

Önemli olan: Harita ile bir yerde tek bir kişiye sahip olabilirsiniz. bununla birlikte eski kişiliğiniz. Bu arada, daha fazla listeye ihtiyacınız yok.

Diğer stratejiler Aynı yerde birden kişileri tutmak için: Kişi => konumu:

bir harita olsun. Bir yerde insanlara ihtiyacınız olduğunda, tekrarlamak zorundasınız.

Diğer olasiligimn: aynı zamanda bir Harita < Konum tutmak, Set < Kişi >>: her bir yer için, bir set var.

+0

Teşekkürler! Fakat bu çoklu iktidarların aynı yerde olabilmesi için herhangi bir yol yok mu? Her zaman adımında, insanlar birbirleriyle etkileşime girebilmeli (birbirlerini öldürmeli, evlenmeli, çocuklarını almalı ...). Cevabımda – StievieG

+0

diğer olasılıklar. Koleksiyonlar (Harita, Set, ...) ile hayal edebileceğiniz neredeyse her şeyi yapabilirsiniz. –

2

addPerson yöntem Yüzey sınıfı yerine static yöntemin bir örneği yöntem olmalıdır. Ayrıca, yöntemin yerel bir değişkeninden ziyade sınıfın bir alanı üzerinde hareket etmelidir.

Ayrıca, bir kişiyi bir konuma bağlamanın bir yoluna da ihtiyacınız olacaktır - çok sayıda şey olabilir, tüm ızgarayı temsil eden 2 D dizisi, koordinatlardan kişi nesnelerine eşlenen bir harita veya kişi üzerindeki location alanı olabilir. nesne.

public class Terrain { 
    private static int width; 
    private static int height; 
    private final Map<Location, Person> personAtLocation = new HashMap<>(); 

    public void addPerson(Person p, Location x){ 
     personAtLocation.put(x, p); 
    } 
    ... 
} 

bir Location bir Kişiyi bağlamak için en iyi mekanizma gerçekten geri kalanında elde etmeye çalıştığınız ne bağlı olacak ... Diyelim ki o zaman şu şekilde görünecektir, bir harita kullanmak diyelim senin programın.