[Pygame actual combat] programming and mini games are popular, and "eliminate viruses and defend the city" is launched. The mini games show great potential

Introduction

Hello, hello! I am mumuzi ~ today is another beautiful day!

Approaching the Spring Festival, many people who work in other places all year round are ready to go home for the new year. Although the epidemic has been controlled, everyone

All need the best protection

Ha! We should always start to prevent the epidemic! Correctly wear masks, wash hands and epidemic prevention~

Today, I still prepared a little game for you 👇:

Many people ask me, what game is the most popular now?

If it's on a cell phone? That may be nothing more than the two new year game lists "King xx" and "eating chicken"!

If you ask me again, what Python games are the most popular now? Recently, it must be "eliminate the virus"! You don't know much

Say, let's have a look

text

Rules of the game:

This game is a strategy game. You can buy props by setting the number of people in the city (determining the income):

Including medical staff (determining the number of patients to be admitted, one medical staff can treat 5 people), drug research and development (can improve the cure rate and reduce the mortality rate), and limiting

OK (it can reduce the range of personnel movement and reduce the generation of funds), national protection (it can prevent virus infection).

Every day, you can use the income to buy props and start protection. When all infected people have been cured or died, the game will win or fail.

Environmental preparation:

1) Material (pictures, music, etc.)

2) Operating environment

The running environment used in this paper: Python 3 7. Pycham community 2020, Pygame, numpy and tkinter modules can not be imported directly

Installation required. (if you need to install package software, activation code or encounter problems, you can send me a private letter!)

 Module installation: pip install -i https://pypi.douban.com/simple / + module name

Code demonstration:

There are too many codes, which is not easy to show. It is mainly divided into three pYS. Here is a simple display of the main program

Code it! Complete everyone directly to me, a lot of code is to show the comments, ha, do not understand can find me!

It's better to have some basic friends to come to me, otherwise I feel that novice friends have to start over. I can't speak clearly. Please forgive me

Solution, you need time to study and write articles. Maybe you don't have enough time! Answer questions occasionally!

More than 700 lines of main program code:

import pygame
import sys
import traceback
import os
from pygame.locals import *
import numpy as np
import linecache
from random import *
import people
import easygui as g
from tkinter import *

pygame.init()  # Game initialization
pygame.mixer.init()  # Sound initialization

bg_size = width, height = 1200, 700  # Screen size
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("Eliminate virus and defend the City Games")  # title
mycity = pygame.image.load("source/city.jpg").convert()
hospital_image = pygame.image.load("source/hospital.jpg").convert_alpha()
# massage_image = pygame.image.load("source / information area. PNG") convert_ alpha()


good_man_image = pygame.image.load("source/Healthy people.png").convert_alpha()
infect_man_image = pygame.image.load("source/Infected person.png").convert_alpha()
ill_man_image = pygame.image.load("source/Severe person.png").convert_alpha()
dead_man_image = pygame.image.load("source/Dead person.png").convert_alpha()
cure_man_image = pygame.image.load("source/Heal people.png").convert_alpha()

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
GRAY = (192, 192, 192)
ORANGE = (255, 165, 0)

# Game music
pygame.mixer.music.load("source/background music.mp3")
pygame.mixer.music.set_volume(0.2)
success_sound = pygame.mixer.Sound("source/correct.wav")
success_sound.set_volume(0.2)
lost_sound = pygame.mixer.Sound("source/fail.wav")
lost_sound.set_volume(0.2)
win_sound = pygame.mixer.Sound("source/victory.wav")
win_sound.set_volume(0.2)

def ShowBack():
    # Background picture
    # mycity = pygame.image.load("source / city. JPG") convert()
    # hospital_image = pygame.image.load("source / hospital. JPG") convert_ alpha()
    doctor_image = pygame.image.load("source/Medical support.png").convert_alpha()
    pill_image = pygame.image.load("source/Drug research.png").convert_alpha()
    limit_image = pygame.image.load("source/Restricted travel.png").convert_alpha()
    protect_image = pygame.image.load("source/National protection.png").convert_alpha()
    doctor_t_image = pygame.image.load("source/Medical support_t.png").convert_alpha()
    pill_t_image = pygame.image.load("source/Drug research_t.png").convert_alpha()
    limit_t_image = pygame.image.load("source/Restricted travel_t.png").convert_alpha()
    protect_t_image = pygame.image.load("source/National protection_t.png").convert_alpha()
    massage_image = pygame.image.load("source/Information area.png").convert_alpha()
    money_image = pygame.image.load("source/RMB.png").convert_alpha()
    # screen.blit(mycity, (500, 0))  # Load background picture
    # screen.blit(hospital_image, (100, 200))  # Load hospital pictures
    screen.blit(massage_image, (0, 0))  # Load information picture
    screen.blit(doctor_image, (300, 0))  # Load doctor picture
    screen.blit(doctor_image, (0, 200))  # Load doctor picture
    screen.blit(doctor_t_image, (0, 300))  # Load doctor text picture
    screen.blit(pill_image, (400, 0))  # Load drug picture
    screen.blit(pill_image, (0, 325))  # Load drug picture
    screen.blit(pill_t_image, (0, 425))  # Load drug picture
    screen.blit(limit_image, (300, 100))  # Load restricted travel picture
    screen.blit(limit_image, (0, 450))  # Load restricted travel picture
    screen.blit(limit_t_image, (0, 550))  # Load restricted travel picture
    screen.blit(protect_image, (400, 100))  # Load protected picture
    screen.blit(protect_image, (0, 575))  # Load protected picture
    screen.blit(protect_t_image, (0, 675))  # Load protected picture
    screen.blit(money_image, (300, 2))  # Load RMB picture
    screen.blit(money_image, (400, 2))  # Load RMB picture
    screen.blit(money_image, (300, 102))  # Load RMB picture
    screen.blit(money_image, (400, 102))  # Load RMB picture

# Number of initialized cities
def InitCity(group, myimage, num):
    for i in range(num):
        gm = people.City(myimage)
        screen.blit(gm.image, gm.rect)
        group.add(gm)

# Initialize hospital population
def InitHospital(group, myimage, num):
    for i in range(num):
        gm = people.Hospital(myimage)
        screen.blit(gm.image, gm.rect)
        group.add(gm)

# Hospitalization
def AddtoHospital(group, image):
    hm = people.Hospital(image)
    group.add(hm)
    screen.blit(hm.image, hm.rect)

# death
def AddtoDead(group, num):
    for i in range(num):
        dm = people.DeadErea()
        group.add(dm)
        screen.blit(dm.image, dm.rect)

# cure
def AddtoCure(group, num):
    for i in range(num):
        cm = people.CureErea()
        group.add(cm)
        screen.blit(cm.image, cm.rect)
# Write log file
def PutRecord(file, record):
    f = open(file, mode='w', encoding='utf-8')
    for i in range(len(record)):
        f.write(str(record[i]))
        f.write("\n")
    f.close()
# Read record
def GetRecord(file):
    record = []
    f = open(file, mode='r', encoding='utf-8')
    for each in f.readlines():
        record.append(int(each))
    f.close()
    # print(record)
    return record
# Empty group
def Clear(group):
    for each in group:
        group.remove(each)

# Main function
def main():
    pygame.mixer.music.play(-1)  # Play background music

    # Generate healthy group, infected group, severe group, cured group and dead group
    goodmans = pygame.sprite.Group()
    infectmans = pygame.sprite.Group()
    illmans = pygame.sprite.Group()
    curemans = pygame.sprite.Group()
    deadmans = pygame.sprite.Group()
    # Nosocomial infection and severe cases
    hos_infectmans = pygame.sprite.Group()
    hos_illmans = pygame.sprite.Group()

    clock = pygame.time.Clock()  # Clock
    delay = 100
    historyfile = "source/record.txt"  # Record file

    running = True  # Judge the running state
    active = False  # Start the game
    waited = False  # Wait
    tolnum = 0  # Total number
    goodnum = 0  # Initialize health population
    infectnum = 0  #  Number of initial infections
    city_infectnum = 0  # Number of people infected in initial cities
    hos_infectnum = 0 # Number of hospital infections initialized
    illnum = 0  # Number of critical patients initialized
    city_illnum = 0  # Number of critical cases in initialization City
    hos_illnum = 0  # Number of critical patients in initial hospital
    curenum = 0  # Number of people cured by initialization
    deadnum = 0  # Initialize deaths
    money = 0  # Initial money
    doc_price = 1000  # Medical price
    doc_num = 0  # Number of medical care
    doc_cure = 5  # Number of patients treated by each doctor
    pill_price = 2000  # Drug price
    pill_level = 0  # Drug grade
    limit_price = 3000  # Limit price
    limit_level = 0  # Limit level
    protect_price = 4000  # Protection price
    protect_num = 0  # National protection days
    mlen = 20  # Move step
    getmoney = 6  # Number of earnings per person per day
    speed = 50  # Game speed
    protect_status = False  # Protection status, no protection by default
    # goodtofm = [1, 2]  # Probability of mild infection
    # goodtoill = [1, 1]  # Severe infection probability
    fmtohos = [1, 50]  # Hospitalization probability of mild patients, 1 / 5
    fmtoill = [1, 100]  # Probability of mild patients turning to severe, 1 / 10
    fmtocure = [1, 20]  # Cure probability of mild disease, 1 / 10
    illtohos = [1, 5]  # Probability of severe hospitalization, 1 / 5
    illtodead = [1, 100]  # Severe to death, 1 / 5
    illtofm = [1, 20]  # Severe to mild, 1 / 5
    record = []

    day = 1  # Days
    time = 3  # Number of moves per day
    move = 0  # Move count

    myfont = pygame.font.Font("source/Regular script_GB2312.ttf", 20)  # Use italics
    myfont_big = pygame.font.Font("source/Regular script_GB2312.ttf", 36)  # Use large font
    myfont_small = pygame.font.Font("source/Regular script_GB2312.ttf", 12)  # Use small font
    # Flag whether to pause the game
    # paused = False
    # paused_image = pygame.image.load("source / pause. PNG") convert_ alpha()
    # resume_image = pygame.image.load("source / play. PNG") convert_ alpha()
    # paused_rect = paused_image.get_rect()
    # paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10
    # paused_show_image = paused_image

    # homepage
    mained = False  # Home page logo
    main_image = pygame.image.load("source/homepage.png").convert_alpha()
    main_rect = main_image.get_rect()
    main_rect.left, main_rect.top = width - main_rect.width - 10, 10

    # Main page
    start_image = pygame.image.load("source/Start the game.png").convert_alpha()
    start_rect = start_image.get_rect()
    start_rect.left, start_rect.top = (width - start_rect.width) // 2, 380
    gameover_image = pygame.image.load("source/End the game.png").convert_alpha()
    gameover_rect = gameover_image.get_rect()
    gameover_rect.left, gameover_rect.top = (width - gameover_rect.width) // 2, 500
    goon_image = pygame.image.load("source/Continue the game.png").convert_alpha()
    goon_rect = goon_image.get_rect()
    goon_rect.left, goon_rect.top = (width - goon_rect.width) // 2, 380
    restart_image = pygame.image.load("source/restart.png").convert_alpha()
    restart_rect = restart_image.get_rect()
    restart_rect.left, restart_rect.top = (width - restart_rect.width) // 2, 440
    tolnum_add_image = pygame.image.load("source/increase.png").convert_alpha()
    tolnum_add_rect = tolnum_add_image.get_rect()
    tolnum_add_rect.left, tolnum_add_rect.top = 710, 300
    tolnum_dec_image = pygame.image.load("source/reduce.png").convert_alpha()
    tolnum_dec_rect = tolnum_dec_image.get_rect()
    tolnum_dec_rect.left, tolnum_dec_rect.top = 735, 300

    protect_start_image = pygame.image.load("source/Start defending.png").convert_alpha()
    protect_start_rect = protect_start_image.get_rect()
    protect_start_rect.left, protect_start_rect.top = 180, 150
    doc_buy_image = pygame.image.load("source/purchase.png").convert_alpha()
    doc_buy_rect = doc_buy_image.get_rect()
    doc_buy_rect.left, doc_buy_rect.top = 310, 70
    pill_buy_image = pygame.image.load("source/purchase.png").convert_alpha()
    pill_buy_rect = pill_buy_image.get_rect()
    pill_buy_rect.left, pill_buy_rect.top = 410, 70
    limit_buy_image = pygame.image.load("source/purchase.png").convert_alpha()
    limit_buy_rect = limit_buy_image.get_rect()
    limit_buy_rect.left, limit_buy_rect.top = 310, 170
    protect_buy_image = pygame.image.load("source/purchase.png").convert_alpha()
    protect_buy_rect = protect_buy_image.get_rect()
    protect_buy_rect.left, protect_buy_rect.top = 410, 170
    tip_text = myfont.render("I'm sorry! You don't have enough money!!", True, RED)
    doc_dec_image = pygame.image.load("source/reduce.png").convert_alpha()
    doc_dec_rect = doc_dec_image.get_rect()
    doc_dec_rect.left, doc_dec_rect.top = 75, 205
    limit_dec_image = pygame.image.load("source/reduce.png").convert_alpha()
    limit_dec_rect = limit_dec_image.get_rect()
    limit_dec_rect.left, limit_dec_rect.top = 75, 455
    protect_dec_image = pygame.image.load("source/reduce.png").convert_alpha()
    protect_dec_rect = protect_dec_image.get_rect()
    protect_dec_rect.left, protect_dec_rect.top = 75, 580

    winflag = False  # Victory sign
    recorded = False  # Are there records
    lostflag = False  # Failure flag
    # Custom timing events
    COUNT = pygame.USEREVENT
    # Send custom events every 1 second
    pygame.time.set_timer(COUNT, 1000)
    goon = False  # Default new game
    # Timer, current duration
    counts = 0
    # Timing flag
    timer = False
    if os.path.exists(historyfile):  # If there are records
        recorded = True
        record = GetRecord(historyfile)
        day = record[0]
        tolnum = record[1]
        goodnum = record[2]  # Initialize health population
        city_infectnum = record[3]  # Number of people infected in initial cities
        hos_infectnum = record[4]  # Number of hospital infections initialized
        city_illnum = record[5]  # Number of critical cases in initialization City
        hos_illnum = record[6]  # Number of critical patients in initial hospital
        curenum = record[7]  # Number of people cured by initialization
        deadnum = record[8]  # Initialize deaths
        money = record[9]  # Initial money
        doc_num = record[10]  # Number of medical care
        pill_level = record[11]  # Drug grade
        limit_level = record[12]  # Limit level
        protect_num = record[13]  # National protection days
        infectnum = city_infectnum + hos_infectnum  # Number of initial infections
        illnum = city_illnum + hos_illnum  # Number of critical patients initialized
    else:  # When there is no record
        recorded = False
    ShowBack()  # Display background
    screen.blit(mycity, (500, 0))  # Load City picture
    screen.blit(hospital_image, (100, 200))  # Load hospital pictures
    # Initialize group
    InitCity(goodmans, good_man_image, goodnum)  # Initialize health population
    InitCity(infectmans, infect_man_image, city_infectnum)  # Initialize the number of people with mild infection in the city
    InitCity(illmans, ill_man_image, city_illnum)  # Number of people with severe infection in urban areas
    InitHospital(hos_infectmans, infect_man_image, hos_infectnum)  # Number of people with mild nosocomial infection
    InitHospital(hos_illmans, ill_man_image, hos_illnum)  # Number of patients with mild nosocomial infection
    AddtoCure(curemans, curenum)  # Initialize cured patients
    AddtoDead(deadmans, deadnum)  # Initialize dead patients
    if tolnum == 0:
        tolnum =500
    # Record file
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:  # sign out
                # Write log file
                record = [day, tolnum, goodnum, city_infectnum, hos_infectnum, city_illnum, hos_illnum,\
                    curenum, deadnum, money, doc_num, pill_level, limit_level, protect_num]
                # Ensure documentation is established
                with open(historyfile, mode='w', encoding='utf-8') as f:
                    f.close()
                PutRecord(historyfile, record)
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:  # Press the left mouse button
                # Press the home key
                if main_rect.collidepoint(event.pos):  # Home page
                    mained = True
                    active = False
                    waited = True
                    if mained:
                        pygame.mixer.music.pause()  # Background music pause
                        pygame.mixer.pause()  # Sound pause
                elif start_rect.collidepoint(event.pos) and not goon:  # Start the game
                    # print(goon)
                    active = True  # Start the game
                    winflag = False  # Reset
                    lostflag = False  # Reset
                    mained = False  # Reset
                    waited = False
                    paused = False
                    pygame.mixer.music.unpause()  # Background music cancel pause
                    pygame.mixer.unpause()  # Sound cancel pause
                    # Initialize game
                    day = 1
                    goodnum = tolnum - 1
                    city_infectnum = 1
                    InitCity(goodmans, good_man_image, goodnum)  # Initialize health population
                    InitCity(infectmans, infect_man_image, city_infectnum)  # Number of people with mild infection in the initial City
                    InitCity(illmans, ill_man_image, city_illnum)  # Number of people with severe infection in urban areas
                    InitHospital(hos_infectmans, infect_man_image, hos_infectnum)  # Number of patients with mild nosocomial infection
                    InitHospital(hos_illmans, ill_man_image, hos_illnum)  # Number of patients with mild nosocomial infection
                    AddtoCure(curemans, curenum)  # Initialize cured patients
                    AddtoDead(deadmans, deadnum)  # Initialize dead patients
                elif goon_rect.collidepoint(event.pos) and goon:  # Continue the game
                    active = True
                    waited = False
                    mained = False
                elif restart_rect.collidepoint(event.pos):  # restart
                    recorded = False
                    active = False
                    mained = False
                    # Reset
                    day = 0  # Days
                    tolnum = 500  # Total number
                    goodnum = 0  # Initialize health population
                    city_infectnum = 0  # Number of people infected in initial cities
                    hos_infectnum = 0  # Number of hospital infections initialized
                    city_illnum = 0  # Number of critical cases in initialization City
                    hos_illnum = 0  # Number of critical patients in initial hospital
                    curenum = 0  # Number of people cured by initialization
                    deadnum = 0  # Initialize deaths
                    money = 0  # Initial money
                    doc_num = 0  # Number of medical care
                    pill_level = 0  # Drug grade
                    limit_level = 0  # Limit level
                    protect_num = 0  # National protection days
                    Clear(goodmans)
                    Clear(infectmans)
                    Clear(illmans)
                    Clear(curemans)
                    Clear(deadmans)
                    Clear(hos_infectmans)
                    Clear(hos_illmans)
                elif gameover_rect.collidepoint(event.pos):  # End game
                    # Write log file
                    record = [day, tolnum, goodnum, city_infectnum, hos_infectnum, city_illnum, hos_illnum, \
                              curenum, deadnum, money, doc_num, pill_level, limit_level, protect_num]
                    # Ensure documentation is established
                    with open(historyfile, mode='w', encoding='utf-8') as f:
                        f.close()
                    PutRecord(historyfile, record)
                    pygame.quit()
                    sys.exit()
                # Start defending
                elif protect_start_rect.collidepoint(event.pos) and waited:
                    waited = False  # motion
                    move = 0  # Reset
                # Purchase medical care
                elif doc_buy_rect.collidepoint(event.pos) and waited:
                    if money >= doc_price:
                        doc_num += 1
                        money -= doc_price
                    else:
                        screen.blit(tip_text, (510, 10))
                    #     g.msgbox("sorry, you don't have enough money!")

                # Purchase drug research
                elif pill_buy_rect.collidepoint(event.pos) and waited:
                    if money >= pill_price:
                        pill_level += 1
                        money -= pill_price
                        illtodead[1] += int(illtodead[1] / 10)  # Mortality reduction
                        fmtoill[1] += int(fmtoill[1] / 10)  # Reduction of severe disease rate
                        if illtofm[0] < illtofm[1]:
                            illtofm[0] += int(fmtoill[1] / 10)  # Turn rash and improve
                        if fmtocure[0] < fmtocure[1]:
                            fmtocure[0] += int(fmtocure[1] / 10)  # Improved cure rate
                        # print(illtodead, fmtoill, illtofm, fmtocure)
                    else:
                        # g.msgbox("sorry, you don't have enough money!")
                        screen.blit(tip_text, (510, 10))
                # Purchase restricted investment
                elif limit_buy_rect.collidepoint(event.pos) and waited:
                    if money >= limit_price and getmoney > 0 and mlen > 0:
                        getmoney -= 1  # Lower income
                        limit_level += 1  # Limit level increased
                        mlen -= 5
                        money -= limit_price
                    else:
                    #     g.msgbox("sorry, you don't have enough money!")
                        screen.blit(tip_text, (510, 10))
                # Purchase protection
                elif protect_buy_rect.collidepoint(event.pos) and waited:
                    if money >= protect_price:
                        protect_num += 1
                        money -= protect_price
                        protect_status = True
                    else:
                    #     g.msgbox("sorry, you don't have enough money!")
                        screen.blit(tip_text, (510, 10))
                # Reduce care
                elif doc_dec_rect.collidepoint(event.pos) and waited:
                    if doc_num > 0:
                        doc_num -= 1
                        money += doc_price
                # Reduce restrictions
                elif limit_dec_rect.collidepoint(event.pos) and waited:
                    if limit_level > 0:
                        limit_level -= 1
                        mlen += 5
                        getmoney += 1
                # Reduce protection
                elif protect_dec_rect.collidepoint(event.pos) and waited:
                    if protect_num > 0:
                        protect_num -= 1
                        money += protect_price
                # Increase the total number of people
                elif tolnum_add_rect.collidepoint(event.pos):
                    if tolnum < 1000:
                        tolnum += 100
                # Reduce the total number of people
                elif tolnum_dec_rect.collidepoint(event.pos):
                    if tolnum > 0:
                        tolnum -= 100

        if not (delay % speed) and move < time and active and not waited:  # Move every 5 times
            screen.blit(mycity, (500, 0))  # Load City picture
            screen.blit(hospital_image, (100, 200))  # Load hospital pictures
            move += 1
            for gm in goodmans:  # Show healthy people
                gm.move(mlen)
                screen.blit(gm.image, gm.rect)
            for fm in infectmans:  # Show infected person
                fm.move(mlen)
                screen.blit(fm.image, fm.rect)
                # Is it infected with healthy people
                isinfect = pygame.sprite.spritecollide(fm, goodmans, False, pygame.sprite.collide_mask)
                if isinfect and not protect_status:  # and randint(0, goodtofm[1]) < goodtofm[0]:  # Infected and unprotected
                    for each in isinfect:
                        goodmans.remove(each)
                        each.image = infect_man_image
                        infectmans.add(each)
                        screen.blit(each.image, each.rect)
                # Is it severe
                if randint(0, fmtoill[1]) < fmtoill[0]:
                    infectmans.remove(fm)
                    fm.image = ill_man_image
                    illmans.add(fm)
                    screen.blit(fm.image, fm.rect)
                # Whether to enter the hospital, each medical care can treat 4 patients
                if randint(0, fmtohos[1]) < fmtohos[0] and (len(hos_infectmans) + len(hos_illmans) < doc_num * doc_cure):
                    infectmans.remove(fm)
                    AddtoHospital(hos_infectmans, infect_man_image)

            for im in illmans:  # Show critically ill people
                im.move(mlen)
                screen.blit(im.image, im.rect)
                # Is it infected with healthy people
                isinfect = pygame.sprite.spritecollide(im, goodmans, False, pygame.sprite.collide_mask)
                if isinfect and not protect_status:  # and randint(0, goodtoill[1]) < goodtoill[0]:  # Infected and unprotected
                    for each in isinfect:
                        goodmans.remove(each)
                        each.image = infect_man_image
                        infectmans.add(each)
                        screen.blit(each.image, each.rect)
                # Whether hospitalized, 4 patients per medical care
                if randint(0, illtohos[1]) < illtohos[0] and (len(hos_infectmans) + len(hos_illmans) < doc_num * doc_cure):
                    illmans.remove(im)
                    AddtoHospital(hos_illmans, ill_man_image)
                    continue
                # Death
                rate = randint(0, illtodead[1])
                if rate < illtodead[0]:
                    # print(rate, illtodead[0])
                    illmans.remove(im)
                    AddtoDead(deadmans, 1)

            for hfm in hos_infectmans:  # Hospital mild patients
                screen.blit(hfm.image, hfm.rect)
                # Is it cured
                if randint(0, fmtocure[1]) < fmtocure[0]:
                    hos_infectmans.remove(hfm)
                    AddtoCure(curemans, 1)
                    money += 100  # Cure one person and earn 100 yuan
                    continue
                # Is it serious
                if randint(0, fmtoill[1]) < fmtoill[0]:
                    hos_infectmans.remove(hfm)
                    hfm.image = ill_man_image
                    hos_illmans.add(hfm)
                    screen.blit(hfm.image, hfm.rect)

            for him in hos_illmans:  # Hospital critically ill patients
                screen.blit(him.image, him.rect)
                # Is it mild
                if randint(0, illtofm[1]) < illtofm[0]:
                    hos_illmans.remove(him)
                    him.image = infect_man_image
                    hos_infectmans.add(him)
                    screen.blit(him.image, him.rect)
                    continue
                # Death
                rate = randint(0, illtodead[1])
                if rate < illtodead[0]:
                    # print(rate)
                    hos_illmans.remove(him)
                    AddtoDead(deadmans, 1)

            for cm in curemans:  # Cure patients
                screen.blit(cm.image, cm.rect)

            for dm in deadmans:  # Dead patient
                screen.blit(dm.image, dm.rect)

        elif move == time:
            success_sound.play()
            move = 0  # Re count
            day += 1  # Add one day
            waited = True
            # Non hospitalized personnel earn 5 yuan per person per day
            money += (len(goodmans) + len(infectmans) + len(illmans)) * getmoney
            if protect_num > 0:
                protect_num -= 1
                protect_status = True
            else:
                protect_status = False
            if (infectnum + illnum) == 0 and goodnum > 0:
                win_sound.play()
                active = False
                mained = True
                winflag = True
            elif (infectnum + illnum) == 0 and goodnum == 0:
                lostflag = True

        # Show score
        # screen.blit(massage_image, (0, 0))  # Load information picture
        ShowBack()  # Display background
        goodnum = len(goodmans)  # Number of healthy people
        infectnum = len(infectmans) + len(hos_infectmans)  # patient with mild symptoms
        illnum = len(illmans) + len(hos_illmans)  # patient in severe condition
        curenum = len(curemans)  # Number of cured
        deadnum = len(deadmans)  # death toll
        day_text = myfont_big.render(f"{str(day)}", True, RED)
        screen.blit(day_text, (75, 10))
        tolnum_text = myfont.render(f"{str(tolnum)}", True, BLACK)
        screen.blit(tolnum_text, (65, 60))
        goodnum_text = myfont.render(f"{str(goodnum)}", True, BLACK)
        screen.blit(goodnum_text, (75, 83))
        infectnum_text = myfont.render(f"{str(infectnum)}", True, BLACK)
        screen.blit(infectnum_text, (75, 106))
        illnum_text = myfont.render(f"{str(illnum)}", True, BLACK)
        screen.blit(illnum_text, (75, 129))
        curenum_text = myfont.render(f"{str(curenum)}", True, BLACK)
        screen.blit(curenum_text, (75, 152))
        deadnum_text = myfont.render(f"{str(deadnum)}", True, BLACK)
        screen.blit(deadnum_text, (75, 175))
        money_text = myfont.render(f"{str(money)}", True, RED)
        screen.blit(money_text, (210, 18))
        screen.blit(protect_start_image, protect_start_rect)  # Start button
        # Show prop price
        doc_price_text = myfont.render(f"{str(doc_price)}", True, ORANGE)
        screen.blit(doc_price_text, (320, 3))
        pill_price_text = myfont.render(f"{str(pill_price)}", True, ORANGE)
        screen.blit(pill_price_text, (420, 3))
        limit_price_text = myfont.render(f"{str(limit_price)}", True, ORANGE)
        screen.blit(limit_price_text, (320, 103))
        protect_price_text = myfont.render(f"{str(protect_price)}", True, ORANGE)
        screen.blit(protect_price_text, (420, 103))
        # Show purchase
        screen.blit(doc_buy_image, doc_buy_rect)
        screen.blit(pill_buy_image, pill_buy_rect)
        screen.blit(limit_buy_image, limit_buy_rect)
        screen.blit(protect_buy_image, protect_buy_rect)
        # Displays the number of props
        doc_num_text = myfont.render(f"{str(doc_num)}", True, RED)
        screen.blit(doc_num_text, (5, 205))
        pill_level_text = myfont.render(f"{str(pill_level)}", True, RED)
        screen.blit(pill_level_text, (5, 330))
        limit_level_text = myfont.render(f"{str(limit_level)}", True, RED)
        screen.blit(limit_level_text, (5, 455))
        protect_num_text = myfont.render(f"{str(protect_num)}", True, RED)
        screen.blit(protect_num_text, (5, 580))
        screen.blit(doc_dec_image, doc_dec_rect)
        screen.blit(limit_dec_image, limit_dec_rect)
        screen.blit(protect_dec_image, protect_dec_rect)
        if waited:
            wait_text = myfont.render("Please deploy your protection!", True, RED)
            screen.blit(wait_text, (140, 85))

        # Pause / play
        # screen.blit(paused_show_image, paused_rect)  # Pause picture
        # homepage
        screen.blit(main_image, main_rect)  # Home page picture

        if not active:  # At start-up
            # homepage
            pygame.draw.rect(screen, GRAY, (400, 100, 400, 500), 0)  # Draw a rectangle, position 400100, length 400, height 500
            # Displays the fastest record and the current record
            tolnum_record_text = myfont.render(f"Your urban population is:{tolnum} people", True, RED)
            day_record_text = myfont.render(f"You have guarded:{day} day", True, RED)
            goodnum_record_text = myfont.render(f"The number of healthy people is:{goodnum} people", True, RED)
            infectnum_record_text = myfont.render(f"Mild patients include:{infectnum} people", True, RED)
            illnum_record_text = myfont.render(f"Severe patients include:{illnum} people", True, RED)
            curenum_record_text = myfont.render(f"The number of cured persons is:{curenum} people", True, RED)
            deadnum_record_text = myfont.render(f"Number of deaths:{deadnum} people", True, RED)
            record_text = myfont.render("", True, RED)
            if not recorded and not mained:  # No record, initial entry
                goon = False
                wel_text = myfont_big.render("Welcome to the game of defending the city!", True, RED)
                screen.blit(wel_text, (410, 200))
                screen.blit(tolnum_record_text, (480, 300))
                # Increase and decrease
                screen.blit(tolnum_add_image, tolnum_add_rect)
                screen.blit(tolnum_dec_image, tolnum_dec_rect)
                # Start the game
                screen.blit(start_image, start_rect)
            elif recorded and not mained:  # Read record
                goon = True
                record_text = myfont.render("Your last game progress was:", True, RED)
                screen.blit(record_text, (480, 140))
                screen.blit(tolnum_record_text, (480, 170))
                screen.blit(day_record_text, (480, 200))
                screen.blit(goodnum_record_text, (480, 230))
                screen.blit(infectnum_record_text, (480, 260))
                screen.blit(illnum_record_text, (480, 290))
                screen.blit(curenum_record_text, (480, 320))
                screen.blit(deadnum_record_text, (480, 350))
                # Continue the game
                screen.blit(goon_image, goon_rect)
                # restart
                screen.blit(restart_image, restart_rect)
            elif mained:
                if not winflag and not lostflag:  # Click home
                    record_text = myfont.render("Your current game progress is:", True, RED)
                    # Continue the game
                    screen.blit(goon_image, goon_rect)
                elif winflag:  # victory
                    record_text = myfont.render("congratulations! Destroy all viruses!!", True, RED)
                elif lostflag:  # fail
                    record_text = myfont.render("unfortunately! Failed to eliminate the virus!!", True, RED)
                goon = True
                screen.blit(record_text, (480, 140))
                screen.blit(tolnum_record_text, (480, 170))
                screen.blit(day_record_text, (480, 200))
                screen.blit(goodnum_record_text, (480, 230))
                screen.blit(infectnum_record_text, (480, 260))
                screen.blit(illnum_record_text, (480, 290))
                screen.blit(curenum_record_text, (480, 320))
                screen.blit(deadnum_record_text, (480, 350))
                # restart
                screen.blit(restart_image, restart_rect)

            # End the game
            screen.blit(gameover_image, gameover_rect)

        # time interval
        delay -= 1
        if not delay:
            delay = 50
        pygame.display.flip()  # page refresh 

        clock.tick(60)


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        pass
    except:
        traceback.print_exc()
        pygame.quit()
        input()

Effect display:

1) Game interface

2) Start the game

Buying corresponding items, such as medical staff and drugs, will reduce money accordingly. The number of infections on the right will then be displayed on the map

above. The figure of the hospital shows the number of cured people, treatment area, dead people and so on.

Every day, I will arrange new deployment and choose what to buy. Ha ~ this is the third day. I bought a doctor and treatment drugs!

3) this is a screenshot of my random play

summary

The interface of this little game "eliminate virus and defend the city" is still very good, and the effect is also very clear. You can try it yourself

Try! See how long you can hold on?!

🎯 Complete free source code collection: find me!

Didi, I can acridine!

🎉 Recommended reading in previous periods——

Item 6.0 Chinese chess game 👍

Pygame actual combat: Chinese chess man-machine confrontation starts today. Who has the upper hand? Would you like to try one?

Item 5.3 squid game - 123 wooden man

When "squid game" came: "one, two, three, wooden man, Smecta." Are you still scared?

Item 4.9 everyday cool running games

Is cool running every day really out of fire? Python releases the "cool run +" program.

Item 1.1 mine clearance

Pygame actual combat: it is said that this is the most difficult minesweeping game in history. There is no one. Feel it

🎄 Article summary——

Item 1.0 Python-2021 | summary of existing articles | continuously updated. It's enough to read this article directly

(more content + source code are summarized in the article!! welcome to read ~)

Keywords: Python Game Development source code pygame

Added by dotwebbie on Thu, 20 Jan 2022 18:48:36 +0200