RosettaCodeData/Task/Bulls-and-cows/Smart-BASIC/bulls-and-cows.basic
2023-07-01 13:44:08 -04:00

87 lines
2.2 KiB
Text

'by rbytes, January 2017
OPTION BASE 1
P(" B U L L S A N D C O W S")!l
P("A secret 4-digit number has been created, with")
P("no repeats and no zeros. You must guess the number.")
P("After each guess, you will be shown how many of your")
P("digits are correct and in the matching location (bulls),")
P("and how many are correct but in a different location (cows).")
p("See how many tries it takes you to get the right answer.")
' generate a 4-digit number with no repeats
guesses = 0
1 WHILE LEN(sec$) <4
c$ =CHR$( INTEG(RND(1) *9) +49)
IF INSTR(sec$, c$)=-1 THEN sec$&=c$
ENDWHILE!l
2 PRINT "Your guess: "
INPUT "FOUR DIGITS": guess$!l
IF guess$="" THEN ' check if entry is null
P("Please enter something!")!l
GOTO 2
ENDIF
P(guess$)!l
IF LEN(guess$)<>4 THEN ' check if entry is exactly 4 characters
P("Please enter exactly 4 digits.")!l
GOTO 2
ENDIF
FOR t=1 TO 4 ' check if all characters are digits 1 - 9
IF INSTR("123456789",MID$(guess$,t,1))=-1 THEN
P("You have entered at least one illegal character")!l
GOTO 2
ENDIF
NEXT t
rep = check(guess$) ' check if any digits are repeated
IF check.chk THEN
P("Please enter a number with no repeated digits.")!l
GOTO 2
ENDIF
guesses+=1
r$=score$(guess$,sec$)
P(r$)!l
IF guess$=sec$ THEN
P("W I N N E R ! ! !")!l
IF guesses>1 THEN gs$="guesses!" ELSE gs$="guess!"
P("You won after "&guesses&" "&gs$)
P("Thanks for playing!")!l
PAUSE 2
P("A G A I N with a new secret number")!l
guesses=0
END IF
GOTO 1
END ' _____________________________________________________________
DEF P(p$) ' function to print a string
PRINT p$
END DEF
DEF L() ' function to print an empty line
PRINT
END DEF
DEF check(i$) ' check=0 if digit is not repeated, else=1
chk=0
FOR i =1 TO 3
FOR j =i +1 TO 4
IF MID$( i$, i, 1)=MID$( i$, j, 1) THEN chk =1
NEXT j
NEXT i
END DEF
DEF score$(a$,b$) ' calculate the numbers of bulls & cows.
bulls=0!cows=0
FOR i = 1 TO 4
c$ = MID$( a$, i, 1)
IF MID$( b$, i, 1)=c$ THEN
bulls+=1
ELSE
IF INSTR( b$, c$) <>-1 AND INSTR( b$, c$) <>i THEN
cows+=1
END IF
END IF
NEXT i
r$ ="Bulls: "&STR$( bulls)& ", "& "Cows: " &STR$( cows)
RETURN r$
END DEF
END