Bulls and Cows


Task

Create a four digit random number from the digits   1   to   9,   without duplication.

The program should:

   ask for guesses to this number
   reject guesses that are malformed
   print the score for the guess


The score is computed as:

 The player wins if the guess is the same as the randomly chosen number, and the program ends.
 A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
 A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.


Related tasks

   Bulls and cows/Player
   Guess the number
   Guess the number/With Feedback
   Mastermind


 
numCount = 4 -- number of digits to use
 
digits = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
num = ""
while num.count < numCount and digits.count > 0 do
(
	local r = random 1 digits.count
	append num (digits[r] as string)
	deleteitem digits r
)
digits = undefined
numGuesses = 0
inf = "Rules: \n1. Choose only % unique digits in any combination"+\
		" (0 can't be used).\n2. Only positive integers are allowed."+\
		"\n3. For each digit that is in it's place, you get a bull,\n"+\
		"\tand for each digit that is not in it's place, you get a cow."+\
		"\n4. The game is won when your number matches the number I chose."+\
		"\n\nPress [esc] to quit the game.\n\n"
clearlistener()
format inf num.count
while not keyboard.escpressed do
(
	local userVal = getkbvalue prompt:"\nEnter your number: "
	if (userVal as string) == num do
	(
		format "\nCorrect! The number is %. It took you % moves.\n" num numGuesses
		exit with OK
	)
	local bulls = 0
	local cows = 0
	local badInput = false
	case of
	(
		(classof userVal != integer): 
			(
			format "\nThe number must be a positive integer.\n"
			badInput = true
			)
		((userVal as string).count != num.count): 
			(
			format "\nThe number must have % digits.\n" num.count
			badInput = true
			)
		((makeuniquearray (for i in 1 to (userVal as string).count \
			collect (userVal as string)[i])).count != (userVal as string).count):
			(
				format "\nThe number can only have unique digits.\n"
				badInput = true
			)
	)
	if not badInput do
	(
		userVal = userVal as string
		i = 1
		while i <= userVal.count do
		(
			for j = 1 to num.count do
			(
				if userVal[i] == num[j] do
				(
					if i == j then bulls += 1 else cows += 1
				)
			)
			i += 1
		)
		numGuesses += 1
		format "\nBulls: % Cows: %\n" bulls cows
	)
)