search
HomeBackend DevelopmentPython Tutorial跟老齐学Python之做一个小游戏

在讲述有关list的时候,提到做游戏的事情,后来这个事情一直没有接续。不是忘记了,是在想在哪个阶段做最合适。经过一段时间学习,看官已经不是纯粹小白了,已经属于python初级者了。现在就是开始做那个游戏的时候了。

游戏内容:猜数字游戏

太简单了吧。是的,游戏难度不大,不过这个游戏中蕴含的东西可是值得玩味的。

游戏过程描述

程序运行起来,随机在某个范围内选择一个整数。
提示用户输入数字,也就是猜程序随即选的那个数字。
程序将用户输入的数字与自己选定的对比,一样则用户完成游戏,否则继续猜。
使用次数少的用户得胜.
分析

在任何形式的程序开发之前,不管是大还是小,都要进行分析。即根据功能需求,将不同功能点进行分解。从而确定开发过程。我们现在做一个很小的程序,也是这样来做。

随机选择一个数

要实现随机选择一个数字,可以使用python中的一个随机函数:random。下面对这个函数做简要介绍,除了针对本次应用之外,还扩展点,也许别处看官能用上。

还是要首先强化一种学习方法,就是要学会查看帮助文档。

复制代码 代码如下:

>>> import random  #这个是必须的,因为不是内置函数
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

>>> help(random.randint)

Help on method randint in module random:

randint(self, a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

耐心地看文档,就明白怎么用了。不过,还是把主要的东西列出来,但仍然建议看官在看每个函数的使用之前,在交互模式下通过help来查看文档。

随机整数:

复制代码 代码如下:

>>> import random
>>> random.randint(0,99)
21

随机选取0到100间的偶数:

复制代码 代码如下:

>>> import random
>>> random.randrange(0, 101, 2)
42

随机浮点数:

复制代码 代码如下:

>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881

随机字符:

复制代码 代码如下:

>>> import random
>>> random.choice('qiwsir.github.io')
'g'

多个字符中选取特定数量的字符:

复制代码 代码如下:

>>> import random
random.sample('qiwsir.github.io',3)
['w', 's', 'b']

随机选取字符串:

复制代码 代码如下:

>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'

洗牌:把原有的顺序打乱,按照随机顺序排列

复制代码 代码如下:

>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]

有点多了。不过,本次实验中,值用到了random.randint()即可。多出来是买一送一的(哦。忘记了,没有人买呢,本课程全是白送的)。

关键技术点之一已经突破。可以编程了。再梳理一下流程。画个图展示:

(备注:这里我先懒惰一下吧,看官能不能画出这个程序的流程图呢?特别是如果是一个初学者,流程图一定要自己画哦。刚才看到网上一个朋友说自己学编程,但是逻辑思维差,所以没有学好。其实,画流程图就是帮助提高逻辑思维的一种好方式,请画图吧。)

图画好了,按照直观的理解,下面的代码是一个初学者常常写出来的(老鸟们不要喷,因为是代表初学者的)。

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8

import random

number = random.randint(1,100)

print "请输入一个100以内的自然数:"

input_number = raw_input()

if number == int(input_number):
    print "猜对了,这个数是:"
    print number
else:
    print "错了。"

上面的程序已经能够基本走通,但是,还有很多缺陷。

最明显的就是只能让人猜一次,不能多次。怎么修改,能够多次猜呢?动动脑筋之后看代码,或者看官在自己的代码上改改,能不能实现多次猜测?

另外,能不能增强一些友好性呢,让用户知道自己输入的数是大了,还是小了。

根据上述修改想法,新代码如下:

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8

import random

number = random.randint(1,100)

print "请输入一个100以内的自然数:"

input_number = raw_input()

if number == int(input_number):
    print "猜对了,这个数是:"
    print number
elif number > int(input_number):
    print "小了"
    input_number = raw_input()
elif number     print "大了"
    input_number = raw_input()
else:
    print "错了。"

嗯,似乎比原来进步一点点,因为允许用户输入第二次了。同时也告诉用户输入的是大还是小了。但,这也不行呀。应该能够输入很多次,直到正确为止。

是的。这就要用到一个新的东西:循环。如果看官心急,可以google一下while或者for循环,来进一步完善这个游戏,如果不着急,可以等等,随后我也会讲到这部分。

这个游戏还没有完呢,即使用了循环,后面还会继续。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools