youtube:guess-number-cr
差分
このページの2つのバージョン間の差分を表示します。
両方とも前のリビジョン前のリビジョン次のリビジョン | 前のリビジョン | ||
youtube:guess-number-cr [2024/02/28 18:26] – 削除 - 外部編集 (不明な日付) 127.0.0.1 | youtube:guess-number-cr [2024/02/29 11:50] (現在) – freemikan | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== 数当てゲーム (CLI) ====== | ||
+ | |||
+ | ===== game.cr ===== | ||
+ | |||
+ | |||
+ | <file crystal> | ||
+ | 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 "# | ||
+ | if last_guess > 1 | ||
+ | puts "last guess: # | ||
+ | else | ||
+ | puts | ||
+ | end | ||
+ | last_guess = guess | ||
+ | end | ||
+ | end | ||
+ | |||
+ | if success | ||
+ | puts " | ||
+ | else | ||
+ | puts " | ||
+ | end | ||
+ | end | ||
+ | |||
+ | def read_number | ||
+ | print " | ||
+ | while true | ||
+ | r = read_line | ||
+ | if r.to_i? | ||
+ | break | ||
+ | end | ||
+ | puts "#{r} is not a number, try again." | ||
+ | print " | ||
+ | end | ||
+ | r.to_i | ||
+ | end | ||
+ | |||
+ | def ask_play_again | ||
+ | print "play again [y/N]? " | ||
+ | read_line.upcase.starts_with? | ||
+ | end | ||
+ | |||
+ | play_game | ||
+ | while ask_play_again | ||
+ | play_game | ||
+ | end | ||
+ | </ | ||
+ | |||
+ | ===== Makefile ===== | ||
+ | |||
+ | |||
+ | <file makefile> | ||
+ | .PHONY: all | ||
+ | all: game | ||
+ | |||
+ | game: game.cr | ||
+ | crystal build $< -o $@ | ||
+ | </ | ||