• 通过实现石头剪刀布小游戏了解Shell编程数组的应用
#!/bin/bash
#
##***********************************************************************
## Author: sunmy
## MAil: sunmy@sunmy.pro
## Date: 2021-12-16
## FileName:Rock_Game_v2.sh
## URL: https://www.sunmy.pro
## Description:Play with PC.
## Copyright (C): 2021 All rights reserved
##***********************************************************************
#
game=(Rock Paper Scissors) ## 定义数组
num=$[RANDOM%3] ## 定义数组下标
computer=${game[$num]} ## 定义计算机函数

## 通过随机数对3取模,获取下标分别是0,1,2的数组内容,实现计算机随机出拳

Show(){
  echo "Chose you want !"
  echo "1.${game[0]}"
  echo "2.${game[1]}"
  echo "3.${game[2]}"
}

Choose(){
    read -p "Please Chose 1-3:"  Player
    echo "You ${game[$Player-1]}"
    case $Player in
    1)
      if [ $num -eq 0 ];then
          echo "Draw!"
      elif [ $num -eq 1 ];then
          echo "You win!"
      else 
          echo "I win!"
      fi;;
    2)
      if [ $num -eq 0 ];then
          echo "I win!"
      elif [ $num -eq 1 ];then
          echo "Draw!"
      else 
          echo "You win!"
      fi;;
    3)
      if [ $num -eq 0 ];then
          echo "You win!"
      elif [ $num -eq 1 ];then
          echo "You win!"
      else 
          echo "Draw!"
      fi;;  
    *)
      echo "You have to intup 1-3!"  
    esac
}

while : ; do
 Show
 sleep 1
 Choose && echo PC ${computer}" >> RockGame`date +%F`.log
 sleep 1
 echo "Pass Ctrl+D tu Quit Game!"
 sleep 1
done

  • 后期可以加上颜色更好看一些,我懒得加了,就这吧。
    石头剪刀布
Logo

更多推荐