GabrielaGuedes
GabrielaGuedes

Reputation: 27

How to fix mismatching type of object returned in ruby?

I'm developing and application using ruby2d.

I have a function that should return an object which class is "Tile".

The object that will be returned is "tileStone" and while it's inside the function, its class is "Tile" (I have used some "puts" for printing this information). But, when it returns for the main function, it returns as a "Ruby2D::Window::EventDescriptor" object. Why?

 def player1turn(grid)
      tileStone  = stoneChose(1,grid)
      puts tileStone.class #here it prints "Ruby2D::Window::EventDescriptor", which is wrong
  end

  def stoneChose(nplayer,grid)
    Window.on :mouse do |event|
      case event.button
      when :left
        grid.movableStone(grid.getPlayer(nplayer)).each do |tileStone|
          if tileStone.contains? event.x, event.y
            puts tileStone.class #here it prints "Tile"
            tileStone

          end 
        end 
      end
    end 
  end

Upvotes: 1

Views: 89

Answers (1)

ololobus
ololobus

Reputation: 4088

I am not familiar with ruby2d, but it seems, that Window.on only puts an event listener/handler, and returns EventDescriptor. Next, when the event is fired, the code inside on will be executed. Thus, your function stoneChose just set this event listener and returns this descriptor class instance.

You can check a general architecture of ruby2d project in this Pong game. In short words:

1) You have to setup all your event listeners first

def setup
    Window.on :mouse do |event|
        case event.button
        when :left
        grid.movableStone(grid.getPlayer(nplayer)).each do |tileStone|
            if tileStone.contains? event.x, event.y
                doSmthWithTileStone(tileStone)
            end
        end
    end
end

2) Define a function, which does some action with your found object on each event

def doSmthWithTileStone(tileStone)
    puts tileStone
end

3) And do the main app loop

def main
    setup

    update do
        ...
    end
end

main

Upvotes: 1

Related Questions