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):
    self.hp=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):
    attack_value=random.randint(0,10)
    return attack_value
def not_dead(self):
    if self.hp<=0:
        return False
    else:
        return True
def nowhp(self,attack_value):
    self.hp=self.hp-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 .

pleyer=Creature(100)
enemy=Creature(120)
 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():
     pleyer.show_stastic()
     enemy.show_stastic()
     choose=input('A or D')
     if choose=='A':
        pleyer.attack_value=pleyer.attack()
        enemy.attack_value=enemy.attack()
        pleyer.nowhp(pleyer.attack_value)
        enemy.nowhp(pleyer.attack_value)


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


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

Conclusion

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.
https://en.pythonmana.com/2022/02/202202011332545748.html

Random recommended