Assignment

Concentration Game

For this assignment you will implement a modified version of Concentration Game.

Note that in this assignment words like “deck” and “board” are used interchangeably.

You may assume that the player will follow your instructions and enter the correct date type but not necessarily the correctdata values for that type. For example, if you ask the player for an even integer between 2 and 52 you may assume that indeedthey will enter an integer but your program should test if the player entered an integer in therequired range and if it is indeed even number. Your program should prompt the player to repeat the entry until correct inputis obtained. You should also fully test your program – like, what does the program do if the player does something silly, e.g. enters a location that is already discovered, or enters two same locations.

Your program should have a function that displays the currentboard, but it should also have a function that displays the board with two new positions revealed. These functions should be called from your game playing function(called play_game). Design your program by decomposing it into smaller sub problems.

The game is usually played with cards lied down on a table. Your game will not use graphics libraries to display the board,but instead it will print the board with the tools. A typical
card has a suit and a rank on one side. Let’s call that side of a card, a face side, and the other case a dull side. Instead ofsuit and a rank each of our cards will have a single character on its face side and that character will be an upper case letter ofEnglish alphabet or any special character. A typical card deck hasthe same drawing on the dull side of the cards. Instead of a drawing our cards will have a character star, *, on their dull side.
For the deck to be suitable for playingConcentration game, each character that appears in the deck needs to appear on an even number of cards. Furthermore, thedeck cannot have cards with * on their face sides, as we could not distinguish a face side from a dull side of such cards.Therefore before playing we need to clean up the deck. In particular, we need to remove all the cards that have a * on theirfaces. In addition, for each character that appears on an odd number of cards, we need to remove exactly one card with thatcharacter from the deck. After such a clean-up, the resulting deck can be used for playing Concentration game. We call such a
deck, the one where each character appears on even number of cards and where no card has * on its face side, a playable deck.Finally we call a deck rigorous if it is playable and each character of the deck appears exactly two times.
Your game must use a (one dimensional) list as the board, as implied by the provided code in a3_xxxxxx.py
The game starts off by asking the player
(1) if they wanted a (rigorous) deck, and thus board, automatically generated
(2) or if they want to start with the deck given in a file.
If option (1) is chosen, you need to first prompt the player for the size of the deck. You should only accept even integers,between 2 and 52 for Option 1.
If option (2) is chosen, the deck will be read from a file. The player will enter a name of that file when prompted.

Finally you will notice that a3_xxxxxx.py has a function called play_game(board). That is where you should put yourgame paying code. The function play_game takes a playable deck as input parameter.

2). Once the player completes the game, you should also print the number of guesses it took to solve it and how far it is fromthe optimal len(board)/2 guesses.

a3_xxxxxx.py 

import random

defshuffle_deck(deck):

”'(list of str)->None

Shuffles the given list of strings representing the playing deck

”’

# YOUR CODE GOES HERE

deck=[‘A’,’B’,’C’,’D’,’E’,’F’,’G’,’H’,’I’,’J’,’K’,’L’,’M’,’N’,’O’,’P’,’Q’,’R’,’S’,’T’,’U’,’V’,’W’,’X’,’Y’,’Z’]

random.shuffle(deck)

print(‘Shuffling the deck…’)

return deck

defcreate_board(size):

”’int->list of str

Precondition: size is even positive integer between 2 and 52

Returns a rigorous deck (i.e. board) of a given size.

”’

board = [None]*size

letter=’A’

for i in range(len(board)//2):

board[i]=letter

board[i+len(board)//2 ]=board[i]

letter=chr(ord(letter)+1)

return board

defprint_board(a):

”'(list of str)->None

Prints the current board in a nicely formated way

”’

for i in range(len(a)):

print(‘{0:4}’.format(a[i]), end=’ ‘)

print()

for i in range(len(a)):

print(‘{0:4}’.format(str(i+1)), end=’ ‘)

defwait_for_player():

”'()->None

Pauses the program/game until the player presses enter

”’

input(“\nPress enter to continue. “)

print()

defprint_revealed(discovered, p1, p2, original_board):

”'(list of str, int, int, list of str)->None

Prints the current board with the two new positions (p1 & p2) revealed from the original board

Preconditions: p1 & p2 must be integers ranging from 1 to the length of the board

”’

# YOUR CODE GOES HERE

#############################################################################

#   FUNCTIONS FOR OPTION 1 (with the board being read from a given file)    #

#############################################################################

defread_raw_board(file):

”’str->list of str

Returns a list of strings represeniting a deck of cards that was stored in a file.

The deck may not necessarifly be playable

”’

raw_board = open(file).read().splitlines()

for i in range(len(raw_board)):

raw_board[i]=raw_board[i].strip()

returnraw_board

defclean_up_board(l):

”’list of str->list of str

The functions takes as input a list of strings representing a deck of cards.

It returns a new list containing the same cards as l except that

one of each cards that appears odd number of times in l is removed

and all the cards with a * on their face sides are removed

”’

print(“\nRemoving one of each cards that appears odd number of times and removing all stars …\n”)

for i in l :

if i ==”*”:

l.remove(i)

playable_board=[]

# YOUR CODE GOES HERE

##    print(“*************************************************************************”)

##    print(“*                                                                       *”)

##    print(“*  __This deck is now playable but not rigorous and it has 20 cards.__  *”)

##    print(“*                                                                       *”)

##    print(“*************************************************************************”)

playable_board=list(set(l))

for i in playable_board:

x=l.count(i)

if x % 2==1:

l.remove(i)

return l

defis_rigorous(l):

”’list of str->True or None

Returns True if every element in the list appears exactlly 2 times or the list is empty.

Otherwise, it returns False.

Precondition: Every element in the list appears even number of times

”’

# YOUR CODE GOES HERE

s = []

s=set(l)

iflen(l) ==0:

return True

else:

for i in s:

x=l.count(i)

if (x!=2):

return False

else:

return True

####################################################################3

defplay_game(board):

”'(list of str)->None

Plays a concentration game using the given board

Precondition: board a list representing a playable deck

”’

print(“Ready to play …\n”)

# this is the funciton that plays the game

# YOUR CODE GOES HERE

print_revealed(discovered, p1, p2, original_board)

p1=input(“Enter two distinct positions on the board that you want to revealed.\ni.e two integers in the range[1, “+len(board)+”]\nEnterposition 1:”

p2=input(“Enter position 2:”)

wait_for_player()

#main

print(“******************************************”)

print(“*                                        *”)

print(“*  __Welcome to my Concentration game__  *”)

print(“*                                        *”)

print(“******************************************”)

# YOUR CODE TO GET A CHOICE 1 or CHOCE 2 from a player GOES HERE

status=input(“Would you like (enter 1 r 2 to indicate your choice):\n(1) me to generate a rigorous deck of cards for you\nor, would you like me to read a deck from a file?” +”\n”)

print(status+” is not an existing option. Please try again. Enter 1 or 2 to indicate your choice”)

# YOUR CODE FOR OPTION 1 GOES HERE

while True:

if status ==’1′:

print(“You chose to have a rigorous deck generated for you”+”\n”)

cards_want_to_play=input(“how many cards do you want to play with?\nEnter an even numer between 0 and 52: “)

# In option 1 somewhere you need to and MUST have a call like this:

# board=create_board(size)

while True:

ifcards_want_tp_play>=6 and cards_want_tp_play<=26:

board=creat_board(size)

# YOUR CODE FOR OPTION 2 GOES HERE

elif status==’2′:

# In option 2 somewhere you need to and MUST have the following 4 lines of code one after another

#

#print(“You chose to load a deck of cards from a file”)

#file=input(“Enter the name of the file: “)

#file=file.strip()

#board=read_raw_board(file)

#board=clean_up_board(board)

else:

print(status+” is not an existing option. Please try again. Enter 1 or 2 to indicate your choice”)

 Solution 

 main (1).py

import random

defcreate_board(size):

board = [None]*size

letter = “A”

for i in range(len(board)//2):

board[i]=letter

board[i + len(board)//2] = board[i]

letter=chr(ord(letter)+1)

return board

defshuffle_deck(deck):

”'(list of str)->None

Shuffles the given list of strings representing the playing deck

”’

print(“Shuffling the deck”)

random.shuffle(deck)

return deck

# defprint_board(deck):

#     print(deck)

defprint_board(a):

”'(list of str)->None

Prints the current board in a nicely formated way

”’

for i in range(len(a)):

print(‘{0:4}’.format(a[i]), end=’ ‘)

print()

for i in range(len(a)):

print(‘{0:4}’.format(str(i+1)), end=’ ‘)

defprint_revealed(discovered, p1, p2, original_board):

”'(list of str, int, int, list of str)->None

Prints the current board with the two new positions (p1 & p2) revealed from the original board

Preconditions: p1 & p2 must be integers ranging from 1 to the length of the board

”’

# YOUR CODE GOES HERE

board_size = len(original_board)

if p1>=1 and p1<=board_size and p2>=1 and p2<=board_size:

p1 = p1-1

p2 = p2-1

#Check for distinct entries

if p1 == p2:

print(‘You chose the same positions.’)

return(None)

#Check if one of the positions has already been paired

if discovered[p1] != “*” or discovered[p2] != “*”:

print(‘One or both of your chosen positions has already been paired.’)

return(None)

p1Character = original_board[p1]

p2Character = original_board[p2]

if p1Character == p2Character:

discovered[p1] = original_board[p1]

discovered[p2] = original_board[p2]

print_board(discovered)

return(discovered)

else:

discovered[p1] = original_board[p1]

discovered[p2] = original_board[p2]

print_board(discovered)

discovered[p1] = “*”

discovered[p2] = “*”

return(discovered)

defwait_for_player():

”'()->None

Pauses the program/game until the player presses enter

”’

raw_input(“\nPress enter to continue. “)

for i in range(25):

print(“\n”)

defread_raw_board(file):

”’str->list of str

Returns a list of strings represeniting a deck of cards that was stored in a file.

The deck may not necessarifly be playable

”’

raw_board = open(file).read().splitlines()

for i in range(len(raw_board)):

raw_board[i]=raw_board[i].strip()

returnraw_board

defclean_up_board(l):

”’list of str->list of str

The functions takes as input a list of strings representing a deck of cards.

It returns a new list containing the same cards as l except that

one of each cards that appears odd number of times in l is removed

and all the cards with a * on their face sides are removed

”’

print(“\nRemoving one of each cards that appears odd number of times and removing all stars …\n”)

for i in l :

if i ==”*”:

l.remove(i)

playable_board=[]

playable_board=list(set(l))

for i in playable_board:

x=l.count(i)

if x % 2==1:

l.remove(i)

return l

defis_rigorous(l):

”’list of str->True or None

Returns True if every element in the list appears exactlly 2 times or the list is empty.

Otherwise, it returns False.

Precondition: Every element in the list appears even number of times

”’

s = []

s=set(l)

iflen(l) ==0:

return True

else:

for i in s:

x=l.count(i)

if (x!=2):

return False

else:

return True

defplay_game(board):

print(“Ready to play …\n”)

discovered = [‘*’]*len(board)

guesses = 0

while True:

print_board(discovered)

p1=input(“Enter two distinct positions on the board that you want to revealed.\ni.e two integers in the range[1, “+str(len(board))+”]\nEnter position 1:”)

p2 = input(“Enter position 2:”)

output = print_revealed(discovered,p1,p2,board)

if output!=None:

discovered = output

guesses += 1

else:

print(“Please try again. This guess did not count. You current number of guesses is %d.”%(guesses))

ifdiscovered.count(“*”)==0:

print(“Congratulations! You completed the game with %d guesses. That is %d more than the best possible”%(guesses, guesses – len(board)//2 ))

break

wait_for_player()

#######################################################################################

# MAIN

print(“******************************************”)

print(“*                                        *”)

print(“*  __Welcome to my Concentration game__  *”)

print(“*                                        *”)

print(“******************************************”)

print(“Would you like (enter 1 or 2 to indicate your choice):\n(1) me to generate a rigorous deck of cards for you\n(2) or, would you like me to read a deck from a file?” +”\n”)

gameChoice = input()

whilegameChoice not in (1,2):

print(‘%d is not an existing option. Please try again. Enter 1 or 2 to indicate your choice ‘%gameChoice)

gameChoice = input()

ifgameChoice ==1:

print(“You chose to have a rigorous deck generated for you”+”\n”)

cards_to_play = input(“how many cards do you want to play with?\nEnter an even numer between 2 and 52: “)

while(cards_to_play%2==1 or cards_to_play<2 or cards_to_play>52):

cards_to_play = input(“how many cards do you want to play with?\nEnter an even numer between 2 and 52: “)

deck  =create_board(cards_to_play)

deck = shuffle_deck(deck)

wait_for_player()

play_game(deck)

elifgameChoice ==2:

print(“You chose to load a deck of cards from a file”)

filename = raw_input(“Enter the name of the file : “)

board = read_raw_board(filename)

board = clean_up_board(board)

rigor = is_rigorous(board)

if rigor == True:

print(“*  __This deck is now playable and rigorous and it has %d cards.__  *”%len(board))

else:

print(“*  __This deck is now playable and but not rigorous and it has %d cards.__  *”%len(board))

wait_for_player()

play_game(board)