Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Programming Code
#1
Hello Every one,
There is program please help if I have done any thing wrong

To implement following memory game :--
Computer makes 20 boxes,numbered 1 to 20. Into each box,it places a single letter randomly taken from set of letters: "aabbccddeeffgghhiijj". The aim of the game is to remove all the boxes.

Each turn the user is told which boxes are still present. Initially, this will be all 20.

The user then selects which box to open by its number,and the computer tells the user what letter is in that box.Once the user has seen what is in the box, the screen is cleared and the user may select another box to open.

If the user select 2 boxes in a row that contain the same letter, those 2 boxes are removed.

The user can open 40 boxes before the game ends. if the user removes all the boxes before their 40 opens are up , they win. Otherwise they loose.




import random


def unbox():
   Boxes = {}

   strlist = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h', 'i', 'i', 'j', 'j']

   # Created a dictionary from randomly generated numbers from strlist
   for x in range(1, 21):
       letter = random.choice(strlist)
       Boxes[x] = letter
       strlist.remove(letter)

   # Printing all the boxes numbers
   print("Following Boxes are available initially")
  # print(Boxes.keys())
   print(Boxes)

   # Total 40 Chances will be given to user to open the boxes
   for i in range(0, 40, 2):
       try:
           # Take input from user to open first box
           choice1 = int(input("Enter a number to select the Box"))
           print("The letter in Box " + str(choice1) + "is " + str(Boxes[choice1]))
           if choice1 not in Boxes.keys():
               print("This box in not available")
               continue
           #ClearScreen()

           # Take input from user to open second box
           choice2 = int(input("Enter a number to select the Box"))

           if choice2 not in Boxes.keys():
               print("This box in not available")
               continue
           if  choice1 == choice2 :
               print("Both the boxes are having same number")
           # if the values of both the Boxes match then remove both the boxes
           if Boxes[choice1] == Boxes[choice2]:
               del Boxes[choice1]
               del Boxes[choice2]

           # Print the number of all available boxes
           if len(Boxes) > 0:
               print("Following Boxes are available")
               print(Boxes.keys())

               # if there are no more boxes to open that means user won
           else:
               print("You Win The Game !!")
               return ()

       except Exception as e:
           print("Exception Occured ", e)

   print("You Lost The Game !!")


unbox()
Reply
#2
Is there any error or you just ask for advise how this can be done better/in more pythonic way?
Reply
#3
I appeared for coding challenge but was unsuccessful...that's why need suggestions on this
Reply
#4
(Jun-27-2017, 08:21 AM)Poonam Wrote: Hello Every one,
There is program please help if I have done any thing wrong

To implement following memory game :--
Computer makes 20 boxes,numbered 1 to 20. Into each box,it places a single letter randomly taken from set of letters: "aabbccddeeffgghhiijj". The aim of the game is to remove all the boxes.

Each turn the user is told which boxes are still present. Initially, this will be all 20.

The user then selects which box to open by its number,and the computer tells the user what letter is in that box.Once the user has seen what is in the box, the screen is cleared and the user may select another box to open.

If the user select 2 boxes in a row that contain the same letter, those 2 boxes are removed.

The user can open 40 boxes before the game ends. if the user removes all the boxes before their 40 opens are up , they win. Otherwise they loose.




import random


def unbox():
   Boxes = {}

   strlist = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h', 'i', 'i', 'j', 'j']

   # Created a dictionary from randomly generated numbers from strlist
   for x in range(1, 21):
       letter = random.choice(strlist)
       Boxes[x] = letter
       strlist.remove(letter)

   # Printing all the boxes numbers
   print("Following Boxes are available initially")
  # print(Boxes.keys())
   print(Boxes)

   # Total 40 Chances will be given to user to open the boxes
   for i in range(0, 40, 2):
       try:
           # Take input from user to open first box
           choice1 = int(input("Enter a number to select the Box"))
           print("The letter in Box " + str(choice1) + "is " + str(Boxes[choice1]))
           if choice1 not in Boxes.keys():
               print("This box in not available")
               continue
           #ClearScreen()

           # Take input from user to open second box
           choice2 = int(input("Enter a number to select the Box"))

           if choice2 not in Boxes.keys():
               print("This box in not available")
               continue
           if  choice1 == choice2 :
               print("Both the boxes are having same number")
           # if the values of both the Boxes match then remove both the boxes
           if Boxes[choice1] == Boxes[choice2]:
               del Boxes[choice1]
               del Boxes[choice2]

           # Print the number of all available boxes
           if len(Boxes) > 0:
               print("Following Boxes are available")
               print(Boxes.keys())

               # if there are no more boxes to open that means user won
           else:
               print("You Win The Game !!")
               return ()

       except Exception as e:
           print("Exception Occured ", e)

   print("You Lost The Game !!")


unbox()

Hello ,

Please helpto know how to write it in better way

Thanks
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code error from Fundamentals of Python Programming van Richard L. Halterman Heidi 12 1,601 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