Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
109 lines (82 sloc) 2.86 KB

Assignment 6 Dog Hunts Sheep Game

Create your own Dog Hunts Sheep Game by doing the following five steps.

  1. A sheep running in the grass farm.

    • Use this pic as the background.
    • A sheep runs from the bottom of the window to the top.
    • The sheep stops at the top.
  2. There are twenty-five sheep and one dog

    • Twenty-five sheep run at various speed or stop a while.
    • Dog moves with the arrow keys.
  3. Dog woofs sheep

    • Dog woofs at sheep when and where he catches sheep.
    • 'Woofs!' will vanish after a while.
  4. Dog catches sheep and sends them where they belong!

    • A deepskyblue star appears when and where the dog catches a sheep.
    • The sheep return where they belong.
  5. Finish the game

    • Sheep say 'baa!' at the top.
    • The game finishes when all the sheep reach the top of the window or return the bottom.

sample68.png

sample68.png

# sample68.rb
W, H = 600, 450

class Sheep < Shoes::Widget
  def initialize x
    @s = oval x, H - 15, 15, :fill => white, :strokewidth => 3
    @a = animate(20) do
      @s.move @s.left, @s.top - [0, 0, 15, 30, 45, 60][rand(6)]
      (@s.move(@s.left, -5); @a.stop; para 'baa!', :left => @s.left, :top => 0) if @s.top < 0
    end
  end

  def pos
    return @s.left, @s.top
  end

  def woofed
    @s.hide
    @a.remove
  end

  def hidden?
    @s.hidden
  end
end

Shoes.app :width => W, :height => H do
  def dog_catch_sheep s
    return if s.hidden?
    x, y = s.pos
    s.woofed
    msg = para 'Woof!', :left => x, :top => y, :stroke => red, :weight => 'bold'
    timer(1){msg.remove}
    star x, y, 12, 10, 7, :fill => deepskyblue, :stroke => white
    oval x, H - 15, 15
    @caught += 1
  end

  @caught = 0
  background '../images/pasture.jpg'
  border black, :strokewidth => 5
  sheeps = []
  25.times{|i| sheeps << sheep(30 + 15 * i)}

  dog = oval 300, 210, 25, :fill => yellow, :strokewidth => 3
  keypress do |key|
    x, y = 0, 0
    case key
      when :up then y = -15
      when :down then y = 15
      when :left then x = -15
      when :right then x = 15
      else
    end
    dog.move dog.left + x, dog.top + y
    sheeps.each{|s| dog_catch_sheep(s) if [dog.left, dog.top] == s.pos}
    reached = 0
    sheeps.each{|s| reached += 1 if s.pos[1] == -5}
    alert("Dog caught #{@caught} sheep.") or exit if @caught + reached == 25
  end
end

Have fun!

NOTE

Original article was created by Karel Minarik. Thank you for giving us consent to use the material.

Policeman

Replaced Widget to Shoes::Widget. Then the sample68.rb worked well with Shoes-0.r1263.