Learn faster and stay on-track by joining this free class with other self-learners.
Register for MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming now.
|
MIT OpenCourseWare 6.00 Introduction to Computer Science and ProgrammingClass length: 24 weeks. Start anytime. Creator: duallain Status: Established |
Join this class! |
|
Lesson 9: Assignment 2There is one problem set, but I have split it into two assignments so you can paste your code for the two games separately. Please post your solutions thusly:
POST YOUR SOLUTIONS TO GHOST HERE.The solutions to the 6.00 Wordgame should be posted to lesson 9 HW 1
Homework Submissions20 totalInteresting problem-set! # Problem Set 5: Ghost
# Name: Chapman
# Collaborators:
# Time: 5:00
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
def is_valid_word(wordFragment,wordlist):
"""Returns True if the word fragment matches the start of any word
in the 'wordlist' list"""
for word in wordlist:
valid = string.find(word,wordFragment)
if valid == 0:
return True
return False
def word_formed(word,wordlist):
"""if the length of the word is greater than 3 AND that word is in the
'worlist' list, returns True."""
if len(word) > 3 and word in wordlist:
return True
return False
def print_result(player,reason,word):
""" parameters include: player number (1 or 2), the reason for losing the
game('Invalid' for entry of letter which cannot form a word or 'word' for
completion of a word in 'wordlist' longer than 3 letters) and the current
word fragment 'word'. This function strings the above infomation together
and prints the appropriate reply. """
if reason == 'word':
print 'player',player, 'loses because', '"',word,'"', 'is a word.'
elif reason == 'Invalid':
print 'player', player, 'loses because no word begins with:', '"', word,'".'
if player == 1:
print 'player 2 wins!!'
else:
print 'player 1 wins!!'
def single_letter(letter):
"""verifies that the charactor/s 'letter' is a single aplhabetic charactor"""
if len(letter)== 1 and letter in string.ascii_letters:
return True
else:
return False
def user_prompt(playerName,word_string):
userPrompt = "Player " + str(playerName) + "'s chooses letter:"
player = string.lower(raw_input(userPrompt)) #prompts the current player to input a letter
while not single_letter(player): #keeping prompting player until he/she enters a single alphabetic charactor
print 'Invalid charactor/s. Please enter a single alphabetic letter'
player = string.lower(raw_input(userPrompt))
result = word_string = word_string + player #adds the charactor to the word fragment and returns it
return result
def is_player_end(playerName,word_string):
if is_valid_word(word_string,wordlist): #checks if a real word starts with the word fragment
if word_formed(word_string,wordlist): #checks whether a real word longer than 3 letters is formed
print_result(playerName,'word',word_string) # if real word is formed, the player loses and result is printed
return True
else:
print_result(playerName,'Invalid',word_string) #if no word starts with word fragment, player loses and result is printed
return True
return False
def ghost():
endGame = False
current_string = ''
currentPlayer = 1
print current_string
print 'Player 1 goes first!'
current_string = user_prompt(currentPlayer,current_string) #the first charactor entered is not checked because each alphabetic letter has words begining with it
while endGame == False:
if currentPlayer == 1: #the player number is changed to give the other player his/her turn
currentPlayer = 2
else:
currentPlayer = 1
print "Player " + str(currentPlayer) + "'s" + " turn." #alerts the player that it's his/her turn
current_string = user_prompt(currentPlayer,current_string) #the charactor entered by player is checked and concatenated into 'current_string' variable
endGame = is_player_end(currentPlayer, current_string) #checks whether a player has lost the game
if __name__ == '__main__':
ghost()
This was a good one, and not hard to do at all once you do the first 5 problems because its just a search function + the gameplay # Problem Set 5: Ghost
# Name: Nick
# Collaborators: None
# Time: 0:50
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "/Users/Nick/Desktop/Introduction to CS and Programming/Assignments/5/Supporting Files/words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
word_list = load_words()
def search(word, word_list, first, last):
if (last-first) < 2: return word_list[first] == word or word_list[last] == word
mid = first + (last-first)/2
if word_list[mid] == word: return True
if word_list[mid] > word: return search(word, word_list, first, mid - 1)
return search(word, word_list, mid + 1, last)
def ghost():
print 'Welcome to Ghost!'
print 'Player 1 goes first.'
turn = '1'
word = ''
while not search(string.lower(word), word_list, 0, len(word_list)-1) or len(word) <= 3:
if word != '':
if turn == '1': turn = '2'
else: turn = '1'
print "Player "+turn+"'s turn."
letter = string.upper(str(raw_input('Player ' + turn + ' says letter: ')))
while not letter in string.ascii_letters or letter == '':
print 'Error: Not a letter'
letter = string.upper(str(raw_input('Player ' + turn + ' says letter: ')))
word += letter
print
print "Current word fragment: '"+word+"'"
print "Player " + turn + " loses because '"+ word +"' is a word!"
if turn == '1': turn = '2'
else: turn = '1'
print 'Player ' + turn + ' wins!'
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name:
# Collaborators: None
# Time:
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
# TO DO: your code begins here!
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name: Andrew
# Collaborators: CuriousReef
# Time:
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
# TO DO: your code begins here!
def isWordFrag(current, wordList): #returns True if input1 is on the road to making a word.
for i in wordList:
if i[0:len(current)] == current:
return True
return False
word_list = load_words()
currentTurn = 1
while True:
currentFrag = ''
gameOver = False
while gameOver == False:
while currentTurn == 1 and gameOver == False:
currentFrag += raw_input("Player 1 says letter: ").lower()
if currentFrag in word_list:
if len(currentFrag) > 3:
print "Player 1 loses because",currentFrag,"is a word!"
currentTurn = 2
gameOver = True
break
if not isWordFrag(currentFrag,word_list):
print "Player 1 loses because no word begins with",currentFrag
gameOver = True
currentTurn = 2
break
currentTurn = 2
while currentTurn == 2 and gameOver == False:
currentFrag += raw_input("Player 2 says letter: ").lower()
if currentFrag in word_list:
print "Player 2 loses because",currentFrag,"is a word!"
currentTurn = 1
gameOver = True
break
if not isWordFrag(currentFrag,word_list):
print "Player 2 loses because no word begins with",currentFrag
currentTurn = 1
gameOver = True
break
currentTurn = 1
print "Player",currentTurn,"wins!"
print("continue? (y/n)")
playAgain = raw_input()
if playAgain == 'n':
break
No comments. Sign up or log in to comment It works... But I don't feel pretty happy about it. I'm still looking for a way around al the globals I have to take in my function, for one... letter=0
player = "player 1"
word = ''
def is_part_in_list(word):
"""
Tests if the word fragment (word) is a part of a word so letters can be added
"""
fragment_length=len(word)
for part in range(len(wordlist)):
if wordlist[part][:fragment_length]==word: return True
return False
def playerchange():
if player == "player 1" : return "player 2"
else: return "player 1"
def takeinput():
ready = False
while not ready:
letter = raw_input("what letter do you wish to add? ")
if letter in string.ascii_letters:
ready = True
letter.lower()
else: print 'that is not a valid input'
return letter
def play():
global player
global letter
global word
gameover=False
print "welcome tho Ghosts"
print "+"*50,"\n"
while not gameover:
print
print player,"'s turn."
letter = takeinput()
word+=letter
if word in wordlist and len(word)>3:
print player, "loses the game because a word was formed:"
print word, "was the word you constructed"
gameover=True
if not is_part_in_list(word):
print
print player, "loses because it is impossible to construct a word with the sequence:"
print word
gameover=True
if not gameover: print "the current word is: ", word
player=playerchange()
print
print "+"*50
print "the game is over"
print "+"*50
play()
Comments:those three globals don't need to be globals, just put them at the beginning of your function This was one of my favourite problem sets so far.
# Problem Set 5: Ghost
# Name: tuckertuck
# Collaborators:
# Time: 2 hours
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
def is_valid_fragment(word, wordlist, low, high):
"""
Returns True if the word fragment is a fragment of a word in wordlist.
Performs a binary search to locate the fragment within the list of words.
"""
word = word.lower()
guess = (low+high)/2
if wordlist[guess].find(word) == 0:
#print wordlist[guess], low, high
return True
if low + 1 == high:
#print wordlist[guess], low, high
return False
if word < wordlist[guess]:
#print wordlist[guess], low, high
return is_valid_fragment(word, wordlist, low, guess)
else:
#print wordlist[guess], low, high
return is_valid_fragment(word, wordlist, guess, high)
def is_word(word, wordlist):
"""
Returns True if the word fragment is a completed word in wordlist
4 letters or more in length.
"""
word = word.lower()
if len(word) > 3 and word in wordlist:
return True
return False
def alt_player(currentPlayer):
if currentPlayer == 1:
return 2
else: return 1
def ghost(wordlist):
"""
Allows two players to play a game of Ghost
* Displays current word fragment
* Asks to input letter
* If letter is valid adds it to the word fragment
* If word fragment is valid players take turns
* Player loses if they complete a word over 3 letters or creates and invalid word fragment
wordlist: list of lowercase strings
"""
## Initialize Game
currentPlayer = 1
word = ''
lossCondition = 0
print
print 'Welcome to Ghost!'
print 'Player', currentPlayer ,'goes first.'
## Game Loop
while True:
print "Current word fragment: '" + word.upper() + "'"
letter = raw_input('Player ' + str(currentPlayer) + ' says letter: ')
if letter == '':
print 'Invalid letter, please choose again.'
continue
if letter in string.ascii_letters:
word += letter
else:
print 'Invalid letter, please choose again.'
continue
# Checks if word fragment is valid
if not is_valid_fragment(word, wordlist, 0, len(wordlist)):
lossCondition = 1
break
# Checks if word fragment is complete word 4 letters or more
if is_word(word, wordlist):
lossCondition = 0
break
# Alternates Players
currentPlayer = alt_player(currentPlayer)
print
print 'Player '+ str(currentPlayer)+"'s turn"
## Win/Loss Conditions
if lossCondition == 1:
print
print "Current word fragment: '" + word.upper() + "'"
print "Player " + str(currentPlayer) + " loses because no word begins with '"+ word.upper()+"'!"
print "Player " + str(alt_player(currentPlayer)) + " wins!"
elif lossCondition == 0:
print
print "Current word fragment: '" + word.upper() + "'"
print "Player " + str(currentPlayer) + " loses because '"+ word.upper()+"' is a word!"
print "Player " + str(alt_player(currentPlayer)) + " wins!"
## Replay Game Loop
while True:
print
replay = raw_input('Do you want to play again? Y/N: ').upper()
if replay == 'Y':
return ghost(wordlist)
elif replay == 'N':
print 'Thanks for playing, Goodbye!'
break
else:
print 'Invalid choice, please choose again'
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
wordlist = load_words()
ghost(wordlist)
No comments. Sign up or log in to comment pset 5 part 2 # Problem Set 5: Ghost
# Name: Marc
# Collaborators:
# Time: ~1 Hour
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
def ghost(wordlist):
print 'Welcome to ghost!!!'
print 'Player one goes first.'
running = True
wordfrag = ''
player = 1
while running:
print 'The current word fragment is ', wordfrag
print 'player %s enter a letter: ' %player
wordfrag += raw_input()
if is_valid(wordfrag,wordlist) == False:
running = False
if is_valid(wordfrag,wordlist) == True:
player = player_switch(player)
print "Word: '%s' is an illegal play, Player %s loses" % (wordfrag, player)
print "Congratulations Player %s, You Win!" % player_switch(player)
print '-'*50
ghost(wordlist)
def is_valid(wordfrag,wordlist):
length = len(wordfrag)
templist = []
for word in wordlist:
if word[:length] == wordfrag:
templist.append(word)
if len(templist) > 1:
if len(wordfrag) > 3 and wordfrag in templist:
return False
else:
return True
return False
def player_switch(player):
if player == 1:
player = 2
else:
player = 1
return player
if __name__ == '__main__':
wordlist = load_words()
ghost(wordlist)
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name:
# Collaborators:
# Time:
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
# TO DO: your code begins here!
def get_letter(player):
letter = raw_input('Please enter the letter: ').lower()
print 'player',player , 'says', letter,'.'
return letter
def up_date_fragment(letter,fragment):
fragment = fragment + letter
return fragment
def is_valid(fragment,wordlist):
if fragment in wordlist and len(fragment)>3:
print 'The fragment {0} is a word longer than 3 letter, the game is over.'.format(fragment)
return False
for word in wordlist:
if str.find(word,fragment) != -1:
print 'The fragment {0} is valid. The game continues.'.format(fragment)
print
return True
print 'The fragment {0} is invalid. The game is over.'.format(fragment)
return False
##is_valid('work',['worked','word'])
def player_goes(player,fragment,wordlist):
print 'Current word fragment:',fragment
letter = get_letter(player)
fragment = up_date_fragment(letter,fragment)
if not is_valid(fragment,wordlist):
print player,'has lost.'
return False
return fragment
def play_ghost(wordlist):
fragment = ''
letter = ''
print 'Welcome to Ghost!'
p1 = raw_input('Please enter the name of player 1: ')
p2 = raw_input('Please enter the name of player 2: ')
raw_input('Press ENTER to begin the game.')
while True:
print 'Player {0}\'s turn.'.format(p1)
fragment = player_goes(p1,fragment,wordlist)
if fragment == False:return
print 'Player {0}\'s turn.'.format(p2)
fragment = player_goes(p2,fragment,wordlist)
if fragment == False:return
if __name__ == '__main__':
word_list = load_words()
play_ghost(word_list)
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name: Hugo A M Torres
# Collaborators: solo
# Time: about 2 friggin days (with plenty of interruptions - can't concentrate quite well)
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence): #I never had to use this - must we use dictionaries? simple strings seem apropriate.
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
print #empty line for aesthetics
# TO DO: your code begins here!
def is_contained(seq,wordlist):
"""Tests wether 'seq' is contained in a word from our list
'seq' must be ascii letters in lowercase"""
for word in wordlist:
if seq.lower() in word[:len(seq)]:
#print 'ta ae'
return True
else:
continue
#print 'nao tem'
return False
#is_contained('f', wordlist)
def turn(player, seq, wordlist):
"""lets player choose a letter.
Returns 'False' in case it completes a word or if its addition makes
impossible the completion of a proper english word.
Returns word fragment if it does not complete but contributes to the
completion of the word
player = current player
seq = current word fragment
wordlist = a list of words in english
"""
print 'Current word fragment: ', "'"+seq+"'"
print player+',',
letter = raw_input("enter a letter: ")
while letter not in string.ascii_letters:#checks if input in composed of letters
print letter,'is not a letter in the english alphabet!'
print
letter = raw_input("Enter a letter: ")
else:
seq += letter.lower()
if seq in wordlist and len(seq)>3:
print player, 'loses because', seq, 'is a word!'
return False
else:
if is_contained(seq, wordlist):
print 'Cool!', seq, 'is part of a word! You get to survive.'
return seq#print word.lower()
else:
print 'no word begins with', seq +'! YOU LOOSE!!'
return False
#turn('Hugo', 'qui', wordlist)
#word=''
def ghost():
"""
Ghost is an inanely popular two-player wordgame. Our goal in
this problem is to implement an interactive Python program that
allows two humans to play a game of Ghost against each other.
For those of you who are unfamiliar with the rules, you may read
all about it at Wikipedia.
"""
print "Welcome to Ghost:"
print
print "Each turn one player guesses a letter trying to avoid forming a full word."
print "One looses when creating a fragment which cannot be turned into a word by "
print "adding further letters OR by completing a valid english word:"
print
Player1 = raw_input("Who's player 1?: ")
Player2 = raw_input("Who's player 2?: ")
CurrentPlayer = Player1 #this variable keeps switching between player1 and 2 each turn.
WaitingPlayer = Player2
word = ""
word = turn(CurrentPlayer, word, wordlist)
print#empty line for aesthetics
CurrentPlayer = Player2
WaitingPlayer = Player1
while word != False:
word = turn(CurrentPlayer, word, wordlist)
if CurrentPlayer == Player1:#This block will exachange players.
CurrentPlayer = Player2
WaitingPlayer = Player1
print #empty line before next iteration
else:
CurrentPlayer = Player1
WaitingPlayer = Player2
print #empty line before next iteration
else:
if CurrentPlayer == Player1:#This block will exachange players.
CurrentPlayer = Player2
WaitingPlayer = Player1
print WaitingPlayer, 'wins!!!'
else:
CurrentPlayer = Player1
WaitingPlayer = Player2
print WaitingPlayer, 'wins!!!'
ghost()
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name: conwayblue
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
print '-'*30
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
# TO DO: your code begins here!
def ghost(wordlist):
print "Welcome to Ghost!"
print "Player 1 goes first"
running = True
wordFrag = ''
player = 1
while running:
print 'The current word fragment is: ', wordFrag
print 'Player %s, enter a letter: ' % player
wordFrag += raw_input()
if is_valid_word(wordFrag, wordlist) == False:
running = False
if is_valid_word(wordFrag, wordlist) == True:
player = which_player(player)
print "Word: '%s' is an illegal play, Player %s loses" % (wordFrag, player)
print "Congratulations Player %s, You Win!" % which_player(player)
print '-'*30
ghost(wordlist)
def is_valid_word(wordFrag, wordlist):
length = len(wordFrag)
templist = []
for word in wordlist:
if word[:length] == wordFrag:
templist.append(word)
if len(templist) > 1:
if len(wordFrag) > 3 and wordFrag in templist:
return False
else:
return True
return False
def which_player(player):
if player == 1:
return 2
return 1
if __name__ == '__main__':
wordlist = load_words()
ghost(wordlist)
No comments. Sign up or log in to comment import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
def get_input_letter():
letter = raw_input('Input a letter: ')
while not letter in string.ascii_letters:
letter = raw_input('Invalid letter, please enter again: ')
return letter
def is_word(word, wordList):
return word in wordList
def word_starts_with(word, fragment):
return word[:len(fragment)] == fragment
def can_make_word(wordFragment, wordList):
wordLength = len(wordFragment)
for validWord in wordList:
if word_starts_with(validWord, wordFragment):
return True
return False
def ghost(wordList):
print "Welcome to Ghost!"
currentPlayer = 'Player 1'
gameDone = False
currentWordFragment = ''
while not gameDone:
print "Current Player: %s" % currentPlayer
print "The current word fragment is: '%s'" % currentWordFragment
currentWordFragment += string.lower(get_input_letter())
print "New word fragment: '%s'" % currentWordFragment
if is_word(currentWordFragment, wordList) and len(currentWordFragment) > 3:
print "'%s' lost because he or she spelled a word" % currentPlayer
gameDone = True
elif not can_make_word(currentWordFragment, wordList):
print "'%s' lost because no word starts with '%s'" % (currentPlayer, currentWordFragment)
gameDone = True
elif currentPlayer == 'Player 1':
currentPlayer = 'Player 2'
else:
currentPlayer = 'Player 1'
print
# Actually load the dictionary of words and point to it with
# the wordList variable so that it can be accessed from anywhere
# in the program.
wordList = load_words()
ghost(wordList)
Comments:Nice job! You're flying through this class. Thanks! That's not completely true, I've been working on the class on and off for a little while, just hadn't discovered that I could post assignments here :) # Problem Set 5: Ghost
# Name: Chris Coe
# Collaborators: none
# Time: 60 min
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
def changePlayers(p):
"""Makes player 1 become player 2 and vice versa"""
if p == 1:
p = 2
else: p = 1
return p
def is_valid(wordFragment, wordlist): #time taken: 60min
"""
Returns True if wordFragment is in the word_list. Will not fail
if the word is a fragment of a valid word. Does not mutate
word or wordlist.
wordFragment: string (the word fragment so far)
wordlist: list of lowercase strings
"""
length = len(wordFragment)
## newWordlist = [word for word in wordlist #creates a new list to check based
## if wordFragment in word[0:length]] #letters input so far
newWordlist = []
for word in wordlist:
if wordFragment in word[0:length]:
newWordlist.append(word)
if len(newWordlist) == 0:
gameover = True
print '\nThere is no word that begins with the letters',wordFragment
elif wordFragment in wordlist and length > 3:
gameover = True
print 'You formed the word',wordFragment
print
else: gameover = False
return (gameover, newWordlist)
def play_game(p):
"""
Plays one round of ghost game with two players.
p = int (player #)
"""
word = ''
gameover = False
primeWordlist = wordlist
while not gameover:
while True:
letter = raw_input('Player '+str(p)+' Enter your letter: ').lower()
if (letter in string.ascii_letters) and (len(letter)==1):
word += letter
print 'Current word fragment: \''+word+'\'\n'
break
else: print '\nInvalid input, please try again.'
gameover,primeWordlist = is_valid(word, primeWordlist) #checks if the fragment is part of a valid word
p = changePlayers(p) #switch whose turn it is
return p
def playGhost():
"""
Play the exciting two-player word game Ghost!
Players alternate entering letters to form a word, or more accurately,
to NOT form a word while forming the beginnings of a word.
Each fragment must be the beginning of an actual word.
Player looses is word wormed is longer than 3 letters.
"""
print 'Welcome to Ghost!'
firstPlayer = raw_input('Enter first player\'s name:')
secondPlayer = raw_input('Enter second player\'s name:')
while True:
menuChoice = int(raw_input('Please choose from the options below:\n'+
'\t1: Start a new game\n\t2: Exit\n\t'))
if menuChoice == 1:
player = play_game(1) #first player starts
if player == 1:
print firstPlayer,'wins!\n'
else: print secondPlayer,'wins!\n'
elif menuChoice == 2: print 'Thank you for playing Ghost!'break
else: print 'Invalid input. Try again'
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
if __name__ == '__main__':
wordlist = load_words()
playGhost()
No comments. Sign up or log in to comment My implementation: # Problem Set 5: Ghost
# Name:
# Collaborators:
# Time:
#
import random
import string
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
inFile.close()
return wordlist
def ghost(wordlist,player):
gameover = False
i = 0
word_frag = ""
print "\n \nWelcome to Ghost!"
while not gameover:
new_wordlist = []
if i > 0: print "\nThe current word frament is", word_frag.upper()
else: print
no_letter = True
while no_letter:
letter = raw_input("%s. Please enter your letter: " %player[i%2])
if letter not in string.ascii_letters or len(letter) != 1:
print "Please enter a single letter!"
else:
no_letter = False
word_frag += letter
for word in wordlist:
if i < len(word) and word[i] == letter.lower():
new_wordlist.append(word)
if len(new_wordlist) == 0:
gameover = True
print "\nGAME OVER LOSER! %s loses because no word begins with %s." %(player[i%2],word_frag)
elif word_frag in new_wordlist and len(word_frag) > 3:
gameover = True
print "\nGAME OVER LOSER! %s loses because %s is a word." %(player[i%2],word_frag)
else:
wordlist = new_wordlist
i += 1
## print wordlist[:10]
return
def play_game():
wordlist = load_words()
player = [None]*2
print
for a in range(2):
player[a] = raw_input("PLAYER %i: Please enter your name: " %(a+1))
while True:
cmd = raw_input('Enter n to play a new game or e to end game: ')
if cmd == 'n':
ghost(wordlist,player)
print
elif cmd == 'e':
break
else:
print "Invalid command."
play_game()
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name:
# Collaborators:
# Time:
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
def is_word(word, word_list):
"""
Returns True if word is in the word_list. Otherwise, returns False.
Does not mutate word_list.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
return word in word_list
def play_letter(fragment, player):
"""displays the current word fragment and prompts the player to enter
the next word"""
check = False
while not check:
print ''
print 'Current word fragment: %s' % (fragment)
turn = raw_input('Player %i says letter: ' % (player))
test = turn in string.ascii_letters
if test == True and len(turn) == 1:
turn = string.lower(turn)
fragment += turn
check = True
else:
print ''
print turn, 'is not valid'
print 'enter a letter'
return fragment
def is_valid_fragment(fragment, word_list):
for word in word_list:
indx = word.find(fragment)
if indx != -1:
if indx == 0:
return True
return False
def update_player(player):
if player is 1:
player = 2
else:
player = 1
return player
def game_over_word(player, fragment):
print 'Player %s loses, %s is a word' % (player, fragment)
if player == 1:
print 'Player 2 wins!'
else:
print 'Player 1 wins!'
def game_over_fragment(player, fragment):
if player == 1:
print 'Player 1 loses!'
player = 2
else:
print 'Player 2 loses!'
player = 1
print 'There is no word that starts with %s' % (fragment)
print 'Player %s wins!' % (player)
def play_again():
while True:
ask = raw_input('Would you like to play again? (y/n): ')
if ask == 'y':
return True
elif ask == 'n':
break
else:
print 'invalid command'
def play_game(word_list):
"""Runs the game Ghost"""
print 'Welcome to Ghost'
print 'Player 1 goes first.'
frag = ''
player = 1
while True:
frag = play_letter(frag, player)
test1 = is_word(frag, word_list)
test2 = is_valid_fragment(frag, word_list)
if test1 == True:
game_over_word(player, frag)
break
elif test2 == False:
game_over_fragment(player, frag)
break
player = update_player(player)
print ''
print 'GAME OVER - Thanks for playing'
print ''
ask = play_again()
if ask == True:
play_game(word_list)
if __name__ == '__main__':
word_list = load_words()
play_game(word_list)
No comments. Sign up or log in to comment #Problem Set 5
#Name: chip
WORDLIST_FILENAME = "words.txt"
def load_words():
inFile = open(WORDLIST_FILENAME, encoding='utf-8')
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
return wordlist
word_list = load_words()
def make_turn(player, fragment):
print("Current word fragment:\'",fragment,"\'")
print(player, "turn")
letter = input(player + " says letter: ")
if check_input(letter) != False:
fragment += letter
check_fragment(fragment)
return fragment
def check_input(letter):
if not letter.isalpha() or len(letter) != 1:
return False
return True
def check_fragment(fragment):
fg = fragment.lower().strip()
if fg in word_list and len(fg) > 3:
return fragment + " is a word"
for word in word_list:
indx = word.find(fg)
if indx != -1:
if indx == 0:
return True
return "no words begins with " + fragment;
def play_game():
players = ["Player 1", "Player 2"]
player = 0
fragment = ""
print ("Welcome to Ghost!")
while True:
fragment = make_turn(players[player], fragment)
fragment_check = check_fragment(fragment)
if fragment_check != True:
print("Player", players[player],"loses because",fragment_check)
break
if player + 1 >= len(players):
player = 0
else:
player += 1
print("\n")
play_game()
No comments. Sign up or log in to comment Word games # Problem Set 5: Ghost
# Name: Joe Li
# Time: 3:30
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
def ghost(wordlist):
print 'Welcome to Ghost!'
current=''
print 'Player 1 goes first.'
turn=1
player=1
valid=1
# if valid=1, this game continue
while valid==1:
if turn>1:
# the odd turn is player 1's turn, the even trun is player 2's turn
if turn%2==0:
player='2'
else:
player='1'
print 'Player '+player+'\'s turn.'
#this messege should only occur since 2nd turn
else:
#the 1st turn is player 1's turn
player='1'
print 'Current word fragment: '+current
letter=string.lower(raw_input('Player '+player+' says letter: '))
valid=0
passtest=0
# if passtest==0 after the test, means that no word begins with the current word
if letter in string.ascii_letters:
# make sure only one letter entered
current+=letter
for word in wordlist:
# check if there's a word start with the current word
if len(current)<=len(word):
if current==word[:len(current)]:
passtest=1
if passtest==1:
if len(current)>3:
# if len(current)>3, the current word can't be an actual word, else the player lose
if not current in wordlist:
# the current word isn't yet an actual word
valid=1
# game continue
turn+=1
else:
# the current word is an actual word
print 'Player '+player+' loses because \''+current+'\' is a word!'
if player==1:
print 'Player 2 wins!'
else:
print 'Player 1 win!'
else:
# if the len(current)<=3, then it doesn't matter
valid=1
turn+=1
else:
# fail the passtest
print 'Player '+player+' loses because no word begins with \''+current+'\'!'
if player=='1':
print 'Player 2 wins!'
else:
print 'Player 1 win!'
else:
# whatever entered is not a letter
print 'Please enter a letter.'
valid=1
ghost(wordlist)
No comments. Sign up or log in to comment This was fun! import random
#---Helper code
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
#---End of helper code
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
def get_letter(message):
"""
Asks the player for a letter, checks that it is a valid
letter and returns that letter if it is.
message: string
return: string
"""
letter = raw_input(message)
while True:
if letter in string.ascii_letters and len(letter) == 1:
return letter
else:
letter = raw_input("not a valid letter, please try again: ")
def update_stub(stub, letter):
"""
Adds a valid letter to a given stub and returns the new stub.
letter: string
stub: string
"""
new_stub = stub + letter
print "Current word fragment is: %s" % string.upper(new_stub)
return new_stub
def validate_stub(stub, wordlist):
"""
Checks if a given stub is a valid part word, also checking if
it is a full word already returning a code for each result:
0 = not a valid word fragment
1 = a valid fragment
2 = already a complete word longer than 3 characters
stub: string
wordlist: list
"""
def slice_words(stub, wordlist):
"""
Slices each item in the wordlist to the same number of characters
as the stub then returns the unique items in this new list.
stub: string
wordlist: list
"""
length = len(stub)
sliced_list = []
for word in wordlist:
sliced_list.append(word[:length])
return set(sliced_list) # cast the list to a set to remove all dups
if stub in slice_words(stub, wordlist):
if stub in wordlist and len(stub) > 3:
return 2
else:
return 1
else:
return 0
# TODO: write outer loop that will ask to play again or exit
def main_loop():
play_again = 1
while play_again == 1:
inner_loop()
again = string.upper(raw_input("Play again (Y or N)"))
while True:
if again == "Y":
play_again = 1
break
elif again == "N":
play_again = 0
break
else:
again = string.upper(raw_input("Please enter Y or N"))
def inner_loop():
letter = ""
stub = ""
player = 1
game_state = 1
print "Welcome to Ghost!"
print "Player 1 goes first"
while game_state == 1:
letter = get_letter("Player %i's letter: " % player)
stub = update_stub(stub, letter)
if player == 1:
player += 1
elif player == 2:
player -= 1
game_state = validate_stub(stub, wordlist)
game_states = {0: "is not a valid word fragment",
1: "is a valid stub",
2: "is a full word"}
if player == 1:
player += 1
elif player == 2:
player -= 1
print "player %i looses because '%s' %s" % (player, string.upper(stub),
game_states[game_state])
main_loop()
No comments. Sign up or log in to comment # Problem Set 5: Ghost
# Name:
# Collaborators:
# Time:
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
def lost_by_word(word, wordlist):
"""Did player lost the game?"""
if len(word) > 3 and word in wordlist:
return True
return False
def lost_by_no_word(word, wordlist):
for tmp_word in wordlist:
if word in tmp_word[0:len(word)]:
print tmp_word
return False
return True
def test_lost_by_word(wordlist):
succeed = True
word = "eye"
if lost_by_word(word, wordlist):
print "Must return False and got True with word " + word
succeed = False
word = "banana"
if not lost_by_word(word, wordlist):
print "Must return True and got False with word " + word
succeed = False
if succeed:
print "All test passed"
else:
print "Failed"
def test_lost_by_no_word(wordlist):
succeed = True
word = "zar"
if not lost_by_no_word(word, wordlist):
print "Must return True and got False with word " + word
succeed = False
word = "pyn"
if lost_by_no_word(word, wordlist):
print "Must return False and got True with word " + word
succeed = False
if succeed:
print "All test passed"
else:
print "Failed"
def ghost(wordlist):
print "Welcome to Ghost"
print "Player 1 goes first."
game_over = False
fragment = ''
current_player = 1
while not game_over:
print "Current word fragment: '" + fragment + "'"
no_letter = True
while no_letter:
letter = raw_input("Player " + str(current_player) + " says letter: ")
if letter not in string.ascii_letters:
print "A letter please!"
else:
no_letter = False
fragment += letter.lower()
#print fragment
if lost_by_word(fragment, wordlist):
game_over = True
print "Player " + str(current_player) + " loses because '" + fragment + "' is a word!"
if lost_by_no_word(fragment, wordlist):
game_over = True
print "Player " + str(current_player) + " loses no word begins with " + fragment
if current_player == 1:
current_player = 2
else:
current_player = 1
if game_over:
print "Player " + str(current_player) + " wins!"
wordlist = load_words()
ghost(wordlist)
# test_lost_by_word(wordlist)
# test_lost_by_no_word(wordlist)
No comments. Sign up or log in to comment # Problem Set 5, Part 2
#########
# GHOST #
#########
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().upper())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
def isvalid(wordSoFar, wordlist):
"""
Takes in the word created so far as well as a list of valid words.
Returns, in a tuple:
[0] Whether the game has ended (a word has been or cannot be formed)
[1] An updated word list containing the remaining possible words
"""
numltr = len(wordSoFar)
# Make a list of all possible words that can be formed.
# The word list is updated to include only these words.
newwordlist = [word for word in wordlist if wordSoFar in word[0:numltr]]
# Checks to see if any possible words were found
if len(newwordlist) == 0:
gameover = True
print '\nThere is no word that begins with the letters',\
wordSoFar + '!'
# Checks to see if a word has already been formed
elif wordSoFar in wordlist and numltr > 3:
gameover = True
print '\nYou have formed the word', wordSoFar + '!'
else: gameover = False
return (gameover, newwordlist)
def swapPlayer(p):
"""Switches the player from 1 to 2 or vice versa"""
if p == 1:
p = 2
else: p = 1
return p
def playGhost(p):
"""
This represents a round of the game.
The input is the starting player; the winner is the output.
"""
word = ''
wordlist = masterwordlist
gameover = False
while not gameover:
# This runs until the player enters an acceptable character
while True:
print '\nThe word so far is:', word
ltr = raw_input("It's your turn, Player " + str(p) +\
'. ' + 'Add a letter! ').upper()
# Stops the loop when a letter is entered
if (ltr in string.ascii_letters) and (len(ltr) == 1):
word += ltr
break
# Helpful message if an unacceptable character is entered
print '\nInvalid input. Try again!'
gameover,wordlist = isvalid(word, wordlist)
p = swapPlayer(p)
print 'Player',p,'wins!'
return p
def ghost():
"""
Play the exciting two-player word game Ghost!
Players alternate entering letters to form a word, or more accurately,
to NOT form a word while forming the beginnings of a word.
A player loses if he or she:
(1) Forms a complete word greater than 3 letters long
(2) Creates a fragment which cannot become a word by adding more letters
("QZ", for example)
"""
scores = [0,0]
first = 1 # Player 1 goes first in the first game. It then alternates.
while True:
action = raw_input('\nWelcome to Ghost! Enter "1" to play a round,'+\
'"2" to reset the scores, or "3" to exit. ')
if action is '1':
winrar = playGhost(first)
scores[winrar-1] += 1
print '\nThe overall score is:'
print 'Player 1:',scores[0]
print 'Player 2:',scores[1],'\n'
first = swapPlayer(first)
elif action is '2':
scores = [0,0]
print 'The scores have been reset.'
elif action is '3':
break
else: print '\nInvalid input. How about trying one of the given'+\
'options?'
if __name__ == '__main__':
masterwordlist = load_words()
ghost()
No comments. Sign up or log in to comment I wrote Ghost with the same variable-passing work-around I used for global variables in the 6.00 Wordgame. #!/usr/bin/env python
#-*- coding:utf-8 -*-
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "/home/dave/Documents/python/Assignments/ps5/words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
word_list = []
for line in inFile:
word_list.append(line.strip().lower())
print " ", len(word_list), "words loaded."
return word_list
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
# word_list = load_words()
#def generate_letter():
# '''Returns a random, lowercase letter'''
# index = random.randint(0, 25)
# char = string.lowercase[index]
# return char
# returns true if sequence is a valid word longer than 3 characters
def is_valid_word(word, word_list):
"""
Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list. DOES NOT FAIL IF word IS AN
INVALID WORD FRAGMENT.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
if len(word) < 4:
return False
elif word in word_list:
return True
else:
return False
#
# returns true if input is a valid word fragment or word, else returns false. To confirm 'word' is a playable fragment, contrast result with is_valid_word()
def is_valid_fragment(fragment, word_list):
n = len(fragment)
for word in word_list:
if len(word) < n: # if 'word' is smaller than frag, skip
continue
for i in range(0,n):
if word[i] == fragment[i]: # stepwise comparison iterating by index
if i == (n - 1):
return True
else:
i += 1
continue
else:
break
return False
def update_player(player):
if player is 1:
player = 2
else:
player = 1
return player
# tests word sequence. If valid word fragment, returns 1. If invalid word fragment, returns 2. If valid word longer than 3 characters, returns 0.
def word_test(word, word_list):
is_word = is_valid_word(word, word_list)
if is_word:
return 0
else:
frag = is_valid_fragment(word, word_list)
if frag:
return 1
else:
return 2
def new_game(word_list):
newgame = raw_input("Play again? (y/n)\n")
if newgame == 'y':
play_game(word_list)
elif newgame == 'n':
print "Thanks for playing!"
return ""
else:
print newgame, " is not a valid option."
new_game(word_list)
# Effectively plays a round. Accepts user input. converts uppercase to lower case, requests new input if not a valid character. User can input '.' to exit.
def play_char(word_list, word, player):
print "Current word fragment: ", word
print "\nPlayer", player,
char = raw_input("plays letter: ")
if char == '.':
print "Thanks for playing!"
return ''
elif char in string.letters:
char = string.lower(char)
word_temp = word[:] + char
test = word_test(word_temp, word_list)
if test == 2:
print word_temp, " is not a valid word fragment. Please try again.\n"
play_char(word_list, word, player)
elif test == 0:
print word_temp, "is a word."
print "GAME OVER."
new_game(word_list)
elif test == 1:
player = update_player(player)
word = word_temp
play_char(word_list, word, player)
else:
print char, " is not a valid character."
play_char(word_list, word, player)
## initiates computers turn
## def computer_plays():
##
## initiates two player game. Prompts whether player wants to go first.
## def two_players(word_list):
## pass
##
## initiates a single player game
## def single_player(word_list):
## pass
# initiate game.
# ONCE GAME IS BUILT: prompt number of players. If 1, player vs. computer. If 2, human vs. human. After each round, prompt player if they want to play again. Also, insert option to track score later on.
def play_game(word_list):
word = ''
player = 1
print "Welcome to Ghost!"
print "Player 1 goes first. Type '.' to quit round."
play_char(word_list, word, player)
if __name__ == '__main__':
word_list = load_words()
play_game(word_list)
Comments:my one 'problem' with this set of code (which I haven't gone through your other code to see if you do the same thing), but some of your comments are too long for a single line. If you read the 'Code Like a Pythonista' article about long lines it talks about good code practice. I linked to the part about long lines: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#long-lines-continuations so apparently you can't edit comments after you post them, but here's an actual link to the Code Like a Pythonista book, specifically about line length |
No comments. Sign up or log in to comment