Monday, November 30, 2009

[Level 3] OX shell game.

Today, I deliver the shell programming course.
And I think, why not to write a simple shell script game.
The script should be to fun.

#!/usr/bin/bash
showUsage() {
  cat<<EOF
Usage:
  $0 init/load 0/X
Ex.
  $0 init 0/X
  $0 load O/X
EOF
}

checkLine() {
  sDisp=$1
  s1=`echo $sDisp | cut -d'|' -f1`
  s2=`echo $sDisp | cut -d'|' -f2`
  s3=`echo $sDisp | cut -d'|' -f3`
  s4=`echo $sDisp | cut -d'|' -f4`
  s5=`echo $sDisp | cut -d'|' -f5`
  s6=`echo $sDisp | cut -d'|' -f6`
  s7=`echo $sDisp | cut -d'|' -f7`
  s8=`echo $sDisp | cut -d'|' -f8`
  s9=`echo $sDisp | cut -d'|' -f9`
  if [ $s1 == $s2 ] && [ $s2 == $s3 ]
  then
    echo "$s1 wins..." && return 0
  elif [ $s4 == $s5 ] && [ $s5 == $s6 ]
  then
    echo "$s4 wins..." && return 0
  elif [ $s7 == $s8 ] && [ $s8 == $s9 ]
  then
    echo "$s7 wins..." && return 0
  elif [ $s1 == $s4 ] && [ $s4 == $s7 ]
  then
    echo "$s1 wins..." && return 0
  elif [ $s2 == $s5 ] && [ $s5 == $s8 ]
  then
    echo "$s2 wins..." && return 0
  elif [ $s3 == $s6 ] && [ $s6 == $s9 ]
  then
    echo "$s3 wins..." && return 0
  elif [ $s1 == $s5 ] && [ $s5 == $s9 ]
  then
    echo "$s1 wins..." && return 0
  elif [ $s3 == $s5 ] && [ $s5 == $s7 ]
  then
    echo "$s3 wins..." && return 0
  else
    return 1
  fi
}

checkDone() {
  sArea=`cat $0.area | sed -e 's/[ ]*//g'`
  sDisp=`cat $0.disp | sed -e 's/n//g' | sed -e 's/. - ./|/g' | sed -e 's/[ -.]*//g'`
  checkLine $sDisp && return 0
  [ `echo $sArea | grep -c "[1-9]"` -eq 0 ] && echo "even..." && return 0
  return 1
}

############################ main
sAct=${1:-init}
case $sAct in
init)
  sArea="1 2 3 4 5 6 7 8 9"
  echo $sArea > $0.area
  sDisp="1 | 2 | 3n- . - . -n4 | 5 | 6n- . - . -n7 | 8 | 9"
  echo $sDisp > $0.disp
  sOX=$2
  clear && echo $sDisp | sed -e 's|n|\\\\n|g' | xargs echo
  if [ "$sOX" == "X" ] || [ "$sOX" == "x" ]
  then
    sOX=X
  else
    sOX=O
  fi
  $0 load $sOX
  ;;
load)
  sOX=$2
  sArea=`cat $0.area`
  sDisp=`cat $0.disp`
  while true
  do
    read -p "Please enter your pos ($sOX): " nPos
    sNArea=`echo $sArea | sed -e "s/$nPos//"`
    [ "$sArea" != "$sNArea" ] && sArea=$sNArea && break
  done
  echo $sArea > $0.area
  sDisp=`echo $sDisp | sed -e "s/$nPos/$sOX/"`
  echo $sDisp > $0.disp
  clear && echo $sDisp | sed -e 's|n|\\\\n|g' | xargs echo
  checkDone && rm $0.area $0.disp && exit 0
  if [ $sOX == "O" ]
  then
    sOX=X
  else
    sOX=O
  fi
  $0 load $sOX
  ;;
*)
  showUsage
  exit 1
  ;;
esac





Wish this helps.

regards,
Stanley Huang