Linha de comando jogo de cobra?

13

Eu me lembro há muito tempo de ter um celular antigo que tinha um jogo que eu acho que foi chamado de "Snake" ou "Snakes" e basicamente você pode mudar a direção da cobra com a flecha. chaves, a cobra não pode tocar-se (ou game over), mas se tocar as bordas do mapa, ele simplesmente aparecerá no outro lado. O objetivo do jogo era fazer com que a cobra comesse comida, mas com cada pedaço de comida (toda vez que comia um pouco mais apareceria em outro lugar, mas normalmente um de cada vez) a cobra ficaria um pouco mais longa mais difícil de jogar o jogo.

Tenho certeza de que você vai estar familiarizado com este jogo, então eu estava pensando (como eu sinto falta deste jogo e só posso encontrar versões 3D estranhas) se existe uma versão deste jogo no Terminal? Eu estava esperando que iria ficar com o original e iria algo ao longo das linhas de ASCII, talvez?

Estou executando o Ubuntu GNOME 16.04.1 com o GNOME 3.20, existe um aplicativo gratuito nos repositórios oficiais (de onde eu gostaria que ele viesse)?

    
por Great Uncle Bulgaria 12.10.2016 / 11:13

3 respostas

20
  

", existe uma aplicação gratuita nos repositórios oficiais?   (de onde eu preferiria que viesse)? "

Primeiro, há nsnake que deve atender exatamente à sua necessidade

sudo apt-get install nsnake

Mais dois que eu encontrei são snake4 , mas isso abre em uma nova janela, então não é um jogo de terminal e gnibbles , mas eu não consegui executá-lo.

    
por Mark Kirby 12.10.2016 / 11:59
7

O jogo chama-se centipede e a história completa pode ser encontrada aqui: link . Este é um jogo bash que não requer nenhum download e um estudo interessante para os interessados em scripts bash.

Você pode alterar o tamanho da tela para torná-lo menor e mais desafiador alterando essas variáveis:

LASTCOL=40                              # Last col of game area
LASTROW=20                              # Last row of game area

Este é o código:

#!/bin/bash
#
# Centipede game
#
# v2.0
#
# Author: [email protected]
#
# Functions

drawborder() {
   # Draw top
   tput setf 6
   tput cup $FIRSTROW $FIRSTCOL
   x=$FIRSTCOL
   while [ "$x" -le "$LASTCOL" ];
   do
      printf %b "$WALLCHAR"
      x=$(( $x + 1 ));
   done

   # Draw sides
   x=$FIRSTROW
   while [ "$x" -le "$LASTROW" ];
   do
      tput cup $x $FIRSTCOL; printf %b "$WALLCHAR"
      tput cup $x $LASTCOL; printf %b "$WALLCHAR"
      x=$(( $x + 1 ));
   done

   # Draw bottom
   tput cup $LASTROW $FIRSTCOL
   x=$FIRSTCOL
   while [ "$x" -le "$LASTCOL" ];
   do
      printf %b "$WALLCHAR"
      x=$(( $x + 1 ));
   done
   tput setf 9
}

apple() {
   # Pick coordinates within the game area
   APPLEX=$[( $RANDOM % ( $[ $AREAMAXX - $AREAMINX ] + 1 ) ) + $AREAMINX ]
   APPLEY=$[( $RANDOM % ( $[ $AREAMAXY - $AREAMINY ] + 1 ) ) + $AREAMINY ]
}

drawapple() {
   # Check we haven't picked an occupied space
   LASTEL=$(( ${#LASTPOSX[@]} - 1 ))
   x=0
   apple
   while [ "$x" -le "$LASTEL" ];
   do
      if [ "$APPLEX" = "${LASTPOSX[$x]}" ] && [ "$APPLEY" = "${LASTPOSY[$x]}" ];
      then
         # Invalid coords... in use
         x=0
         apple
      else
         x=$(( $x + 1 ))
      fi
   done
   tput setf 4
   tput cup $APPLEY $APPLEX
   printf %b "$APPLECHAR"
   tput setf 9
}

growsnake() {
   # Pad out the arrays with oldest position 3 times to make snake bigger
   LASTPOSX=( ${LASTPOSX[0]} ${LASTPOSX[0]} ${LASTPOSX[0]} ${LASTPOSX[@]} )
   LASTPOSY=( ${LASTPOSY[0]} ${LASTPOSY[0]} ${LASTPOSY[0]} ${LASTPOSY[@]} )
   RET=1
   while [ "$RET" -eq "1" ];
   do
      apple
      RET=$?
   done
   drawapple
}

move() {
   case "$DIRECTION" in
      u) POSY=$(( $POSY - 1 ));;
      d) POSY=$(( $POSY + 1 ));;
      l) POSX=$(( $POSX - 1 ));;
      r) POSX=$(( $POSX + 1 ));;
   esac

   # Collision detection
   ( sleep $DELAY && kill -ALRM $$ ) &
   if [ "$POSX" -le "$FIRSTCOL" ] || [ "$POSX" -ge "$LASTCOL" ] ; then
      tput cup $(( $LASTROW + 1 )) 0
      stty echo
      echo " GAME OVER! You hit a wall!"
      gameover
   elif [ "$POSY" -le "$FIRSTROW" ] || [ "$POSY" -ge "$LASTROW" ] ; then
      tput cup $(( $LASTROW + 1 )) 0
      stty echo
      echo " GAME OVER! You hit a wall!"
      gameover
   fi

   # Get Last Element of Array ref
   LASTEL=$(( ${#LASTPOSX[@]} - 1 ))
   #tput cup $ROWS 0
   #printf "LASTEL: $LASTEL"

   x=1 # set starting element to 1 as pos 0 should be undrawn further down (end of tail)
   while [ "$x" -le "$LASTEL" ];
   do
      if [ "$POSX" = "${LASTPOSX[$x]}" ] && [ "$POSY" = "${LASTPOSY[$x]}" ];
      then
         tput cup $(( $LASTROW + 1 )) 0
         echo " GAME OVER! YOU ATE YOURSELF!"
         gameover
      fi
      x=$(( $x + 1 ))
   done

   # clear the oldest position on screen
   tput cup ${LASTPOSY[0]} ${LASTPOSX[0]}
   printf " "

   # truncate position history by 1 (get rid of oldest)
   LASTPOSX=( 'echo "${LASTPOSX[@]}" | cut -d " " -f 2-' $POSX )
   LASTPOSY=( 'echo "${LASTPOSY[@]}" | cut -d " " -f 2-' $POSY )
   tput cup 1 10
   #echo "LASTPOSX array ${LASTPOSX[@]} LASTPOSY array ${LASTPOSY[@]}"
   tput cup 2 10
   echo "SIZE=${#LASTPOSX[@]}"

   # update position history (add last to highest val)
   LASTPOSX[$LASTEL]=$POSX
   LASTPOSY[$LASTEL]=$POSY

   # plot new position
   tput setf 2
   tput cup $POSY $POSX
   printf %b "$SNAKECHAR"
   tput setf 9

   # Check if we hit an apple
   if [ "$POSX" -eq "$APPLEX" ] && [ "$POSY" -eq "$APPLEY" ]; then
      growsnake
      updatescore 10
   fi
}

updatescore() {
   SCORE=$(( $SCORE +  ))
   tput cup 2 30
   printf "SCORE: $SCORE"
}
randomchar() {
    [ $# -eq 0 ] && return 1
    n=$(( ($RANDOM % $#) + 1 ))
    eval DIRECTION=${$n}
}

gameover() {
   tput cvvis
   stty echo
   sleep $DELAY
   trap exit ALRM
   tput cup $ROWS 0
   exit
}

###########################END OF FUNCS##########################

# Prettier characters but not supported
# by all termtypes/locales
#SNAKECHAR="56"                      # Character to use for snake
#WALLCHAR="44"                       # Character to use for wall
#APPLECHAR="62"                      # Character to use for apples
#
# Normal boring ASCII Chars
SNAKECHAR="@"                           # Character to use for snake
WALLCHAR="X"                            # Character to use for wall
APPLECHAR="o"                           # Character to use for apples
#
SNAKESIZE=3                             # Initial Size of array aka snake
DELAY=0.2                               # Timer delay for move function
FIRSTROW=3                              # First row of game area
FIRSTCOL=1                              # First col of game area
LASTCOL=40                              # Last col of game area
LASTROW=20                              # Last row of game area
AREAMAXX=$(( $LASTCOL - 1 ))            # Furthest right play area X
AREAMINX=$(( $FIRSTCOL + 1 ))           # Furthest left play area X
AREAMAXY=$(( $LASTROW - 1 ))            # Lowest play area Y
AREAMINY=$(( $FIRSTROW + 1))            # Highest play area Y
ROWS='tput lines'                       # Rows in terminal
ORIGINX=$(( $LASTCOL / 2 ))             # Start point X - use bc as it will round
ORIGINY=$(( $LASTROW / 2 ))             # Start point Y - use bc as it will round
POSX=$ORIGINX                           # Set POSX to start pos
POSY=$ORIGINY                           # Set POSY to start pos

# Pad out arrays
ZEROES='echo |awk '{printf("%0"'"$SNAKESIZE"'"d\n",)}' | sed 's/0/0 /g''
LASTPOSX=( $ZEROES )                    # Pad with zeroes to start with
LASTPOSY=( $ZEROES )                    # Pad with zeroes to start with

SCORE=0                                 # Starting score

clear
echo "
Keys:

 W - UP
 S - DOWN
 A - LEFT
 D - RIGHT
 X - QUIT

If characters do not display properly, consider changing
SNAKECHAR, APPLECHAR and WALLCHAR variables in script.
Characters supported depend upon your terminal setup.

Press Return to continue
"

stty -echo
tput civis
read RTN
tput setb 0
tput bold
clear
drawborder
updatescore 0

# Draw the first apple on the screen
# (has collision detection to ensure we don't draw
# over snake)
drawapple
sleep 1
trap move ALRM

# Pick a random direction to start moving in
DIRECTIONS=( u d l r )
randomchar "${DIRECTIONS[@]}"

sleep 1
move
while :
do
   read -s -n 1 key
   case "$key" in
   w)   DIRECTION="u";;
   s)   DIRECTION="d";;
   a)   DIRECTION="l";;
   d)   DIRECTION="r";;
   x)   tput cup $COLS 0
        echo "Quitting..."
        tput cvvis
        stty echo
        tput reset
        printf "Bye Bye!\n"
        trap exit ALRM
        sleep $DELAY
        exit 0
        ;;
   esac
done
    
por WinEunuuchs2Unix 12.10.2016 / 11:21
0

Existe uma coleção de jogos de linha de comando chamada bsdgames .

Você pode instalá-lo digitando sudo apt-get install bsdgames ou sudo apt install bsdgames .

Após a instalação bem sucedida, você pode iniciar o jogo a partir desta lista (apenas digitando o nome no terminal)

adventure (6)        - an exploration game
sol (6)              - a collection of card games which are easy to play with the aid of a mouse.
arithmetic (6)       - quiz on simple arithmetic
atc (6)              - air traffic controller game
backgammon (6)       - the game of backgammon
battlestar (6)       - a tropical adventure game
bcd (6)              - "reformat input as punch cards, paper tape or morse code"
boggle (6)           - word search game
caesar (6)           - decrypt caesar ciphers
canfield (6)         - the solitaire card game canfield
cfscores (6)         - the solitaire card game canfield
chkfont (6)          - checks figlet 2.0 and up font files for format errors
countmail (6)        - be obnoxious about how much mail you have
cowsay (6)           - configurable speaking/thinking cow (and a bit more)
cribbage (6)         - the card game cribbage
dab (6)              - Dots and Boxes game
espdiff (6)          - apply the appropriate transformation to a set of patches
figlet-figlet (6)    - display large characters made up of ordinary screen characters
figlist (6)          - lists figlet fonts and control files
fortune (6)          - print a random, hopefully interesting, adage
gnome-mahjongg (6)   - A matching game played with Mahjongg tiles
gnome-mines (6)      - The popular logic puzzle minesweeper
gnome-sudoku (6)     - puzzle game for the popular Japanese sudoku logic puzzle
go-fish (6)          - play "Go Fish"
gomoku (6)           - game of 5 in a row
hack (6)             - exploring The Dungeons of Doom
hangman (6)          - computer version of the game hangman
hunt (6)             - a multi-player multi-terminal game
huntd (6)            - hunt daemon, back-end for hunt game
intro (6)            - introduction to games
lolcat (6)           - rainbow coloring for text
mille (6)            - play Mille Bornes
monop (6)            - Monopoly game
morse (6)            - "reformat input as punch cards, paper tape or morse code"
number (6)           - convert Arabic numerals to English
phantasia (6)        - an interterminal fantasy game
pig (6)              - eformatray inputway asway Igpay Atinlay
pom (6)              - display the phase of the moon
ppt (6)              - "reformat input as punch cards, paper tape or morse code"
primes (6)           - generate primes
quiz (6)             - random knowledge tests
rain (6)             - animated raindrops display
random (6)           - random lines from a file or random numbers
robots (6)           - fight off villainous robots
rot13 (6)            - decrypt caesar ciphers
sail (6)             - multi-user wooden ships and iron men
snake (6)            - display chase game
snscore (6)          - display chase game
teachgammon (6)      - learn to play backgammon
tetris-bsd (6)       - the game of tetris
trek (6)             - trekkie game
wargames (6)         - shall we play a game?
worm (6)             - Play the growing worm game
worms (6)            - animate worms on a display terminal
wtf (6)              - translates acronyms for you
wump (6)             - hunt the wumpus in an underground cave

Esses jogos geralmente são encerrados pressionando Ctrl + C

    
por Michal Polovka 31.10.2016 / 07:57