python - 为什么这不会输出 diceroll2 函数?
问题描述
我正在为我的计算机科学 GCSE 制作一个回合制骰子游戏,但无法理解为什么我的程序的某个部分不会运行,或者至少不会输出。
class player1:
def __init__(self):
self.rolls = 5
class player2:
def __init__(self):
self.rolls = 5
def dicerollp1():
print("foo")
def dicerollp2():
print("2foo")
while player1.rolls > 0 and player2.rolls > 0:
dicerollp1()
player1.rolls += -1
if player1.rolls > player2.rolls:
dicerollp2()
player2.rolls += -1
不应该输出 2foo 而不是什么都不输出吗?
解决方案
- 您正在尝试使用类名来调用类实例方法
player1.rolls()
,而不是那样,您应该做的是使用类的对象来做到这一点。
p1 = player1()
p1.rolls()
- 一个类
player
对于您的代码就足够了,您不需要两个相同的类,并在其上调用两个实例(感谢@khelwood) dicerollp1
并且dicerollp2
可以在类中移动,也许通过添加一个附加属性player_number
- 您也许可以更改
player1.rolls += -1
为player1.rolls -= 1
所以重构的代码看起来像
#One player class
class player:
#Player number as attribute to diceroll
def __init__(self, player_number):
self.rolls = 5
self.player_number = player_number
#One diceroll function
def diceroll(self):
print("foo{}".format(self.player_number))
#Instantiate object of class player
p1 = player(1)
p2 = player(2)
#Use them in the logic
while p1.rolls > 0 and p2.rolls > 0:
#Refer to p1's diceroll
p1.diceroll()
p1.rolls += -1
if p1.rolls > p2.rolls:
# Refer to p2's diceroll
p2.diceroll()
p2.rolls += -1
同样在你的 while 循环之后,p1.rolls=0
and p2.rolls=5
,因此p1.rolls > p2.rolls
将是 false 并且 if 不会被执行,因此输出将是
foo1
foo1
foo1
foo1
foo1
推荐阅读
- java - 具有可选返回类型的 JavaBean 内省
- swift - 尝试使用 swift 获取天气数据 - JSON OpenWeatherMap api
- azure - 迭代不存在的 Azure 资源管理器 (ARM) 对象属性?
- asp.net-core-2.0 - AspNetCore 防伪和提琴手
- node.js - 使用 Nodejs 的 Firebase 内存泄漏
- c# - 如何获得下一个点位置?
- ios - 了解卷积核的输出图像范围
- c++ - 如何修复“对非常量的初始引用值必须是左值?”
- php - 在存储文件夹中显示多个名称未知的文件 Laravel
- css - Bootstrap 填充剩余高度