-1

ブラックジャックのシミュレーションを作成しようとしています。以下はコードです...

one_suit = [2,3,4,5,6,7,8,9,10,10,10,10,11]; #the value of the cards for blackjack
full_deck = one_suit*4; #clubs, diamonds, hearts and spades
$deck = full_deck; #start off the game with a full deck

class Player
  attr_accessor :ace_count
  attr_accessor :hand_value

  def initialize(ace_count,hand_value)
    @ace_count  = ace_count;
    @hand_value = hand_value;
  end

  def self.hit
    choice_of_card = rand($deck.length); #choose a random card out of the deck
    drawn_card = $deck[choice_of_card]; #draw that random card from the deck
    if drawn_card != 0 #if there is a card there 
     $deck[choice_of_card] = 0; #remove that card from the deck by making the space blank
     if drawn_card == 11 #if you draw an ace
      self.ace_count += 1;
     end 
     self.hand_value += drawn_card ;
    else hit; #if there is no card at that space then redraw (recursion)
    end
  end

end

player1 = Player.new(0,0);
player1.hit;

ただし、実行すると、次の出力が得られます。

NoMethodError: C:\Users\Ernst\Documents\JRuby\blackjack.rb:30 の # (ルート) に対する未定義のメソッド「hit」

私は何を間違っていますか?メソッドはクラス内で定義されます。

4

1 に答える 1

2

hit はクラスメソッドです。

オブジェクトでどのように呼び出すことができますか?

self .method と書くとクラスメソッドとして定義されます。

オブジェクトまたはインスタンスメソッドを書くには

使用def method..end

あなたの場合

def hit
## remove `self` identifier from the attributes.
## e.g. ace_count += 1;
end

クラスメソッドを呼び出したい場合は、使用できます

Player.hitそしてそうではない player_obj.hit

self しかし、識別子を削除することで実行できるオブジェクト/インスタンスメソッドを呼び出す必要があると思います。

于 2012-10-04T10:30:23.140 に答える