All posts by info@distinguishedvision.com

My Rails Learning Journey – “Breakable Toy” #2 – Blackjack in Rails – 02 Jan 2014

So I have wrapped up, for now, writing a Blackjack game in Ruby. It is pretty basic and runs in the console.

The Github repo for this version is at https://github.com/AxleMaxGit/blackjack-game

 

Next I am going to try to build a Blackjack game in Rails. I don't think this kind of app is a good fit for Rails however I am going to give it a shot. Ultimately every app, challenge, etc is going to help me grow my understanding of Ruby, Rails, Git, etc.

My Rails Learning Journey – “Breakable Toy” #1 – Blackjack – 26 Dec 2013

Wow!! I think I made a breakthrough ove the last 2 days & nights. I think I finally get OOP, classes, methods, etc. It is such a great feeling.

Tonight I refactored my code and moved a bunch of methods into the classes they should always have belonged to.

I have set up a Github Repo for my code https://github.com/AxleMaxGit/blackjack-game/tree/master/app/ruby.

I am still doubting some aspects of what I have done so I posted a question on Stack Overflow here (http://stackoverflow.com/questions/20784408/am-i-passing-this-object-as-a-parameter-too-often)

I have started to read Practical Object-Oriented Design in Ruby (POODR) (http://www.poodr.com/) and it seems to be a great book. Even I can understand it so far. :-)

My Github Learning Journey – Set Up Remote Github Repo for my Ruby Blackjack Game – 26 Dec 2013

Background

I am building a Blackjack Game in Ruby. Eventually I want it to be a Rails app but for now I am just building the logic in Ruby and storing them in the app/ruby folder of a vanilla Rails file structure.

Task

I am hopeless with Github. I find it really confusing. This is how I have set up a remote repo on my Github account to version control the source code of this app as I progress.

I have already gone way further than I should have before setting up a repo but I have been focussing on learning & practising the Ruby for the last few days.

Action

Starting in the root of the rails app. The folder is called blackjack   

    git init

    git add .

    git commit -m "setting up remote repo for my Blackjack app

Went to my Git Hub account (https://github.com/AxleMaxGit) and set up a new repo called blackjack-game. Checked the box to add a README.md file and added some notes. This means I will need to pull and merge the remote repo with my blackjack folder (master branch) before I try to push to the remote repo.

git remote add origin git@github.com:AxleMaxGit/rails-blackjack.git

git remote -v
      origin	https://github.com/AxleMaxGit/blackjack-game.git (fetch)
      origin	https://github.com/AxleMaxGit/blackjack-game.git (push)
git push -u origin master

You should be all set.

 

Note: See this Stack Overflow question for details of what the "-u" switch above does? http://stackoverflow.com/questions/7270802/whats-the-use-of-u-in-git-push-u-origin-master

My Rails Learning Journey – “Breakable Toy” #1 – Blackjack – 24 Dec 2013

Last week at the local Ruby on Rails meetup – RoRo Sydney – Harry Curotta (@hiharryhere) gave a talk called "Rollercoaster on Rails: 1 year post career change". It was a great talk to hear for a person with hopes to cross the chasm from beginner to capable Rubyist . To hear that someone else has made it and how long it took them.

Harry talked about the idea of making some "breakable toys", some throw-away code that only really exists for the purpose of learning and experimentation. I had already had the same idea 2 weeks before but the term "breakable toys" sums the idea up perfectly and I am stealing it. Thanks Harry.

So it was Christmas eve and I have some time off work to sit down and code!! I woke up half dreaming / half daydreaming about writing a Blackjack program. A perfect breakable toy to help me learn. At the start of 2013 I took a Java course (that I really struggled with) and the main project was to write a BlackJack program. So there was the benefit of haviong talked through a similar object model to the one I will need but also I never really grasped the concepts of classes and object orientation. I understood the idea but I couldn't apply it.

I lay there thinking through the problem for what felt like a couple of hours until I was literally aching to get out of bed and code it. I think I am hooked on this stuff. It makes me feel so great to be so into programming because it might be the hardest thing I have ever attempted and I feel like, through perserverance, I am finally starting to crack it!

I decided to start with the first object. Simple. What do I need? I need a deck of cards. I quickly realised that it would be far simpler to switch my thinking from Rails to Ruby (which may not be true to an experienced programmer but I wanted to focus on the logic) and ignore the web framework for now. Just get the logic working. So I spent the day with Sublime Text 2 and BASH building the beginnings of my BlackJack app.

The first cut was quite procedural, not at all object oriented.

rank = Array(1..13)
suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
deck = Array.new(52)
counter = 0

suits.each do |s|
  rank.each do |n|
    if n == 1
      cardname = "Ace"
      cardvalue = 11
    elsif n == 11
      cardname = "Jack"
      cardvalue = 10
    elsif n == 12
      cardname = "Queen"
      cardvalue = 10
    elsif n == 13
      cardname = "King"
      cardvalue = 10
    else
      cardname = n.to_s
      cardvalue = n
    end  
    deck[counter] = {:rank => (n.to_s), :suit => s, :cardname => cardname, :cardvalue => cardvalue}     
    counter +=1
  end
end
deck.shuffle!

So I decided to try and build some classes and make it a bit more "OO". I set it up for a future with multiple decks and added the ability to deal a hand and take additional cards. All of a sudden it is 1am on Christmas day and time to go to bed. On another date I might have stayed up all night. (Note: There is a commented out easier way to build the deck but I was playing around so I've left in an alternative that I think allows for changes in the number of ranks if I was using a different style of playing cards or in a different game altogether.)

DECKSIZE = 52

class Card
  RANKS = %w(2 3 4 5 6 7 8 9 10 J Q K A)
  SUITS = %w(Spade Heart Club Diamond)

  attr_accessor :rank, :suit
  def initialize(id)
    self.rank = RANKS[id % 13]
    #easier way to generate suits
    #self.suit = SUITS[id % 4]
    if id < DECKSIZE / SUITS.length
      self.suit = SUITS[0]
    elsif id < DECKSIZE / SUITS.length*2
      self.suit = SUITS[1]
    elsif id < DECKSIZE / SUITS.length*3
      self.suit = SUITS[2]
    else
      self.suit = SUITS[3]   
    end
  end
end

class Deck
  attr_accessor :cards
  def initialize
    # shuffle array and init each Card
    puts "Creating & Shuffling the Deck"
    self.cards = (0..(DECKSIZE-1)).to_a.shuffle.map { |id| Card.new(id) }
    #unshuffled
    #self.cards = (0..(DECKSIZE-1)).to_a.shuffle.map { |id| Card.new(id) }
  end
end

class Hand
  attr_accessor :cards
  def initialize(deck)
    # start with 2 cards from the deck
    self.cards = (0..1).to_a.map { |id| deck.cards.pop }
  end

  def hand_total
    puts "Hand Total"
    total = 0
    self.cards.each do |c|
      puts "C.RANK is #{c.rank}"
      #puts c.rank.to_i
      if c.rank == "A" 
        total += 11
      elsif c.rank == "J" || c.rank == "Q" || c.rank == "K"
        total += 10 
      else
        total += c.rank.to_i
      end
    end 
    puts "The hand total so far is #{total}"
  end
end

#BEGIN THE GAME ... Create & Shuffle the deck
deck1 = Deck.new
#Deal a starting hand
hand1 = Hand.new(deck1)
#Show the running total
hand1.hand_total
#Take another card
hand1.cards.push(deck1.cards.pop)
hand1.hand_total

There are probably a million ways to make this code better but I went to bed feeling pleased that I had made some progress today.

My Rails Learning Journey – Testing – TDD – 21 Dec 2013

Learn Rails 4 native testing: http://guides.rubyonrails.org/testing.html

Watched a great video tutorial from Rails for Zombies.

Read a great post on how to use MiniTest. I think it is the default testing library in Ruby now. http://www.rubyinside.com/a-minitestspec-tutorial-elegant-spec-style-testing-that-comes-with-ruby-5354.html

The article above references a talk about Minitest by its author. http://www.everytalk.tv/talks/159-Cascadia-Ruby-Size-Doesn-t-Matter

Made a schoolboy error when trying to understand a bang in front of a statement instead of after. Posted a Stack Overflow question then slapped my forehead when I got the answer.

http://stackoverflow.com/questions/20714017/what-does-a-bang-before-a-variable-do/20714049?noredirect=1#comment31029834_20714049

15 TDD steps to a rails app

http://andrzejonsoftware.blogspot.com.au/2007/05/15-tdd-steps-to-create-rails.html

Other stuff I have learned before I started this blog

How to replace the default Rails 4 web servr, WebBrick with a different web server that is less verbose (Thin web server) http://code.macournoyer.com/thin/usage/

How to do active model validations. My first use case was simply validating the presence of data in a form. (http://guides.rubyonrails.org/active_record_validations.html)

How to use the rails console (rails c) to play around with the active record query interface. Basically to create and retrieve records from the sqlite3 database. Railscasts has a pretty good lesson on this. (http://railscasts.com/episodes/202-active-record-queries-in-rails-3)

How to use flash messages as a way to pass data between actions / controllers. (http://guides.rubyonrails.org/action_controller_overview.html#the-flash). In my case the first tome the need for this arose when I was wrestling with how to capture and pass model validation error messages between controllers. See the Stack Overflow question for more details on that one. (http://stackoverflow.com/questions/20368717/rails-i-cant-pass-a-validation-error-in-a-redirect/20582976?noredirect=1#20582976)

 

 

My Rails Learning Journey – HTTP Headers & Routing – 22 Dec 2013

Learn about HTTP Headers: (http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/)

Have another look at routing. (http://guides.rubyonrails.org/v2.3.11/routing.html). I’m hoping to get a grip on nested routes.

Here’s an interesting point. The sequence of the routes in routes.rb is important. “The request will be dispatched to the first matching route. If there is no matching route, then Rails returns HTTP status 404”