Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2722

ShellScriptでじゃんけんゲームを作成

$
0
0

この記事の目的

  • ShellScriptの学習
  • じゃんけんゲームのロジックのサンプルとして共有
  • 他にいいロジックがあるか知りたい
  • じゃんけんゲームを始めて作ったので振り返ってみる

やりたいこと

  • じゃんけんゲームをShellScript(Bash)で実装
  • 対話式でじゃんけんを行う
  • コンピュータ側の手はランダムで決定
  • 先取制にする(ex.3回戦だったら2勝でじゃんけん終了)

参考にさせていただいた問題
http://g-network.boo.jp/wiki/2018/02/post-909/

実行環境

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)

ソース

#!/bin/bashreadonly GAME_TIMES=5       #何本勝負かreadonly FIRST_TO_GET_CNT=$((${GAME_TIMES}/2+1))#先取数#手の数字を名前に変換する
handcode_to_name (){case$1in
    0)echo“グー” ;;
    1)echo“チョキ” ;;
    2)echo“パー” ;;esac}game_count=1                #現在何番戦かplayer_win_cnt=0            #プレイヤー勝利数cpu_win_cnt=0               #CPU勝利数aiko_flg=false#あいこかどうかのフラグ#処理開始echo"じゃんけんを開始します。${GAME_TIMES}本勝負、${FIRST_TO_GET_CNT}勝先取です。"sleep 2

#勝負本数まで かつ プレイヤー/CPUが勝数先取するまでループする。while[${game_count}-le${GAME_TIMES}-a\${player_win_cnt}-lt${FIRST_TO_GET_CNT}-a\${cpu_win_cnt}-lt${FIRST_TO_GET_CNT}];do
 if!${aiko_flg};then
    echo"${game_count}回戦目です"sleep 2
  fi
  echo"数字を選んでください。 0:グー 1:チョキ 2:パー"is_vaild_player_hand=false
  loop_cnt=0
  # プレイヤーの手を読み取るwhile[!$is_vaild_player_hand-o${loop_cnt}-eq 0 ];do
    read input
    if[[!${input}=~ ^[0-2]$ ]];then
      echo"0 1 2のいずれかの数字を入力してください。"is_vaild_player_hand=false
      continue
    fi
    is_vaild_player_hand=true
    loop_cnt=$((${loop_cnt}+1))done

  player_hand=${input}cpu_hand=$(($RANDOM%3))echo
  sleep 2

  # 勝敗判定if[${player_hand}-eq${cpu_hand}];then
    echo"あなたの手は`handcode_to_name ${player_hand}`でした。"echo"コンピュータの手は`handcode_to_name ${cpu_hand}`でした。"echo"あいこなので再選択してください。"echo
    aiko_flg=true
    continue
  elif[$(((${player_hand}-${cpu_hand}+3)%3))-eq 2 ];then
    echo"あなたの手は`handcode_to_name ${player_hand}`でした。"echo"コンピュータの手は`handcode_to_name ${cpu_hand}`でした。"echo"あなたの勝ちです"player_win_cnt=$((${player_win_cnt}+1))game_count=$((${game_count}+1))aiko_flg=false
  elif[$(((${player_hand}-${cpu_hand}+3)%3))-eq 1 ];then
    echo"あなたの手は`handcode_to_name ${player_hand}`でした。"echo"コンピュータの手は`handcode_to_name ${cpu_hand}`でした。"echo"あなたの負けです"cpu_win_cnt=$((${cpu_win_cnt}+1))game_count=$((${game_count}+1))aiko_flg=false
  fi

  echo"現在${player_win_cnt}${cpu_win_cnt}敗"echo
  sleep 2
done

echo"あなたは${GAME_TIMES}回中${player_win_cnt}勝ちました。"#${player_win_cnt} > ${cpu_win_cnt}if[${player_win_cnt}-gt${cpu_win_cnt}];then
  echo"${player_win_cnt}${cpu_win_cnt}敗であなたの勝ちです!"elif[${player_win_cnt}-eq${cpu_win_cnt}];then
  echo"${player_win_cnt}${cpu_win_cnt}敗で引き分けです"else
  echo"${player_win_cnt}${cpu_win_cnt}敗であなたの負けです..."fi

苦労した点や感想など

  • 勝敗判定は(自分の手 - 相手の手 + 3) % 3で実装した1
  • まだ比較演算子の書き方が慣れない...
  • bool値の比較方法と正規表現に苦戦

Viewing all articles
Browse latest Browse all 2722

Trending Articles