ユーザ用ツール

サイト用ツール


youtube:guess-number-cr

数当てゲーム (CLI)

game.cr

MAX_GUESSES = 10

def play_game
  the_number = rand(1..100)

  guesses = 0
  success = false
  last_guess = 0

  while !success && guesses < MAX_GUESSES
    guess = read_number
    guesses += 1

    if guess == the_number
      success = true
    else
      large_or_small = guess > the_number ? "too large" : "too small"
      print "#{large_or_small} (#{guesses}/#{MAX_GUESSES}). "
      if last_guess > 1
        puts "last guess: #{last_guess}"
      else
        puts
      end
      last_guess = guess
    end
  end

  if success
    puts "Conguratulations!"
  else
    puts "I'm sorry, but you are not an esper."
  end
end

def read_number
  print "guess? "
  while true
    r = read_line
    if r.to_i?
      break
    end
    puts "#{r} is not a number, try again."
    print "guess? "
  end
  r.to_i
end

def ask_play_again
  print "play again [y/N]? "
  read_line.upcase.starts_with? "Y"
end

play_game
while ask_play_again
  play_game
end

Makefile

.PHONY: all
all: game

game: game.cr
	crystal build $< -o $@

youtube/guess-number-cr.txt · 最終更新: 2024/02/29 11:50 by freemikan

特に明示されていない限り、本Wikiの内容は次のライセンスに従います: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki