current position:Home>Python: simple single player strange game (text)

Python: simple single player strange game (text)

2022-02-01 13:32:57 Xu Hongda

The game is very simple , It is very suitable for newcomers like me to learn . We can learn about Python Classes and objects in the foundation . Steps are as follows .

1. Definition “ class ”

class Creature():# The first letter should be capitalized , The colon cannot be missing

2. initialization

Initialization class Creature, Add attributes to it , Here we add hp This attribute , You can also add more attributes , Add as needed .

def __init__(self,hp):
 Copy code 

3. Defined function

When writing a program, we will use the same piece of code repeatedly , By defining functions, we can greatly reduce the amount of code and our time . This defines the character's attack , Blood volume , A function of whether you're alive or not and how much blood you show .

def attack(self):
    return attack_value
def not_dead(self):
    if self.hp<=0:
        return False
        return True
def nowhp(self,attack_value):
def show_stastic(self):
    print('its hp is {}'.format(self.hp))
 Copy code 

4. Create instance object

A class definition is not an object , Just a blueprint . Now come to the real “ Build a house ”. ad locum , I create two objects “pleyer”,“enemy”, And gave them hp The value of this property . Class and object can be compared to class as a species , Like a dog , And the object is different kinds of dogs . We can change the properties of the object by modifying the class , Modifying a single object cannot change other objects .

 Copy code 

5. Realize the small game

Here , I defined that players can attack (A) And defense (D) Two options , The two options will cause different reactions .

while pleyer.not_dead() and enemy.not_dead():
     choose=input('A or D')
     if choose=='A':

     elif choose=='D':
        enemy.attack_value = enemy.attack()*0.1

if pleyer.not_dead():
     print('you win!')
    print('you lose!')
 Copy code 


For simplicity , Here I only set HP And attack defense , interested , I can go ahead and add MP And various skills , Make the game more interesting .

copyright notice
author[Xu Hongda],Please bring the original link to reprint, thank you.

Random recommended