我觉得这是一个非常简单的概念,但是我似乎无法绕过类并从中返回值……这是我想尝试和实践的,很多WIP,但是我我被困在这里。 预先感谢
import random
global d6
print("welcome to fight night")
#dice roll
class die():
def __init__(self, sides):
self.sides = sides
def roll(self):
chance = random.randint(1,self.sides)
if chance == 3:
return True
if chance != 3:
return False
d6 = die(6)
class Player():
def __init__(self, name, weight, spec):
self.name = name
self.weight = weight
self.spec = spec
fighter1 = Player("BRUCE LEE", 150, "SUPER SPEED")
fighter2 = Player(GEORGE FORMAN", 225, "REACH")
## how do i return true or false here to check hit?
print(fighter1(name) + "attacks"+ fighter2(name))
d6.roll()
if d6 == True:
print(fighter(name) + "hit" + fighter2(name))
if d6 == False:
print("attack missed")
答案 0 :(得分:1)
关于类约定的几件事:
()
使用继承。代码:
class Die:
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides
def roll(self):
"""
Returns True if the roll succeeds, returns False otherwise.
There is a (1 / self.number_of_sides) chance the roll will succeed.
"""
from random import choice
return choice([True] + [False] * (self.number_of_sides-1))
die = Die(6)
if die.roll():
print("Nice!")
else:
print("Sorry, try again.")
编辑,我认为您需要一个更基本的示例来说明return
关键字的工作原理:
def give_me_a_number():
return 5 + 4
x = give_me_a_number()
print(x)
输出:
9
答案 1 :(得分:0)
d6.roll()
返回一个值(是True
或False
)-d6
不会成为该值,它将返回到您。当您在实数d6上滚动3时,骰子本身并不会完全转化为一团烟雾和数学特效中的3,它只是向您展示它的一个面。 :)
所以您可以这样做:
if d6.roll():
print(fighter1.name + " hit " fighter2.name)
else:
print("attack missed")
或者,如果您想更详细些:
die_result = d6.roll()
if die_result is True:
print(fighter1.name + " hit " fighter2.name)
if die_result is False:
print("attack missed")
答案 2 :(得分:0)
我将重组您的模具类,使其仅返回滚动结果的随机值。通常,您希望对象(类的实例)是独立的-模具对象的用户应确定对象使用该对象生成的随机值而不是模具本身来完成操作。
例如,假设我们有许多实力各异的球员。强者攻击弱者的几率与弱者攻击强者的几率不同。此数据(强或弱)应位于播放器对象内,而不是骰子对象内。因此,我将为播放器提供另外两种方法,以及一个诸如“强度”之类的属性,该属性将获得一个int值...
import random
class Die:
def __init__(self, sides):
self.sides = sides
def roll(self):
chance = random.randint(1,self.sides)
return chance
class Player:
def __init__(self, name, weight, spec):
self.name = name
self.weight = weight
self.spec = spec
def get_stats(self):
return self.spec
def attack(self, target):
odds = self.spec / (self.spec + target.get_stats())
#print(odds)
d6 = Die(6);
temp = d6.roll()
#print(temp)
if (d6.roll() / 6 < odds):
return ("hit")
else:
return ("miss")
if __name__ == "__main__":
print("welcome to fight night")
fighter1 = Player("BRUCE LEE", 150, 100)
fighter2 = Player("GEORGE FORMAN", 225, 100)
for x in range(20):
result = fighter1.attack(fighter2)
print(result)
因此,现在Player对象可以自己控制赔率,而不是骰子对象,从而使一切变得更加灵活。 (顺便说一句,在函数内部使Die成为局部对象会增加一些开销,但是全局对象/变量有很多问题,可能最好避免)