0

下面是模拟一个简单的二十一点游戏的代码。玩家和庄家(房子)抽两张牌。玩家然后击牌直到他达到 17。庄家(房子)然后击球直到他与玩家平局或破产。考虑到玩家先玩,他获胜的几率对于任何策略都应该低于 50%。然而,由于某种原因,当我重复模拟时,玩家似乎赢得了超过 50% 的时间。我的代码中一定有一些错误给了我这个结果。

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.dup; #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 hit #instance method, vs. self.hit = class method
    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
    $deck.delete_at(choice_of_card); #remove that card from the array
    if drawn_card == 11 #if you draw an ace
     self.ace_count += 1;
    end 
    self.hand_value += drawn_card;
  end


  def flip_aces
    while self.hand_value > 21 && self.ace_count > 0 #repeat until hand is below 21 or aces are all flipped
     self.ace_count -= 1 #ace gets flipped to a 1
     self.hand_value -= 10 #ace goes from 11 to 1
    end
  end

end


def oneplayergame
 $deck = $full_deck.dup; #start a new game with a full deck 
 #generate the house and the player 
 house = Player.new(0,0);
 player1 = Player.new(0,0);
 #both the house and the player draw two cards
 house.hit; house.hit; player1.hit; player1.hit;
 while player1.hand_value <= 17 #PLAYER STRATEGY: ON WHAT CARD DOES THE PLAYER STAND
  player1.hit;
  player1.flip_aces; 
 end
 while house.hand_value < player1.hand_value && player1.hand_value <=21 #HOUSE DRAWS CARDS IF UNDER PLAYER VALUE AND PLAYER IS NOT BUST
  house.hit;
  house.flip_aces; 
 end
 #outcome



 if player1.hand_value < house.hand_value && house.hand_value <= 21
  return -1;
 elsif player1.hand_value > house.hand_value && player1.hand_value <= 21
  return 1;
 elsif player1.hand_value < house.hand_value && house.hand_value > 21
  return 1;
 elsif player1.hand_value > house.hand_value && player1.hand_value > 21
  return -1;
 else return 0;
 end
end

#the simulation
wins = 0;
losses = 0;
rounds=10000;

for i in 1..rounds
 oneplayergame;
 if oneplayergame >0 
  wins +=1;
 elsif oneplayergame <0
  losses +=1
 end
end

print wins/(wins+losses).round(3)*100;
4

1 回答 1

2

这段代码

for i in 1..rounds
 oneplayergame;
 if oneplayergame >0 
   wins +=1;
 elsif oneplayergame <0
   losses +=1
end

错了:那是跟注oneplayergame三次:只有当玩家输掉第二次和第三次跟注时才算输,这会扭曲结果。您应该只调用oneplayergame一次,将结果分配给局部变量

于 2012-10-22T07:30:43.820 回答