python函数的作用域是什么_函数变量:函数作用域的范围是什么

最近我一直在用python开发一个文字游戏,尽管如此,我还是有一点问题细节。那个这个游戏的想法是用随机给定的一只手上的字母创造单词。协调游戏的功能要求用户输入一个字母并根据它,让他/她玩一个新的手,再次玩同一个手或退出游戏。问题是我不能让游戏回到前一手,让用户再次玩。相反,该代码返回前一手的修改版本,这样,如果您正确地输入了一个单词,该单词中的字母就不会出现在其中。我认为这是不可能的,因为“更新手”的功能位于不同的范围。我正在使用python3.2.1

我发布了整个代码,这样你可以测试它,看看它做了什么。但问题在于它们的功能:play_game、play_hand和update_hand。在import random

import string

VOWELS = 'aeiou'

CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

HAND_SIZE = 7

SCRABBLE_LETTER_VALUES = {

'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10

}

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')

# 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

def get_word_score(word, n):

"""

Returns the score for a word. Assumes the word is a

valid word.

The score for a word is the sum of the points for letters

in the word multiplied by the length of the word, plus 50

points if all n letters are used on the first go.

Letters are scored as in Scrabble; A is worth 1, B is

worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.

word: string (lowercase letters)

returns: int >= 0

"""

score = 0

for character in word:

score = score + (SCRABBLE_LETTER_VALUES[character])

score = score * len(word)

if len(word) == 7:

score = score + 50

return score

def display_hand(hand):

"""

Displays the letters currently in the hand.

For example:

display_hand({'a':1, 'x':2, 'l':3, 'e':1})

Should print out something like:

a x x l l l e

The order of the letters is unimportant.

hand: dictionary (string -> int)

"""

for letter in hand.keys():

for j in range(hand[letter]):

print (letter,)

def deal_hand(n):

"""

Returns a random hand containing n lowercase letters.

At least n/3 the letters in the hand should be VOWELS.

Hands are represented as dictionaries. The keys are

letters and the values are the number of times the

particular letter is repeated in that hand.

n: int >= 0

returns: dictionary (string -> int)

"""

hand={}

num_vowels = int(n / 3)

for i in range(num_vowels):

x = VOWELS[random.randrange(0,len(VOWELS))]

hand[x] = hand.get(x, 0) + 1

for i in range(num_vowels, n):

x = CONSONANTS[random.randrange(0,len(CONSONANTS))]

hand[x] = hand.get(x, 0) + 1

return hand

def update_hand(hand, word):

"""

Assumes that 'hand' has all the letters in word.

In other words, this assumes that however many times

a letter appears in 'word', 'hand' has at least as

many of that letter in it.

Updates the hand: uses up the letters in the given word

and returns the new hand, without those letters in it.

Has no side effects: does not modify hand.

word: string

hand: dictionary (string -> int)

returns: dictionary (string -> int)

"""

for i in word:

new_hand = hand

new_VOWELS = VOWELS

new_CONSONANTS = CONSONANTS

if i in VOWELS:

new_VOWELS = new_VOWELS.replace("i", "")

new_hand[i] = new_hand.get(i, 0) - 1

if new_hand[i] <= 0:

new_hand.pop(i, None)

else:

new_CONSONANTS = new_CONSONANTS.replace("i", "")

new_hand[i] = new_hand.get(i, 0) - 1

if new_hand[i] <= 0:

new_hand.pop(i, None)

return (new_hand)

def is_valid_word(word, hand, 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.

word: string

hand: dictionary (string -> int)

word_list: list of lowercase strings

"""

for character in word:

x = 0

if character in hand:

x = x + 1

if (x==(len(word)-1)) and (word in word_list):

return (True)

else:

return (False)

def calculate_handlen(hand):

handlen = 0

for v in hand.values():

handlen += v

return handlen

def play_hand(hand, word_list):

"""

Allows the user to play the given hand, as follows:

* The hand is displayed.

* The user may input a word.

* An invalid word is rejected, and a message is displayed asking

the user to choose another word.

* When a valid word is entered, it uses up letters from the hand.

* After every valid word: the score for that word is displayed,

the remaining letters in the hand are displayed, and the user

is asked to input another word.

* The sum of the word scores is displayed when the hand finishes.

* The hand finishes when there are no more unused letters.

The user can also finish playing the hand by inputing a single

period (the string '.') instead of a word.

hand: dictionary (string -> int)

word_list: list of lowercase strings

"""

score = 0

han = hand

while True:

print ("Score= ", score)

word = str(input("Enter your word: "))

value = is_valid_word(word, han, word_list)

if value == True:

print ("Congratulations, that word is worth", get_word_score(word, 7), "points")

print ("Please input another word")

han = update_hand(han, word)

print ("Current hand=")

display_hand(han)

score = score + get_word_score(word, 7)

elif word == "." or len(hand)==0:

break

else:

print ("Current hand=")

display_hand(han)

print ("Sorry, that word is not valid")

print ("Please choose another word")

def play_game(word_list):

"""

Allow the user to play an arbitrary number of hands.

* Asks the user to input 'n' or 'r' or 'e'.

* If the user inputs 'n', let the user play a new (random) hand.

When done playing the hand, ask the 'n' or 'e' question again.

* If the user inputs 'r', let the user play the last hand again.

* If the user inputs 'e', exit the game.

* If the user inputs anything else, ask them again.

"""

global handy

handy = deal_hand(7)

while True:

print ("Use 'n' to play a new hand, 'r' to play the last hand again or 'e' to exit game")

inp = str(input("Enter a letter:'n' or 'r' or 'e': ="))

if inp == 'n':

hand = deal_hand(7)

handy = hand

print("Current hand =")

display_hand(hand)

play_hand(hand, word_list)

elif inp == 'r':

print("Current hand =")

display_hand(handy)

play_hand(handy, word_list)

elif inp == 'e':

exit(play_game)

else:

print ("Please input a valid letter")

if __name__ == '__main__':

word_list = load_words()

play_game(word_list)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值