
上QQ阅读APP看书,第一时间看更新
3.3 游戏初步——猜单词游戏
【例3-14】游戏初步——猜单词游戏。计算机随机产生一个单词,打乱字母顺序,供玩家去猜。

猜单词游戏
分析:游戏中需要随机产生单词及随机数字,所以引入random模块随机数函数,其中random.choice()可以从序列中随机选取元素。例如:

游戏中随机挑出一个单词word后,如何把单词word的字母顺序打乱,方法是随机从单词字符串中选择一个位置position,把position位置的字母加入乱序后的单词jumble,同时将原单词word中position位置的字母删去(通过连接position位置前字符串和其后字符串实现)。通过多次循环就可以产生新的乱序后的单词jumble。

猜单词游戏的程序代码如下:

程序运行结果:
