"Stupid method" learning Python 3 basic articles series
"Stupid method" learning Python 3 basic part 1 - printing and input
"Stupid method" learning Python 3 basic part 2 - file operation
"Stupid method" learning Python 3 basic part 3 - function
"Stupid method" learning Python 3 Foundation Part 4 - data container and program structure
The fifth part of "the basics of Python's object-oriented approach"
"Stupid method" learning Python 3 Foundation Part 6 - Project skeleton and automatic testing
"Stupid method" learn Python 3 basic part 7 - build a simple website
preface
Finally came to the last article of this series, a little excited. Although there is a lot of time between them, each codeword makes me understand the benefits of persistence and summary. I can reconstruct the knowledge originally stored in a corner of my mind and become the foundation of my knowledge building. My brain also has a spiritual "massage" in each summary.
In this article, I will use the object-oriented programming method to write a dialogue three body game (Zhang Beihai as the protagonist), and create a simple game website through flash (I only learn this at present).
7.1 Web Framework - Flash installation and project creation
To use web services, you need to install a "Web" framework to reduce the development burden. In the book, it mainly introduces the application of flash framework. After activating the virtual environment, the
pip install flask
The installation process is shown as follows:
After installing flash, 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
Different from the previous project creation, a new directory named "templates" is created to store the html templates of the website.
7.2 using object-oriented method to design three body game
Create a new game in the threebody\threebody directory Py as the main program of the three body game. The design idea of the whole three body game is through Scene switching. Players enter different plots by making choices, such as games like "memories of autumn". The core of the program is the design of Scene, and the code is as follows:
class Scene: """Basic scene class""" def __init__(self, name, description): self.name = name self.description = description self.paths = {} def enter(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): self.paths.update(paths)
Each Scene is used as an object to initialize the class Scene. When initializing, render the Scene name and plot description, and initialize the dictionary paths that determine the plot direction. Return the Scene object specified by the direction through the enter(direction) function and add_ The paths (paths) function is used to update the plot direction dictionary paths, so as to establish the plot relationship between different Scene objects. The sequence of the plot is shown in the figure below:
The plot of the game starts from the natural selection and ends at the space mausoleum. If each Scene in the middle is selected incorrectly, it will enter the death Scene (the death Scene needs to be subdivided according to different scenarios). In the death Scene, you can play the game again by selecting play again. The plot flows through add in Scene_ Paths implementation. The specific codes are 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. In case of invalid input, the plot scene will not be switched and will stay in the original scene. The rest of the work is to design different scene objects. The specific code is:
#Natural selection death scene death1 = """ Natural selection and trisomy civilization'Water drop'The probe was destroyed in the fierce battle...... """ death_1_1 = Scene("Game failure", f""" So you also received the ideological seal. Guard! Arrest Zhang Beihai now! {death1} """) death_1_2 = Scene("Game failure", f""" Zhang Beihai, you coward! Your heart is fully exposed. On the surface, you are a human victory theorist, The heart is indeed a failure theorist. Guard! Arrest Zhang Beihai now! {death1} """) death_1_3 = Scene("Game failure", f""" Are you Yun Tianming? Guard! Inform the earth fleet immediately! {death1} """) death_2 = Scene("Game failure", death1) death_3 = Scene("Game failure", f""" Ship control failed! {death1} """ ) death_4 = Scene("Game failure", f""" Dongfang YanXu: Zhang Beihai, I arrest you on behalf of starship earth. All personnel are ready to return to meet the trisomy detector. {death1} """) death_5 = Scene("Game failure", f""" After changing the route, it encountered the fleet of trisomy civilization and was destroyed... """) death_6 = Scene("Game failure", f""" Encountered the dark forest law and was attacked by infrasonic nuclear bombs of other warships in starship earth, All dead! """) #Natural selection number natureSelectionFleet = Scene("Natural selection number", """ Dongfang YanXu: Executive captain Zhang Beihai, this is Dongfang YanXu, the captain of the natural selection. Welcome. Now I'll give you the command of natural selection. The spacecraft has four forward modes, When entering forward 4 mode, the crew must enter the sleep cabin. Now, I need Once again, to confirm whether you are affected by the ideological seal, please answer my question: 'Will mankind win?' [1] Be sure to win [2] Losing [3] It depends on the three body civilization I see [4] Man's will is above all else """) #Escape from the solar system escape = Scene("Battleship natural selection control center", """ Dongfang YanXu: Captain Zhang Beihai, now I hand over control of the natural selection. According to the latest news from the earth Fleet: Three body civilization detector-Water drop-Has reached the edge of the solar system and will contact the earth fleet in 15 minutes. Now the spacecraft awaits your first command: [1] Forward 1 escape from the solar system [2] Forward 2 escape from the solar system [3] Forward 3 escape from the solar system [4] Forward 4 escape from the solar system """) #Flight control terminal control_terminal = Scene("Natural selection warship flight control terminal",""" Warning! Warning! Warning! When the spacecraft enters forward 4, all crew members must be informed to enter deep-sea sleep mode. Please enter the flight control password: [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 system extrasolar = Scene("Battleship natural selection",""" The spacecraft has flown out of the solar system, and behind it are blue space, deep space, ultimate law and enterprise. The next command is: [1] Continue human civilization, fly forward and far away [2] Turn around and destroy the pursuit warship [3] Hand over the command of the fleet to the captain of Dongfang continuation """ ) # Starship earth fleet_earth = Scene("Starship earth",""" The earth fleet has been destroyed by water droplets....... The five warships must continue the responsibility of civilization, and space will be our final destination. Starship earth decides: [1] Execute human traitor Zhang Beihai and go back to fight water drops [2] Zhang Beihai, the traitor who executed mankind, continued to fly to the constellation Cygnus 18 light-years away NH558J2 [3] Zhang Beihai is a hero and continues to fly to the constellation Cygnus 18 light-years away NH558J2 """ ) #Ultimate law number ultimate_rule_fleet = Scene("Ultimate law number",""" There was an uneasy atmosphere in the battleship ultimate law...... Fourteen light-years ago, the resources of the spacecraft are limited. How can we get supplies? Captain, what should we do? [1] Launch infrasonic hydrogen bombs on four other warships [2] Ask the other four warships for help and supplies [3] Ask the Starship earth to change its course and find the supply point [4] Go back to earth """ ) #Blue space number blue_space_fleet = Scene("Blue space number",""" Warning! Warning! Warning! The infrasonic hydrogen bomb shock wave of the ultimate law is about to arrive.... Defense successful, fleet damage 5%... Wait for the next command: [1] Launch high-energy gamma ray laser to destroy the ultimate law [2] flee """) #The last scene last_episode = Scene("Space Mausoleum",""" Blue space took away all the fuel and accessories, and transferred the natural selection, enterprise and deep space The debris was cut into several sections, surrounded the Stonehenge, and built a space mausoleum to commemorate the first experience of mankind universe'Dark forest'Terrible. Congratulations, you passed the plot! """ ) START = 'natureSelectionFleet' # Returns the scene object corresponding to the scene name def load_scene(name): return globals().get(name) # Returns the scene name corresponding to the scene object def name_scene(scene): for key, value in globals().items(): if value == scene: return key
7.3 write game Automatic test script of PY
Next, write game Py automatic test script. Create a new game in the tests \ directory_ tests. Py, the test tool is still nosetests. For game Initialization function and add of Scene in PY_ The paths and enter functions are tested. 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 introducing features, you need to start from Threebody \ game Py introduces all mentioned classes and global variables. The test results in PowerShell are:
7.4 writing HTML template
In the three body game, we use layout templates and POST forms. Create show in the templates \ directory_ room. HTML and layout HTML two files. The layout template code is:
<html> <head> <title>Three body game</title> </head> <body> {% block content %} {% endblock %} </body> </html>
It mainly contains the title "three body game". The POST form code is:
{% extends "layout.html" %} {% block content %} <h1>{{ room.name }}</h1> <pre> {{ room.description }} </pre> {% if room.name == "Game failure"%} <p><a href="/">Play Again?</a></p> {% elif room.name == "Space Mausoleum" %} <p><a href="/">Exit the game</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, first load the layout template, and then display the name of the scene object and the plot description on the web page. Then enable the if else conditional judgment statement. When the string named "game failed" is detected, the "play again?" will be displayed at the bottom of the plot description; When the string named "space mausoleum" is detected, the "exit the game" is displayed at the bottom of the plot description; Otherwise, a text box will be displayed, waiting for the user to enter information to promote the development of the plot.
7.5 create three body web game engine
The python file of the game engine should be created in the project home directory, that is, the first threebody directory. I created an app Py web engine file. It mainly refers to the flash, session, redirect and URL in the flash network framework_ for, request,render_template attribute. Of course, in order to run the game, you also need to introduce game py. The specific codes are 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 #Use the session to temporarily store the scene name return redirect(url_for("play")) @app.route("/play", methods=['POST', 'GET']) def play(): scene_name = session.get('scene_name') #Get the name of the current scene if request.method == 'GET': room = game.load_scene(scene_name) #Load the scene object by the name of the scene 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) #Gets the object of the next scene if not next_scene: next_scene = room.enter('*') #Save the name of the next scenario in a temporary session for use by the web server 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 home directory "/", and uses the session temporary session to store the scene name for the next call. Return the "/ play" directory. The second main function of the program is play() "There are two modes in the directory: post or GET. When the user input is not obtained, the default mode is GET. At this time, the engine loads the show_room.html file. After the user inputs valid information, the engine enters the post mode. At this time, the engine obtains the next plot scene according to the information, stores it in the session, and returns to the play directory to load the next scene. Finally, through app.run() Statement to automatically run the web game engine.
7.6 game operation effect
In the powe shell, run
python app.py
The result is:
At this time, the debug mode is turned off. If you want to turn it on, the app Change run() to app run(debug = True). When running on the local web page, enter localhost:5000 / on the browser according to the prompt. The effect is as follows:
epilogue
This is the first series of articles written by myself on CSDN. Although the content is nothing new, I insist on writing, make my ideas very clear, and know what I haven't mastered yet. Next, be quiet for a period of time, continue to study and stick to writing.