边学Ruby,边玩游戏,一个网页+自己源码

在无意间发现的网址中,作者沉浸于一款名为Ruby Warrior的网页游戏中,通过编写Ruby代码来闯关。游戏包含从第一关到第九关的挑战,作者戏称这种专注为常年扣鼻屎的习惯,幽默地展示了学习编程的乐趣和独特方式。
摘要由CSDN通过智能技术生成

链接如下

https://www.bloc.io/ruby-warrior/#/warriors/8831/levels/1


一不小心碰到了这个网址,一不小心玩了一下午。

君问为何如此?

此乃常年扣鼻屎而成吼吼吼害羞

如下


第一关:

class Player
  def play_turn(warrior)
     warrior.walk!
  end
end


第二关:

class Player
  def play_turn(warrior)
      
      if warrior.feel.enemy?
          warrior.attack!
      else
          warrior.walk!
      end
  end
end

第三关:

class Player
  def play_turn(warrior)
     
     if warrior.feel.enemy?
         warrior.attack!
     else
         if warrior.health < 20
              warrior.rest!
              return 0
         end
         warrior.walk!
     end
  end
end

第四关:

class Player
 @health = 20
  def play_turn(warrior)
     
     if warrior.feel.enemy?
         warrior.attack!
     else
         if warrior.health < 20 && warrior.health == @health
              warrior.rest!
              @health += 2
              return 0
         end
         warrior.walk!
     end
     @he
以下是 Ruby 的实现: ``` class Card attr_reader :value def initialize(value) @value = value end end class Deck FACES = %w[2 3 4 5 6 7 8 9 10 J Q K A].freeze SUITS = %w[♠ ♥ ♦ ♣].freeze def initialize @deck = [] SUITS.each do |suit| FACES.each do |face| @deck << Card.new("#{face}#{suit}") end end end def shuffle @deck.shuffle! end def draw @deck.pop end end class Game POINTS_MAP = { 'J' => 10, 'Q' => 10, 'K' => 10, 'A' => [1, 11] }.freeze attr_reader :player_hand, :dealer_hand def initialize @deck = Deck.new @deck.shuffle @player_hand = [] @dealer_hand = [] 2.times do @player_hand << @deck.draw @dealer_hand << @deck.draw end end def hit @player_hand << @deck.draw end def play_dealer while points(@dealer_hand) < 17 @dealer_hand << @deck.draw end end def points(hand) hand.map(&:value).reduce(0) do |sum, value| face = value[0..-2] if POINTS_MAP.key?(face) if POINTS_MAP[face].is_a?(Array) sum + POINTS_MAP[face][1] else sum + POINTS_MAP[face] end else sum + face.to_i end end end def winner player_points = points(@player_hand) dealer_points = points(@dealer_hand) if player_points > 21 :dealer elsif dealer_points > 21 :player elsif dealer_points > player_points :dealer elsif player_points > dealer_points :player else :tie end end def display puts "Player has: #{@player_hand.map(&:value).join(', ')}. Total: #{points(@player_hand)}" puts "Dealer has: #{@dealer_hand.first.value}, [hidden]" end end game = Game.new game.display while game.points(game.player_hand) < 21 puts "Do you want to hit or stay? (h/s)" input = gets.chomp break if input == 's' game.hit game.display end if game.points(game.player_hand) > 21 puts "You busted!" else game.
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值