The stupid way to learn Python3 Baidu network disk, the stupid way to learn python3 advanced chapter pdf

This article will tell you about the stupid way to learn Python 3 advanced pdf Baidu network disk, and the stupid way to learn python 3 e-book download. I hope it will be helpful to you. Don’t forget to bookmark this site.

"Stupid way" to learn Python 3 basic articles series

"Stupid Ways" to learn Python 3 Basics Part 1 - Printing and Input
"Stupid Ways" to learn Python 3 Basics Part 2 - File Operations
"Stupid Ways" to Learn Python 3 Basics Part 3 - Functions
"Stupid Ways" to learn Python 3 Basics Part 4 - Data Containers and Program Structure
"Stupid Ways" to Learn Python 3 Basics Part 5 - Object-Oriented Classes
"Stupid Ways" to Learn Python 3 Basics Part 6 - Project Skeleton and Automatic Testing
"Stupid Ways" "Learning Python 3 Basics Part Seven - Building a Simple Website



foreword

It's finally the last article in this series, and I'm a little excited. Although there was a lot of time in the middle, every code word made me understand the benefits of persistence and summary, and I was able to reconstruct the knowledge originally stored in a corner of my mind again and become my own knowledge building The foundation of the study, the brain also carried out a spiritual "massage" in each summary.
In this article, I will use the object-oriented programming method to write a dialogue-like three-body game (with Zhang Beihai as the protagonist), and create a simple game website through flask (only this is what I have learned so far).

7.1 Web framework-flask installation and project creation

To use web services, a "Web" framework needs to be installed, reducing the development burden. In the book, the application of the flask framework is mainly introduced. After activating the virtual environment, pass

pip install flask

To realize the installation, the installation process is as shown in the figure below:
installflask
After the flask installation is complete, you need to create a threebody project, and enter the following command in PowerShell:

cd projects
mkdir threebody
cd threebody
mkdir bin
mkdir threebody
mkdir tests
mkdir docs
mkdir templates
new-item -type file .\threebody\__init__.py
new-item -type file .\tests\__init__.py

The difference from the previous project creation is that a new directory named "templates" is created to store the html template of the website.

7.2 Using object-oriented method to design three-body game

Create a new game.py in the threebody\threebody directory as the main program of the threebody game. The design idea of ​​the whole three-body game is carried out through scene switching. Players can enter different plots by making choices, similar to games such as "Autumn Memories". The core of the program is the Scene-like design, and the specific code is:

class Scene:
    """基本场景类"""
    def __init__(self, name, deion):
        self.name = name
        self.deion = deion
        self.paths = {}
    
    def enter(self, direction):
        return self.paths.get(direction, None)

    def add_paths(self, paths):
        self.paths.update(paths)

Each scene initializes the class Scene as an object. When initializing, render the name and plot description of the scene, and initialize the dictionary paths that determine the direction of the plot. Use the enter(direction) function to return the scene object specified by direction, and use the add_paths(paths) function to update the plot direction dictionary paths, so as to establish the plot connection of different scene objects. The context of the plot is shown in the figure below:
game plot
the game plot starts from Natural Selection and ends with the Space Mausoleum. If each scene in the middle is selected incorrectly, it will enter the death scene (according to the different plots, the death scene needs to be subdivided). The game can be replayed by selecting play again during the death scene. This plot flow is realized through add_paths in Scene. The specific code is as follows:

natureSelectionFleet.add_paths({
    '1': death_1_1,
    '2': death_1_2,
    '3': death_1_3,
    '4': escape,
    '*': natureSelectionFleet 
})

escape.add_paths({
    '1': death_2,
    '2': death_2,
    '3': death_2,
    '4': control_terminal,
    '*': escape
})       
        
control_terminal.add_paths({
    '1': extrasolar,
    '2': death_3,
    '3': death_3,
    '4': death_3,
    '*': control_terminal
})

extrasolar.add_paths({
    '1': fleet_earth, 
    '2': death_2,
    '3': death_4,
    '*': extrasolar
})

fleet_earth.add_paths({
    '1': death_2,
    '2': ultimate_rule_fleet,
    '3': ultimate_rule_fleet,
    '*': fleet_earth
})

ultimate_rule_fleet.add_paths({
    '1': blue_space_fleet,
    '2': death_6,
    '3': death_5,
    '4': death_2,
    '*': ultimate_rule_fleet
})

blue_space_fleet.add_paths({
    '1': last_episode,
    '2': death_6,
    '*': blue_space_fleet
})

The * here represents the invalid input of the player. When the input is invalid, the plot scene will not switch and stay in the original scene. The remaining work is to design different scene objects, the specific code is:

#自然选择号死亡场景
death1 = """
        自然选择号在与三体文明'水滴'探测器的激战中被摧毁......
         """

death_1_1 = Scene("游戏失败",
f"""
原来你也接收了思想钢印。
警卫员!
马上逮捕章北海!

{death1}
""")
      
death_1_2 = Scene("游戏失败",
f"""
章北海,你这个懦夫!
你的内心充分暴露出来了,表面是个人类必胜论者,
内心确是一个失败论者。
警卫员!
马上逮捕章北海!

{death1}
""")

death_1_3 = Scene("游戏失败",
f"""
你是云天明?
警卫员!
马上通知地球舰队!

{death1}
""")

death_2 = Scene("游戏失败", death1)

death_3 = Scene("游戏失败", 
f"""
飞船控制失败!

{death1}
"""
)

death_4 = Scene("游戏失败", 
f"""
东方延绪:
        章北海, 我代表星舰地球逮捕你。
        全员准备,返航迎击三体人的探测器。

        {death1}
""")

death_5 = Scene("游戏失败",
f"""
在更改航线后,遭遇了三体文明的舰队,被击毁...
""")

death_6 = Scene("游戏失败",
f"""
遭遇了黑暗森林法则,被星舰地球中的其它战舰次声波核弹攻击,
全员阵亡!
""")

#自然选择号
natureSelectionFleet = Scene("自然选择号", 
"""
东方延绪:
        章北海执行舰长,我是自然选择号的舰长东方延绪。欢迎您。
        现在我把自然选择号的指挥权交给您。飞船有四种前进模式,
        当进入前进4模式时,船员必须进入睡眠仓。现在,我需要
        再次确认您是否受到思想钢印的影响,请您回答我这个问题:
        '人类是否必胜?'
        [1] 必胜
        [2] 必败
        [3] 这要取决于我所见到的三体文明
        [4] 人的意志胜过一切
""")

#逃离太阳系
escape = Scene("自然选择号战舰控制中心",
"""
东方延绪:
        章北海舰长,现在我交出自然选择号的控制权。据地球舰队传来的最新消息:
        三体文明的探测器-水滴-已经抵达太阳系的边缘,15分钟后将与地球舰队接触。
        现在飞船等待您发布第一条命令:
        [1] 前进1 逃离太阳系
        [2] 前进2 逃离太阳系
        [3] 前进3 逃离太阳系
        [4] 前进4 逃离太阳系
""")

#飞控终端
control_terminal = Scene("自然选择号战舰飞控终端","""
警告!
警告!
警告!
飞船进入前进4必须通知所有船员进入深海睡眠模式。请输入飞控密码:
[1] Man Always Remember Love Because Of Romance Only
[2] If You Give Me A Pivot Point I Could Move The Earth
[3] The Sun Rather Than The Earth At The Center Of The Universe
[4] Two Heads Are Always Better Than One
""") 

# 太阳系外
extrasolar = Scene("自然选择号战舰","""
飞船已经飞出了太阳系,身后的蓝色空间号、深空号、终极规律号以及企业号正在追击。
下一步命令是:
[1] 延续人类文明,向前飞,向远飞
[2] 掉头击毁追击战舰
[3] 将舰队指挥权交给东方延续舰长
"""
)

# 星舰地球
fleet_earth = Scene("星舰地球","""
地球舰队已经被水滴摧毁.......
五艘战舰必须延续文明的责任,太空将是我们最后的归宿。星舰地球决定:
[1] 处决人类的叛徒章北海,回去与水滴战斗
[2] 处决人类的叛徒章北海,继续飞往十八光年外的天鹅座NH558J2
[3] 章北海是英雄,继续飞往十八光年外的天鹅座NH558J2
"""
)

#终极规律号
ultimate_rule_fleet = Scene("终极规律号","""
终极规律号战舰中出现了一种不安的气氛......
十四光年,飞船的资源是有限的,如何得到补给?
舰长,我们该怎么办?
[1] 向其它四艘战舰发射次声波氢弹
[2] 向其它四艘战舰求援,请求补给
[3] 要求星舰地球更改航程,找到补给点
[4] 回地球吧
"""
)

#蓝色空间号
blue_space_fleet = Scene("蓝色空间号","""
警告!
警告!
警告!
终极规律号的次声波氢弹冲击波即将到达....
防御成功,舰队损伤5%...
等待下一步命令:
[1] 发射高能伽马射线激光击毁终极规律号
[2] 逃离
""")

#最后的场景
last_episode = Scene("太空陵墓","""
蓝色空间号带走了所有的燃料和配件,并将自然选择号、企业号、深空号的
残骸切割多段,围城巨石阵,构建了一处太空陵墓,纪念人类第一次体会到
宇宙‘黑暗森林’的可怕。

恭喜你,顺利通过了剧情!
"""
) 

START = 'natureSelectionFleet'
# 返回场景名字对应的场景对象
def load_scene(name):
    return globals().get(name) 
# 返回场景对象对应的场景名字
def name_scene(scene):
    for key, value in globals().items():
        if value == scene:
            return key

7.3 Write an automatic test script for game.py

Next, an automated test script for game.py will be written. Create a new game_tests.py in the tests\ directory, and the test tool is still nosetests. Test the initialization function, add_paths and enter functions of Scene in game.py respectively. The specific code is:

from nose.tools import *
from threebody.game import *


def test_scene():
    gold = Scene("GoldRoom",
                """This room has gold in it you can grab. 
                There's a door to the north.""")
    assert_equal(gold.name, "GoldRoom")
    assert_equal(gold.paths, {})

def test_add_enter_paths():
    center = Scene("Center", "Test room in the center.")
    north = Scene("North", "Test room in the north.")
    south = Scene("South", "Test room in the south.")

    center.add_paths({'north': north, 'south': south})
    assert_equal(center.enter('north'), north)
    assert_equal(center.enter("south"), south)


def test_game_map():
    start_room = load_scene(START)
    assert_equal(start_room.enter('1'), death_1_1)
    assert_equal(start_room.enter('2'), death_1_2)
    assert_equal(start_room.enter('3'), death_1_3)
    assert_equal(start_room.enter('4'), escape)
    assert_equal(start_room.enter('*'), natureSelectionFleet)

It should be noted that when importing features, all mentioned classes and global variables need to be imported from threebody\game.py. The test results in PowerShell are:
gametests

7.4 Writing HTML Templates

In the three-body game, we used layout templates and POST forms. Create two files show_room.html and layout.html in the templates\ directory. The layout template code is:

<html>
    <head>
        <title>三体游戏</title>
    </head>
    <body>
        {% block content %}

        {% endblock %}
    </body>
</html>

Mainly contains the title "Three-Body Game". The POST form code is:

{% extends "layout.html" %}

{% block content %}

<h1>{
    
    { room.name }}</h1>

<pre>
    {
    
    { room.deion }}
</pre>

{% if room.name == "游戏失败"%}
    <p><a href="/">Play Again?</a></p>
{% elif room.name == "太空陵墓" %}
    <p><a href="/">退出游戏</a></p>
{% else %}
    <p>
        <form action='/play' method='POST'>
            - <input type='text' name='action'><input type='SUBMIT'>
        </form>
    </p>    
{% endif %}

{% endblock %}

In this html file, the layout template is loaded first, and then the name of the scene object and the plot description are displayed on the web page. Then enable the if-else conditional judgment statement. When the string named "game failure" is detected, "play again?" will be displayed at the bottom of the plot description; when the string named "Space Mausoleum" is detected, Display "Exit Game" at the bottom of the plot description; otherwise, display a text box waiting for the user to enter information to advance the plot.

7.5 Create a three-body web game engine

The python file of the game engine should be created in the main directory of the project, that is, the first threebody directory. I created a web engine file called app.py. It mainly refers to the FLASK, session, redirect, url_for, request, render_template features in the flask network framework. Of course, in order to run the game, game.py also needs to be introduced. The specific code is as follows:

from flask import Flask, session, redirect, url_for, request
from flask import render_template
from threebody import game

app = Flask(__name__)

@app.route("/")
def index():
    #this is used to "setup" session with starting values
    session['scene_name'] = game.START #利用会话临时存储场景名字
    return redirect(url_for("play"))


@app.route("/play", methods=['POST', 'GET'])
def play():
    scene_name = session.get('scene_name') #获得当前场景的名字

    if request.method == 'GET':
        room = game.load_scene(scene_name) #通过场景的名字加载场景对象
        return render_template("show_room.html", room=room)    
 
    else:
        action = request.form.get('action')
        
        if scene_name and action:
            room = game.load_scene(scene_name)
            next_scene = room.enter(action) #获取下一个场景的对象
            if not next_scene:
                next_scene = room.enter('*')
                #将下一个场景的名字存在临时会话中,供web服务器使用
                session['scene_name'] = game.name_scene(next_scene)
            else:
                session['scene_name'] = game.name_scene(next_scene)
        return redirect(url_for("play"))

# YOU SHOULD CHANGE THIS IF YOU PUT ON THE INTERNET
app.secret_key = 'sdjffiweriwuer923riew3shfs'

if __name__ == "__main__":
    app.run()

The first main function of the program is index(), which represents the main directory "/", and uses the session temporary session to store the scene name, so that it can be used in the next call. Return to the "/play" directory. The second main function of the program is play(). There are two modes POST or GET in the "/play" directory. When no user input is obtained, the default is GET. At this time, the engine loads the show_room.html file. After the user enters valid information, it enters the post mode. At this time, the engine obtains the next plot scene according to the information, stores it in the session session, and returns to the play directory to load the next scene. Finally, run the web game engine automatically through the app.run() statement.

7.6 Game running effect

In Powershell, run

python app.py

The result is:
start flask
the debug mode is closed at this time, if you want to open it, change app.run() to app.run(debug = True). When running on the local web page, according to the prompt, enter localhost:5000/ on the browser. The effect is as follows:
renderings

epilogue

This is the first series of articles written by myself on CSDN. Although there is nothing new in the content, I insist on writing, organize my thinking very clearly, and know what I haven't mastered yet. Next, you have to be quiet for a while, continue to study, and keep writing.

Guess you like

Origin blog.csdn.net/chatgpt001/article/details/132104025