Wednesday, 16 January 2013

Example 19: Hangman server (1/3)


Example 19: Hangman server (1/3)

import inbox, messaging, appuifw, e32, contacts
current_word = None
guessed = None
num_guesses = 0
def new_game():
global current_word, guessed, num_guesses
word = appuifw.query(u"Word to guess", "text")
if word:
current_word = word.lower()
guessed = list("_" * len(current_word))
num_guesses = 0
print "New game started. Waiting for messages..."
def game_status():
if current_word:
appuifw.note(u"Word to guess: %s\n" % current_word +\
"Current guess: %s\n" % "".join(guessed) +\
"Number of gusses: %d" % num_guesses)
else:
appuifw.note(u"Game has not been started")
def quit():
print "HANGMAN SERVER EXITS"
app_lock.signal()
The first section of the code contains the functions to handle UI events:
new game(), game status() and exit(). The state of the game is
maintained in three variables:
• the string current word, which contains the word to be guessed
• the list guessed, which contains the already guessed characters in
their correct positions
• the integer num guesses, which contains the current number of
guesses in total.
It is convenient to handle guessed as a list instead of a string, since
we cannot modify individual characters of a string without making a new
copy of it. In contrast, list items can be modified without any restrictions.
Notice how the guessed list is created in function new game():
you can use the multiplication operator to make a string of a repeating
character or substring. Once we have created a string containing as many
dashes as there are characters in current word, we can convert it to
a list of characters with function list(). For printing, the list is later
converted back to a string with the join() function.
The three game state variables are shared among all functions in the
game source code. In contrast, some variables, such as word in the
function new game(), are used locally in one function. Python makes a
distinction between global and local variables: each variable assignment
is assumed to be local to a function unless it is explicitly declared as
global. This distinction is explained in the language lesson.

No comments:

Post a Comment