Table of Contents
Effect display
Essential materials
%%PRE_BLOCK_11%%
Home Backend Development Python Tutorial How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

Apr 27, 2023 pm 07:07 PM
python

Effect display

How to implement a high-end version of King of Games in Python

Essential materials

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

How to implement a high-end version of King of Games in Python

Main code

Import module

import pygame
import os.path
import csv
import setting as set
import live
import game_event
import gameui as gi
import startupui as si

Program main function

def run_game():
    #初始化pygame库
    pygame.init()
    #创建时钟对象(控制帧率)
    clock=pygame.time.Clock()
    #实例化设置类,用于导入游戏设置
    setting=set.Setting()
    #设置游戏窗口
    screen=pygame.display.set_mode((setting.screen_width,setting.screen_height))
    pygame.display.set_caption(setting.screen_caption)

Set different groups to handle various items respectively Relationship

#玩家组
group_player=pygame.sprite.Group()
#玩家的攻击组
group_attack=pygame.sprite.Group()
#敌人组
group_enemy=pygame.sprite.Group()
#敌人的攻击组
group_enemy_attack=pygame.sprite.Group()

Instantiated ui object

    #showinfo用于在游戏内显示人物血条等信息
    showinfo=gi.Info(setting,screen)
    #人物选择按钮
    yi_button=si.MonkeyKingButton(screen,setting)
    monkey_button=si.YiButton(screen,setting)
    fox_button=si.FoxButton(screen,setting)
    bin_button=si.BinButton(screen,setting)

Button of the game start interface

    pve_button=si.PVEButton(screen,setting)
    pvp_button=si.PVPButton(screen,setting)
    endless_button=si.EndlessButton(screen,setting)
    control_button=si.ControlButton(screen,setting)
    memory_button=si.RecordButton(screen,setting)
    cooling_button=si.CoolingButton(screen,setting)

Game background

    select_button=si.SelectButton(screen,setting)
    win_button=si.WinButton(screen,setting)
    dead_button=si.DeadButton(screen,setting)

The character mark currently selected by the player

    player_button_1=si.PlayerButton1(screen,setting)
    player_button_2=si.PlayerButton2(screen,setting)
    #空白按钮
    none_button=si.NoneButton(screen,setting)
    #空白图像
    none_info=gi.ExInfo(screen,none_button,setting.introduce_none)

Introducing the image of button function

    pve_info=gi.ExInfo(screen,pve_button,setting.introduce_pve)
    pvp_info=gi.ExInfo(screen,pvp_button,setting.introduce_pvp)
    endless_info=gi.ExInfo(screen,endless_button,setting.introduce_endless)
    control_info=gi.ExInfo(screen,control_button,setting.introduce_control)
    record_info=gi.ExInfo(screen,memory_button,setting.introduce_record)
    cooling_info=gi.ExInfo(screen,cooling_button,setting.introduce_cooling)

Button group (when drawing, the previous button will be covered by the following button)

    buttons=[select_button,yi_button,monkey_button,fox_button,bin_button,
             pve_button,pvp_button,endless_button,
             cooling_button,control_button,memory_button,
             dead_button,win_button]

Label button group

    choose_buttons=[player_button_1,player_button_2]

Introduction to the image group of button functions

    button_info_dict={none_button:none_info,pve_button:pve_info,pvp_button:pvp_info,
                      endless_button:endless_info,control_button:control_info,
                      memory_button:record_info,cooling_button:cooling_info}
    #当前显示的图像列表
    info_label=[]
    #存储模拟刚体运动的列表
    rigidbody_list=[]
    #玩家实例,初始化为战士
    player_1=live.MonkeyKing(setting,screen)
    player_2=live.MonkeyKing(setting,screen)

    if not os.path.exists(setting.record_path):
        #如果游戏记录文件不存在就新创建一个
        with open(setting.record_path,'w',newline="") as f:
            writer=csv.writer(f)
            header=["Time","Mode","Winner","1st Score","2st Score","Duration(s)","1st Player","2nd Player","isCooling"]
            writer.writerow(header)

Game main loop

    while True: 
        #绘制背景
        screen.blit(setting.screen_surface_background,(0,0))
        #设置游戏帧率
        clock.tick(setting.fps)
        #检测键盘鼠标事件   
        game_event.check_event(setting,screen,group_player,group_attack,group_enemy,
                               group_enemy_attack,buttons,showinfo,button_info_dict,info_label)

Update the label of the currently selected character

        game_event.update_choose(setting,buttons,choose_buttons)

Game running, non-player confrontation mode

        if (setting.game_active and (setting.game_mode==0 or setting.game_mode==2)):

Character initialization

            if(not setting.isinit):
                if setting.player_1!=None:
                    player_1=setting.player_1
                    group_player.add(player_1)
                if setting.player_2!=None:
                    player_2=setting.player_2
                    group_player.add(player_2)                
                setting.isinit=True
            #游戏计时器
            setting.timer+=1
            #更新玩家
            group_player.update()
            #生成敌人
            game_event.generate_enemies(setting,group_enemy,screen)

Update enemies, player attacks, enemy attacks, player status, etc.

game_event.update_enemies(setting,showinfo,screen,group_player,group_enemy,group_attack,group_enemy_attack)
            game_event.update_attacks(setting,screen,group_attack,group_enemy,rigidbody_list)
            game_event.update_enemy_attacks(setting,screen,group_player,group_enemy_attack,rigidbody_list)
            game_event.update_state(setting,showinfo)
            game_event.update_rigidbody(setting,rigidbody_list)

Victory conditions

            if setting.timer>=60*setting.fps and not group_enemy.spritedict and setting.game_mode==0:
                game_event.game_win(setting,showinfo,group_enemy,group_attack,group_enemy_attack)
                setting.timer=0

Failure conditions

            if setting.isinit and ((setting.player_1!=None and setting.health_1<=0) or (setting.player_2!=None and setting.health_2<=0)):              
                game_event.game_dead(setting,showinfo,group_enemy,group_attack,group_enemy_attack)
                setting.timer=0

Players Confrontation mode

        elif setting.game_active and setting.game_mode==1:

Character initialization

            if(not setting.isinit):
                if setting.player_1!=None and setting.player_2!=None:
                    player_1=setting.player_1
                    group_player.add(player_1)
                    player_2=setting.player_2
                    group_player.add(player_2)                        
                    setting.isinit=True

Game timer

setting.timer+=1

Update player

            player_1.update()
            player_2.update()

Update player's attack, information display and physical simulation

game_event.update_attacks_pvp(setting,screen,group_attack,rigidbody_list)
            game_event.update_state(setting,showinfo)
            game_event.update_rigidbody(setting,rigidbody_list)

Player 1 victory condition

            if setting.isinit and setting.health_2<=0:
                setting.score_1+=1
                game_event.game_win(setting,showinfo,group_enemy,group_attack,group_enemy_attack)
                setting.timer=0

Player 2 victory condition

            if setting.isinit and setting.health_1<=0:
                setting.score_2+=1
                game_event.game_win(setting,showinfo,group_enemy,group_attack,group_enemy_attack)
                setting.timer=0

Draw the entire game window based on the results of the above update

        game_event.update_screen(setting,screen,group_player,group_attack,group_enemy,group_enemy_attack,
                                 showinfo,buttons,info_label,choose_buttons)                 

#运行游戏
run_game()

The above is the detailed content of How to implement a high-end version of King of Games in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are class methods in Python What are class methods in Python Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

python asyncio queue example python asyncio queue example Aug 21, 2025 am 02:13 AM

asyncio.Queue is a queue tool for secure communication between asynchronous tasks. 1. The producer adds data through awaitqueue.put(item), and the consumer uses awaitqueue.get() to obtain data; 2. For each item you process, you need to call queue.task_done() to wait for queue.join() to complete all tasks; 3. Use None as the end signal to notify the consumer to stop; 4. When multiple consumers, multiple end signals need to be sent or all tasks have been processed before canceling the task; 5. The queue supports setting maxsize limit capacity, put and get operations automatically suspend and do not block the event loop, and the program finally passes Canc

How to run a Python script and see the output in a separate panel in Sublime Text? How to run a Python script and see the output in a separate panel in Sublime Text? Aug 17, 2025 am 06:06 AM

ToseePythonoutputinaseparatepanelinSublimeText,usethebuilt-inbuildsystembysavingyourfilewitha.pyextensionandpressingCtrl B(orCmd B).2.EnsurethecorrectbuildsystemisselectedbygoingtoTools→BuildSystem→Pythonandconfirming"Python"ischecked.3.Ifn

How to use regular expressions with the re module in Python? How to use regular expressions with the re module in Python? Aug 22, 2025 am 07:07 AM

Regular expressions are implemented in Python through the re module for searching, matching and manipulating strings. 1. Use re.search() to find the first match in the entire string, re.match() only matches at the beginning of the string; 2. Use brackets() to capture the matching subgroups, which can be named to improve readability; 3. re.findall() returns all non-overlapping matches, and re.finditer() returns the iterator of the matching object; 4. re.sub() replaces the matching text and supports dynamic function replacement; 5. Common patterns include \d, \w, \s, etc., you can use re.IGNORECASE, re.MULTILINE, re.DOTALL, re

How to build and run Python in Sublime Text? How to build and run Python in Sublime Text? Aug 22, 2025 pm 03:37 PM

EnsurePythonisinstalledbyrunningpython--versionorpython3--versionintheterminal;ifnotinstalled,downloadfrompython.organdaddtoPATH.2.InSublimeText,gotoTools>BuildSystem>NewBuildSystem,replacecontentwith{"cmd":["python","-

How to use variables and data types in Python How to use variables and data types in Python Aug 20, 2025 am 02:07 AM

VariablesinPythonarecreatedbyassigningavalueusingthe=operator,anddatatypessuchasint,float,str,bool,andNoneTypedefinethekindofdatabeingstored,withPythonbeingdynamicallytypedsotypecheckingoccursatruntimeusingtype(),andwhilevariablescanbereassignedtodif

How to pass command-line arguments to a script in Python How to pass command-line arguments to a script in Python Aug 20, 2025 pm 01:50 PM

Usesys.argvforsimpleargumentaccess,whereargumentsaremanuallyhandledandnoautomaticvalidationorhelpisprovided.2.Useargparseforrobustinterfaces,asitsupportsautomatichelp,typechecking,optionalarguments,anddefaultvalues.3.argparseisrecommendedforcomplexsc

How to debug a remote Python application in VSCode How to debug a remote Python application in VSCode Aug 30, 2025 am 06:17 AM

To debug a remote Python application, you need to use debugpy and configure port forwarding and path mapping: First, install debugpy on the remote machine and modify the code to listen to port 5678, forward the remote port to the local area through the SSH tunnel, then configure "AttachtoRemotePython" in VSCode's launch.json and correctly set the localRoot and remoteRoot path mappings. Finally, start the application and connect to the debugger to realize remote breakpoint debugging, variable checking and code stepping. The entire process depends on debugpy, secure port forwarding and precise path matching.

See all articles