学习面向对象之后,练习使用面向对象思想,实现代码
⼈狗⼤站,2个⻆⾊,⼈和狗,游戏开始后,⽣成2个⼈,3条狗,互相混战,⼈被狗咬了会掉⾎,狗被⼈打了也掉⾎,狗和⼈的攻击⼒,具备的 功能都不⼀样。 类:⼈ 属性:⼈:攻击⼒(打)、⽣命值(⾎) ⽅法:打 类:狗; 属性:攻击⼒(咬)、⽣命值(⾎) ⽅法:咬
# -*- coding: utf-8 -*-
# @File : 面向对象小游戏.py
# 描述 : 人狗大战
# @Time : 2020/6/3 16:27
# @Author : 崔
# @versions : 1.0
from random import randint
class Person:
def __init__(self, name, aggressivity, hp): # 姓名 攻击力 生命值
self.name = name
self.aggressivity = aggressivity
self.hp = hp
def attack(self, dog):
atk = randint(0, self.aggressivity)
if dog.hp > atk:
dog.hp -= atk
print(f"{self.name}打了{dog.name}一下")
else:
dog.hp -= atk
print(f"{dog.name}死翘翘了")
class Dog:
def __init__(self, name, aggressivity, hp):
self.name = name
self.aggressivity = aggressivity
self.hp = hp
def attack(self, person):
atk = randint(0, self.aggressivity) # 随机的攻击力
if person.hp > atk:
person.hp -= atk
print(f"{self.name}咬了{person.name}一下")
else:
person.hp -= atk
print(f"{person.name}被咬死了")
person = [Person("张三", 9, 100), Person("李四", 9, 100), Person("王二", 9, 100)]
dogs = [Dog("豆豆", 20, 60), Dog("贝贝", 20, 90)]
while len(person) > 0 and len(dogs) > 0:
person[randint(0, len(person) - 1)].attack(dogs[randint(0, len(dogs) - 1)])
for i in range(len(dogs) - 1, -1, -1):
if dogs[i].hp <= 0:
dogs.pop(i) # 将已死的狗从列表中删除
if len(dogs) <= 0:
break
dogs[randint(0, len(dogs) - 1)].attack(person[randint(0, len(person) - 1)])
for i in range(len(person) - 1, -1, -1):
if person[i].hp <= 0:
person.pop(i) # 将已死的人从列表中删除
if len(person) > 0:
print("人获得了胜利")
else:
print("狗获得了胜利")
使用了随机攻击的方式,因此运行结果不一定相同