2015-12-09 2 views
5

Для моей игры я внедрил систему инвентаризации. Когда нажимается экран, MousePressedEvent проходит через все layers в игре, ко всем объектам, которые наследуют EventListener (My EventListener). Класс EventListener отлично работает и, используя его, как показано ниже, мне удалось получить мой инвентарь, чтобы вы могли удалить элементы из слота и вернуть их обратно. Однако я хотел бы извлечь их из любого слота, содержащего элементы, и поместить их в любой другой слот (если целевой слот пуст). Я думал, что я бы это допустил, так как в операторе if я не проверял, что, если выбран слот, я добавляю его в слот независимо. Но это на самом деле не работает. Есть идеи?Java: разрешить действие капли в моем инвентаре?

код в Slot.java классе:

public boolean onMousePressed(MousePressedEvent e) { 
    Point p = new Point(Mouse.getX(), Mouse.getY()); 
    if (!this.getBounds().contains(p)) return false; 
    boolean left = (e.getButton() == MouseEvent.BUTTON1); 
    boolean right = (e.getButton() == MouseEvent.BUTTON3); 
    boolean hasItems = (items.size() > 0); 
    if (this.getBounds().contains(p)){ 
     if (right && !selected && hasItems){ 
      select(true); 
      s = new Slot(new Vector2i(Mouse.getX(), Mouse.getY())); 
      addComponent(s); 
      s.add(items.get(0)); 
      remove(items.get(items.size() - 1)); 
     } else if (right && selected){ 
      s.add(items.get(0)); 
      remove(items.get(items.size() - 1)); 
      if (items.size() == 0) { 
       setBackgroundImage(ImageUtil.getImage("/ui/panels/inventory/slot.png")); 
       selected = false; 
       return true; 
      } 
      return true; 
     } else if ((left || right) && s==null) { 
      return true; 
     } else if (left && s != null){ //If left clicked, add to the slot from s regardless of if we are selected. 
      add(s.getItems().get(0)); 
      s.remove(s.getItems().get(s.getItems().size() - 1)); 
      if (s.getItems().size() == 0){ 
       s.setBackgroundImage(ImageUtil.getImage("/ui/panels/inventory/slot.png")); 
       removeComponent(s); 
       s = null; 
       selected = false; 
       return true; 
      } 
     } 
    } 
    return false; 
} 

В псевдокоде:

If (Mouse is clicked) : 
    if (the mouse isn't the bounds of the slot) return false (alert we haven't handled the event) 
    if (we contain the mouse cursor) : 
    if (right is pressed and we aren't selected) : 
     select 
     create a temporary slot at the mouse location 
     remove item from this slot 
     add it to the temporary slot 
     return true 
    else if (right is pressed and we are selected) : 
     add item to temporary slot 
     remove item from selected slot 
     return true 
    else if (we press left or right while temporary slot is null) : 
     return true (tell the dispatcher we have handled the event) 
    //This following else if statement is supposed to add an item to a clicked slot whether that slot is selected or not, but doesn't work 
    else if (left is pressed and temporary slot isn't null) : 
     add the item to the clicked slot 
     remove it from the temporary one 
     return true 
    return false if none of the above applies 

Спасибо :)

+1

Я не вижу, как этот код относится к описанию. Можете ли вы разбить код на минимальный пример и дать объяснение тому, что он делает, и что он не делает в терминах программирования, таких как списки и циклы, и если и так? Понятия вашей игры не очень актуальны для кода. – zapl

+1

@zapl лучше? Я добавил версию псевдокода, чтобы прояснить ситуацию. –

+1

Можете ли вы указать, какая часть вашего псевдокода работает не так, как вы ожидаете? Там много краевых случаев .... –

ответ

2

Добавляя в печатных строк в каждой else if заявлении, я обнаружил, что, когда я пытаюсь для добавления элемента из временного слота в другой слот, временный интервал равен нулю. Это связано с тем, что при создании временного слота он создается экземпляром выбранного вами слота, поэтому тот, который вы пытаетесь добавить, не имеет доступа к временному интервалу. Чтобы обойти это, я переместил временный слот как переменную для каждого экземпляра, сделав его статическим. Код теперь отлично работает