Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Programming Code
#5
i would do it like this:

# use/bin/python3

from random import shuffle
from collections import OrderedDict
import os
import time

LETTERS = 'abcdefj'
USER_TRIES = 40
SLEEP = 3


def show_available_boxes(boxes):
    available = list(map(str, boxes.keys()))
    print('Following boxes are available:\n\n{}\n\n'.format('  '.join(available)))
    return available


def get_user_input(boxes, counter, last):
    while True:
        available_boxes = show_available_boxes(boxes=boxes)
        try:
            number = input('You have {} tries left. Please, select a box number: '.format(USER_TRIES-counter))
            if number not in available_boxes:
                raise ValueError ('Box number is {} not available'.format(number))
            elif number == last:
                raise ValueError ('Select a number from the avilable boxes, which is not the same as your last choice {}'.format(number))
            return int(number)
        except ValueError as ve:
            print('\n{}'.format(ve))
            time.sleep(SLEEP)
            os.system('cls||clear')


def play_game(max_tries = USER_TRIES):
    while True:
        boxes = list(LETTERS)*2
        shuffle(boxes)
        boxes = OrderedDict(enumerate(boxes, start=1))
        counter = 0
        last_choice = -1
        while boxes and counter <= max_tries:
            number = get_user_input(boxes=boxes, counter=counter, last=last_choice)
            counter += 1
            letter = boxes[number]
            print('\nBox {} has letter {}'.format(number, letter))
            if last_choice != -1 and letter == boxes[last_choice]:
                print('You found a pair. Both box {} and {} have letter {}!'.format(last_choice, number, letter))
                boxes.pop(number)
                boxes.pop(last_choice)
                last_choice = -1
            else:
                last_choice = number
            time.sleep(SLEEP)
            os.system('cls||clear')
        if not boxes:
            print('Congratulations! YOU WIN!')
        else:
            print('Sorry! You have lost!')
        new_game = input('\n\n\nDo you want to play again? ')
        if new_game.lower() not in ('y', 'yes'):
            break


if __name__ == '__main__':
    play_game()
Reply


Messages In This Thread
Programming Code - by Poonam - Jun-27-2017, 08:21 AM
RE: Programming Code - by buran - Jun-27-2017, 09:36 AM
RE: Programming Code - by Poonam - Jun-27-2017, 08:15 PM
RE: Programming Code - by Poonam - Jun-30-2017, 05:49 AM
RE: Programming Code - by buran - Jun-30-2017, 08:36 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Code error from Fundamentals of Python Programming van Richard L. Halterman Heidi 12 1,716 Jul-25-2023, 10:32 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020