1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

はじめてのシェルスクリプトでジャンケンゲーム

Last updated at Posted at 2021-05-24

はじめに

シェルスクリプトを初めて触った駆け出しエンジニアがジャンケンゲームを作成しました。

ゲームの概要

  • ジャンケンを始めるかどうかプレイヤーの入力を待つ
  • y (yes)のときゲーム実行。 n (no)やその他の入力があった場合は、ゲームは始まらない
  • プレイヤーは対話型の入力値で何を出すか決める
  • コンピューターはランダムで、何を出すか決める
  • 勝つまでゲームは続く。(負けor引き分けで終わらない)
  • コンピューターに勝った時、それまでのゲーム数を表示させる

ゲームのイメージ

game1.png

コード

.bash
# !/bin/bash

echo " >>> ジャンケンゲームを始めますか?"
echo ">>> y or n"
echo -n ">>>"
read val

### 定義
count_game=0

play_game() {
arr=( "グー" "チョキ" "パー" )

###  player入力
echo ">>> 選択して下さい"
echo ">>> 0:グー 1:チョキ 2:パー"
echo -n ">>>"
read val

### 入力チェック
if [[ ${#val} == 1 && $(echo $val | grep [0-2]) ]]
then
 ### 配列から要素を取得
 play_act=${arr[$val]}
else
 echo " 0 から 1 から 2 を入力してください!"
 exit 1
fi

### 0〜2の乱数を取得
while true
do
 num=$((RANDOM % 3))
 if (( 0 <= num && num <= 2))
 then
  break
 fi
done

### 配列から要素を取得
comp_act=${arr[$num]}

### 判定
if [[ "$play_act" == "$comp_act" ]]
then
 result="draw"
elif [[ "$play_act" == "グー" && "$comp_act" == "チョキ" ]]
then
 result="play"
elif [[ "$play_act" == "チョキ" && "$comp_act" == "パー" ]]
then
 result="play"
elif [[ "$play_act" == "パー" && "$comp_act" == "グー" ]]
then
 result="play"
elif [[ "$comp_act" == "グー" && "$play_act" == "チョキ" ]]
then
 result="comp"
elif [[ "$comp_act" == "チョキ" && "$play_act" == "パー" ]]
then
 result="comp"
elif [[ "$comp_act" == "パー" && "$play_act" == "グー" ]]
then
 result="comp"
fi


### 表示
echo "--- 自分 => [$play_act]"
echo "--- 相手 => [$comp_act]"
count_game=`expr $count_game + 1 `

### 判定
case "$result" in
 "play")
   echo "勝ちです"
   onemore=0
   ;;
 "comp")
   echo "負けです"
   onemore=1
   ;;
 "draw")
   echo "引き分けです"
   onemore=1
   ;;

### 負けた場合、再度呼び出し
if [ "$onemore" == 1 ]
then
 echo "勝つまで続けましょう!"
 play_game
else
 echo "おつかれさま!${count_game}戦目での勝利です!"
fi
}

if [[ ${#val} == 1 && ${val} == y ]]
then
 play_game
else
 echo "やらないんですね。はい。。"
fi

おわりに

プログラミングにまだまだ不慣れなのと、初めてシェルスクリプトを書いたこともあり至らない点もあるかと思います。
多目に見ていただけると幸いです。。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?