Je K
Je K

Reputation: 39

How do I use loops?

I am programming a little game with Ruby/Shoes. I am trying to get this code into a loop. It should repeat after the last timer. I don't know how to start with this.

@timer2= timer(20)do
  @pic.move(100,170)
end

@timer2= timer(40) do
  @pic.move(350,120)
end

@timer2= timer(60) do
  @pic.move(20,400)
end

@timer2= timer(80) do
  @pic.move(420,60)
end

Upvotes: 2

Views: 88

Answers (2)

Yurii Verbytskyi
Yurii Verbytskyi

Reputation: 2052

Simple example to try timer in loops

class Picture
  def initialize
    @last_move = {}
  end

  def move(x, y)
    @last_move = { x: x, y: y }
    puts @last_move
  end

  def self.test_movement
    @pic = new
    pic_moves = [
      { t: 2, x: 100, y: 170 },
      { t: 4, x: 350, y: 120 },
      { t: 6, x: 20, y: 400 },
      { t: 3, x: 420, y: 60 }
    ]
    pic_moves.each do |pm|
      sleep(pm[:t])
      puts(pm[:t])
      @pic.move(pm[:x], pm[:y])
    end
  end
end

Picture.test_movement

Upvotes: 0

Alex Python
Alex Python

Reputation: 327

Just loop your code:

loop {
  @timer2 = timer(20) do
    @pic.move(100, 170)
  end

  @timer2 = timer(40) do
    @pic.move(350, 120)
  end

  @timer2 = timer(60) do
    @pic.move(20, 400)
  end

  @timer2 = timer(80) do
    @pic.move(420, 60)
  end
}

Use break if you need to exit the loop.

Upvotes: 0

Related Questions