這裏是你如何可以創建一個類Character
可能被用於在程序的任何文字的一實例。每個類應該表示一個唯一類型的對象,在這種情況下是一個「字符」。每個角色應該是該類的一個實例。然後用函數或類方法處理字符實例之間的交互。
class Character(object):
def __init__(self, name, attack, defense, health):
self.name = name
self.attack = attack
self.defense = defense
self.health = health
def injure(self, damage):
self.health = self.health - damage
def __str__(self):
return "Character: {}, A:{}, D:{}, H:{}".format(self.name, self.attack, self.defense, self.health)
def check(self):
print("this works")
def doAttack(self, other=None):
dmg = self.attack - other.defense
if dmg > 0:
other.injure(dmg)
print("{} caused {} damage to {}".format(self.name, dmg, other.name))
else:
print("{} did not injure {}".format(self.name, other.name))
hero = Character('Hero', 8, 10, 20)
opponent = Character('Monster', 4, 5, 10)
opponent.doAttack(hero)
print(hero)
print(opponent)
print()
hero.doAttack(opponent)
print(hero)
print(opponent)
print()
運行該代碼產生:
Monster did not injure Hero
Character: Hero, A:8, D:10, H:20
Character: Monster, A:4, D:5, H:10
Hero caused 3 damage to Monster
Character: Hero, A:8, D:10, H:20
Character: Monster, A:4, D:5, H:7
這是一個非常基本的例子。您可能需要閱讀Object Oriented Programming in Python(或類似的文本)以瞭解構造面向對象代碼的背後的概念。
'self = Character()'這個應該被移除 - 你不要在Python中這樣做。 – Julien
你的方法有很多問題。您正在重新定義一個類定義中的函數,並創建您未使用的變量('self = Character()'創建一個您從不訪問的類變量)。嘗試更改數據模型。你可以在程序中創建主角和對手作爲「角色」(不在課堂內)。然後有一個「戰鬥」功能,可以訪問主角和對手的屬性,並根據需要改變每個角色的健康狀況。 – Craig
@克雷格,我將如何創建我的對手?是我的代碼在正確的軌道上,除了self = Character() –