1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- # Copyright (C) 2020, 2019 Girish M
- # This program is free software; you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation; either version 3 of the License, or
- # (at your option) any later version.
- #
- # This program is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # GNU General Public License for more details.
- #
- # You should have received a copy of the GNU General Public License
- # along with this program; if not, write to the Free Software
- # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
- # MA 02110-1301, USA.
- #
- '''
- Create a program that will play the “cows and bulls” game with the user. The game works like this:
- Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
- For every digit that the user guessed correctly in the correct place, they have a “cow”.
- For every digit the user guessed correctly in the wrong place is a “bull.”
- Every time the user makes a guess, tell them how many “cows” and “bulls” they have.
- Once the user guesses the correct number, the game is over.
- Keep track of the number of guesses the user makes throughout teh game and tell the user at the end.
- Say the number generated by the computer is 1038. An example interaction could look like this:
- Welcome to the Cows and Bulls Game!
- Enter a number:
- >>> 1234
- 2 cows, 0 bulls
- >>> 1256
- 1 cow, 1 bull
- ...
- '''
- # @author prince
- import random
- rn = random.choice(range(1000, 10000))
- rnlist = list(str(rn))
- choice = 'no'
- cows = 0
- bulls = 0
- score = 0
- while choice == 'no':
- n = input('[write 0000 to give up.] enter a 4-digit number: ')
- score += 1
- a = n[0::5]
- b = n[1::4]
- c = n[2::4]
- d = n[3::4]
- ra = int(rnlist[0])
- rb = int(rnlist[1])
- rc = int(rnlist[2])
- rd = int(rnlist[3])
- if int(n) == rn:
- print('You Won! You guessed the number in', score, 'guesses!')
- choice = 'yes'
- else:
- if int(a) == ra:
- cows += 1
- else:
- if a in rnlist:
- bulls += 1
- if int(b) == rb:
- cows += 1
- else:
- if b in rnlist:
- bulls += 1
- if int(c) == rc:
- cows += 1
- else:
- if c in rnlist:
- bulls += 1
- if int(d) == rd:
- cows += 1
- else:
- if d in rnlist:
- bulls += 1
- print('cows: ', cows)
- cows = 0
- if cows != 4:
- print('bulls: ', bulls)
- bulls = 0
- if n == '0000':
- print(rn, 'was the number!')
- break
|