SlideShare a Scribd company logo
1 of 35
Download to read offline
Learning Ruby with
   RubyWarrior
     Mr. Big Cat
     2011/1/25
About Me
●   大貓
●   I like coding
●   大貓共和國: http://gaagaaga.blogspot.com
●   Twitter&Plurk: miaout17
Outline
●   Introducing RubyWarrior
●   Playing RubyWarrior
●   Solving RubyWarrior with Metaprogramming
    and DSL
What is RubyWarrior?
A game designed to teach the Ruby language
and artificial intelligence in a fun, interactive way.
Who created RubyWarrior?




RubyWarrior is created
  by Ryan Bates, the
 author of Railscasts.
Spoiler Warning!!
How to start?
In your shell:


$ gem install rubywarrior
$ rubywarrior




                                 Demo!
How to play?

  Read README and
    Edit Your Script
    Edit Your Script



   Run RubyWarrior


                          No
    Level Passed?


             Yes
 Jump to the next level
   Gain New Abilities          Demo!
What's Within?

      Player         RubyWarrior::Turn

    play_turn              attack!
        ...              detonate!
                          rescue!
                            rest!
                           shoot!
                            walk!
RubyWarrior::Space
                        direction_of
       wall?            distance_of
     enemy?                health
     captive?
     empty?                  feel
      stairs?              listen
     ticking?               look
What's Within?

      Player         RubyWarrior::Turn

    play_turn              attack!
        ...              detonate!
                          rescue!
                            rest!
                           shoot!
                            walk!
RubyWarrior::Space
                        direction_of
       wall?            distance_of
     enemy?                health
     captive?
     empty?                  feel
      stairs?              listen
     ticking?               look
What's Within?

      Player         RubyWarrior::Turn

    play_turn              attack!
        ...              detonate!
                          rescue!
                            rest!
                           shoot!
                            walk!
RubyWarrior::Space
                        direction_of
       wall?            distance_of
     enemy?                health
     captive?
     empty?                  feel
      stairs?              listen
     ticking?               look
What's Within?

      Player         RubyWarrior::Turn

    play_turn              attack!
        ...              detonate!
                          rescue!
                            rest!
                           shoot!
                            walk!
RubyWarrior::Space
                        direction_of
       wall?            distance_of
     enemy?                health
     captive?
     empty?                  feel
      stairs?              listen
     ticking?               look
Epic Mode

       Beginner   Intermediate

       Level 1      Level 1
       Level 2      Level 2
Epic                             Epic
Mode   Level 3      Level 3      Mode
       Level 4      Level 4
       Level 5      Level 5
       Level 6      Level 6
       Level 7      Level 7
       Level 8      Level 8
       Level 9      Level 9

                                  Demo!
My Epic Mode Solution
●   An AI logic that pass intermediate epic mode
    with all-S rank
●   Three implementation styles:
    ●   Naive Solution
    ●   Pure-OO Solution
    ●   Metaprogramming&DSL Solution
Naive Solution
DIRS.each do |dir|
  if @warrior.feel(dir).ticking?
    @warrior.rescue!(dir)
    return
  end
end

return if walk_to_ticking!

DIRS.each do |dir|
  if should_detonate?(dir)
    detonate!(dir)
    return
  end
end

DIRS.each do |dir|
  if @warrior.feel(dir).enemy?
    @warrior.attack!(dir)
    return
  end
end

DIRS.each do |dir|
  if @warrior.feel(dir).captive?
    @warrior.rescue!(dir)
    return
  end
end

walk!(direction_of_stairs)


                                      Demo!
Pure OO Solution

                   Demo!
Metaprogramming&DSL Solution
●   Today we won't focus on how to do
    metaprogramming and create a DSL
●   We focus on how metaprogramming & DSL
    make our life easier
What's Metaprogramming?
What's Metaprogramming?




"Writing a program that writes programs."
What's Metaprogramming?




"Writing a program that writes programs."
              哩咧供殺小?
We use attr_accessor everyday
class Warrior
  attr_accessor :health
end

w = Warrior.new
w.health = 95
puts w.health
What is attr_accessor?
class Warrior                      class Warrior
  attr_accessor :health              def health
end                                    @health
                                     end
w = Warrior.new                      def health=(val)
w.health = 95                          @health = val
puts w.health                        end
                                   end

                                   w = Warrior.new
                                   w.health = 59
                                   puts w.health




                     attr_acccessor is a METHOD!
Getter/Setter in Java
class Warrior
{
  public void setHealth(int val)
  {
    health = val;
  }
  public int getHealth()
  {
    return health;
  }
  private int health;
}

public class AttrAccessor
{
    public static void main(String[] args)
    {
      Warrior s = new Warrior();
      s.setHealth(95);
      System.out.println("Health = " + s.getHealth());
    }
}
Delegation
class Player

 def hurt?
   return false unless @last_health
   return @warrior.health < @last_health
 end

 def play_turn(warrior)
   @warrior = warrior
   if @warrior.feel.captive?
     @warrior.rescue!
   elsif !@warrior.feel.empty?
     @warrior.attack!
   elsif @warrior.health == 20 || hurt?
     @warrior.walk!
   else
     @warrior.rest!
   end
   @last_health = @warrior.health
 end

end
Delegation
class Player                               class Player

 def hurt?                                   def hurt?
   return false unless @last_health            return false unless @last_health
   return @warrior.health < @last_health       return health < @last_health
 end                                         end

 def play_turn(warrior)                      def play_turn(warrior)
   @warrior = warrior                          @warrior = warrior
   if @warrior.feel.captive?                   if feel.captive?
     @warrior.rescue!                            rescue!
   elsif !@warrior.feel.empty?                 elsif !feel.empty?
     @warrior.attack!                            attack!
   elsif @warrior.health == 20 || hurt?        elsif health == 20 || hurt?
     @warrior.walk!                              walk!
   else                                        else
     @warrior.rest!                              rest!
   end                                         end
   @last_health = @warrior.health              @last_health = health
 end                                         end

end                                        end
Delegation
Delegation Implementation
class Player

 def health
   @warrior.health
 end

 def feel
   @warrior.feel
 end

 def rescue!
   @warrior.rescue!
 end

 def attack!
   @warrior.attack!
 end

 def walk!
   @warrior.walk!
 end

 def rest!
   @warrior.rest!
 end
Delegation Implementation
class Player            require 'forwardable'

 def health             class Player
   @warrior.health
 end
                          extend Forwardable
 def feel
   @warrior.feel          def_delegators :@warrior, :health, :feel,
 end                        :rescue!, :attack!, :walk!, :rest!

 def rescue!
   @warrior.rescue!
 end

 def attack!
   @warrior.attack!
 end

 def walk!
   @warrior.walk!
 end

 def rest!
   @warrior.rest!
 end
Domain Specific Language(DSL)
               solution
DIRS.each do |dir|                 require 'player_helper'
  if @warrior.feel(dir).ticking?
    @warrior.rescue!(dir)
    return                         class Player
  end
end
                                     include PlayerHelper
return if walk_to_ticking!

DIRS.each do |dir|                   def_strategries do
  if should_detonate?(dir)             directional(:rescue!, :ticking?)
    detonate!(dir)
                                       strategy { rest! if rest_when_ticking? }
    return
  end                                  directional(:detonate!, :should_detonate?)
end                                    directional(:attack!, :enemy?)
DIRS.each do |dir|
                                       directional(:rescue!, :captive?)
  if @warrior.feel(dir).enemy?         strategy { walk!(direction_of_stairs) }
    @warrior.attack!(dir)            end
    return
  end
end

DIRS.each do |dir|
  if @warrior.feel(dir).captive?                  Player
    @warrior.rescue!(dir)
    return
  end
end
                                            PlayerHelper
walk!(direction_of_stairs)


                                                               Demo!
DSL is Everywhere
●   Rails Routing

resources :forums, :only => [:index, :show] do
  resources :posts
end

namespace :admin do
  resources :forums do
    resources :posts, :except => [:new, :create]
  end
end
DSL is Everywhere
 ●   Rake Task

task :drink do
  puts "I drink juice"
end

task :eat do
  puts "I eat sandwich"
end

task :breakfast => [:drink, :eat] do
  puts "I ate breakfast"
end
Conclusion:
                 The Ruby way I know


My RubyWarrior
                             Rails                        Rake
    Script
                                                                    Implementing high-
                                                                    level logic is incredible
   Player                Rails App                      Rake Task   simple with easy-to-
                                                                    use API and DSL


                            Rails
                                                                    Write API and create
                   ActiveRecord         ActionMailer                DSL with
PlayerHelper                                              Rake      metaprogramming
                   ActionPack           ActiveSupport               techniques

                                  ...
Lecture martial
●   Source code is available on github
    https://github.com/gaagaaga/warrior-tuesday
    ●   i-naive
    ●   i-oo
    ●   i-dsl
    ●   dsl-starter
●   Slide will be on slideshare (coming soon)
Learning Resource
●   For Beginners:
    ●   TryRuby: http://tryruby.org/
    ●   RubyWarrior: https://github.com/ryanb/ruby-warrior
    ●   The Ruby Programming Language (Book)
●   For Intermediate:
    ●   Eloquent Ruby (Book)
    ●   Metaprogramming Ruby (Book)
Any Question?

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Learning Ruby with RubyWarrior

  • 1. Learning Ruby with RubyWarrior Mr. Big Cat 2011/1/25
  • 2. About Me ● 大貓 ● I like coding ● 大貓共和國: http://gaagaaga.blogspot.com ● Twitter&Plurk: miaout17
  • 3. Outline ● Introducing RubyWarrior ● Playing RubyWarrior ● Solving RubyWarrior with Metaprogramming and DSL
  • 4. What is RubyWarrior? A game designed to teach the Ruby language and artificial intelligence in a fun, interactive way.
  • 5. Who created RubyWarrior? RubyWarrior is created by Ryan Bates, the author of Railscasts.
  • 7. How to start? In your shell: $ gem install rubywarrior $ rubywarrior Demo!
  • 8. How to play? Read README and Edit Your Script Edit Your Script Run RubyWarrior No Level Passed? Yes Jump to the next level Gain New Abilities Demo!
  • 9. What's Within? Player RubyWarrior::Turn play_turn attack! ... detonate! rescue! rest! shoot! walk! RubyWarrior::Space direction_of wall? distance_of enemy? health captive? empty? feel stairs? listen ticking? look
  • 10. What's Within? Player RubyWarrior::Turn play_turn attack! ... detonate! rescue! rest! shoot! walk! RubyWarrior::Space direction_of wall? distance_of enemy? health captive? empty? feel stairs? listen ticking? look
  • 11. What's Within? Player RubyWarrior::Turn play_turn attack! ... detonate! rescue! rest! shoot! walk! RubyWarrior::Space direction_of wall? distance_of enemy? health captive? empty? feel stairs? listen ticking? look
  • 12. What's Within? Player RubyWarrior::Turn play_turn attack! ... detonate! rescue! rest! shoot! walk! RubyWarrior::Space direction_of wall? distance_of enemy? health captive? empty? feel stairs? listen ticking? look
  • 13. Epic Mode Beginner Intermediate Level 1 Level 1 Level 2 Level 2 Epic Epic Mode Level 3 Level 3 Mode Level 4 Level 4 Level 5 Level 5 Level 6 Level 6 Level 7 Level 7 Level 8 Level 8 Level 9 Level 9 Demo!
  • 14. My Epic Mode Solution ● An AI logic that pass intermediate epic mode with all-S rank ● Three implementation styles: ● Naive Solution ● Pure-OO Solution ● Metaprogramming&DSL Solution
  • 15. Naive Solution DIRS.each do |dir| if @warrior.feel(dir).ticking? @warrior.rescue!(dir) return end end return if walk_to_ticking! DIRS.each do |dir| if should_detonate?(dir) detonate!(dir) return end end DIRS.each do |dir| if @warrior.feel(dir).enemy? @warrior.attack!(dir) return end end DIRS.each do |dir| if @warrior.feel(dir).captive? @warrior.rescue!(dir) return end end walk!(direction_of_stairs) Demo!
  • 17. Metaprogramming&DSL Solution ● Today we won't focus on how to do metaprogramming and create a DSL ● We focus on how metaprogramming & DSL make our life easier
  • 19. What's Metaprogramming? "Writing a program that writes programs."
  • 20. What's Metaprogramming? "Writing a program that writes programs." 哩咧供殺小?
  • 21. We use attr_accessor everyday class Warrior attr_accessor :health end w = Warrior.new w.health = 95 puts w.health
  • 22. What is attr_accessor? class Warrior class Warrior attr_accessor :health def health end @health end w = Warrior.new def health=(val) w.health = 95 @health = val puts w.health end end w = Warrior.new w.health = 59 puts w.health attr_acccessor is a METHOD!
  • 23. Getter/Setter in Java class Warrior { public void setHealth(int val) { health = val; } public int getHealth() { return health; } private int health; } public class AttrAccessor { public static void main(String[] args) { Warrior s = new Warrior(); s.setHealth(95); System.out.println("Health = " + s.getHealth()); } }
  • 24. Delegation class Player def hurt? return false unless @last_health return @warrior.health < @last_health end def play_turn(warrior) @warrior = warrior if @warrior.feel.captive? @warrior.rescue! elsif !@warrior.feel.empty? @warrior.attack! elsif @warrior.health == 20 || hurt? @warrior.walk! else @warrior.rest! end @last_health = @warrior.health end end
  • 25. Delegation class Player class Player def hurt? def hurt? return false unless @last_health return false unless @last_health return @warrior.health < @last_health return health < @last_health end end def play_turn(warrior) def play_turn(warrior) @warrior = warrior @warrior = warrior if @warrior.feel.captive? if feel.captive? @warrior.rescue! rescue! elsif !@warrior.feel.empty? elsif !feel.empty? @warrior.attack! attack! elsif @warrior.health == 20 || hurt? elsif health == 20 || hurt? @warrior.walk! walk! else else @warrior.rest! rest! end end @last_health = @warrior.health @last_health = health end end end end
  • 27. Delegation Implementation class Player def health @warrior.health end def feel @warrior.feel end def rescue! @warrior.rescue! end def attack! @warrior.attack! end def walk! @warrior.walk! end def rest! @warrior.rest! end
  • 28. Delegation Implementation class Player require 'forwardable' def health class Player @warrior.health end extend Forwardable def feel @warrior.feel def_delegators :@warrior, :health, :feel, end :rescue!, :attack!, :walk!, :rest! def rescue! @warrior.rescue! end def attack! @warrior.attack! end def walk! @warrior.walk! end def rest! @warrior.rest! end
  • 29. Domain Specific Language(DSL) solution DIRS.each do |dir| require 'player_helper' if @warrior.feel(dir).ticking? @warrior.rescue!(dir) return class Player end end include PlayerHelper return if walk_to_ticking! DIRS.each do |dir| def_strategries do if should_detonate?(dir) directional(:rescue!, :ticking?) detonate!(dir) strategy { rest! if rest_when_ticking? } return end directional(:detonate!, :should_detonate?) end directional(:attack!, :enemy?) DIRS.each do |dir| directional(:rescue!, :captive?) if @warrior.feel(dir).enemy? strategy { walk!(direction_of_stairs) } @warrior.attack!(dir) end return end end DIRS.each do |dir| if @warrior.feel(dir).captive? Player @warrior.rescue!(dir) return end end PlayerHelper walk!(direction_of_stairs) Demo!
  • 30. DSL is Everywhere ● Rails Routing resources :forums, :only => [:index, :show] do resources :posts end namespace :admin do resources :forums do resources :posts, :except => [:new, :create] end end
  • 31. DSL is Everywhere ● Rake Task task :drink do puts "I drink juice" end task :eat do puts "I eat sandwich" end task :breakfast => [:drink, :eat] do puts "I ate breakfast" end
  • 32. Conclusion: The Ruby way I know My RubyWarrior Rails Rake Script Implementing high- level logic is incredible Player Rails App Rake Task simple with easy-to- use API and DSL Rails Write API and create ActiveRecord ActionMailer DSL with PlayerHelper Rake metaprogramming ActionPack ActiveSupport techniques ...
  • 33. Lecture martial ● Source code is available on github https://github.com/gaagaaga/warrior-tuesday ● i-naive ● i-oo ● i-dsl ● dsl-starter ● Slide will be on slideshare (coming soon)
  • 34. Learning Resource ● For Beginners: ● TryRuby: http://tryruby.org/ ● RubyWarrior: https://github.com/ryanb/ruby-warrior ● The Ruby Programming Language (Book) ● For Intermediate: ● Eloquent Ruby (Book) ● Metaprogramming Ruby (Book)