如何在另一个功能中使用功能?蟒蛇

时间:2014-03-23 06:43:30

标签: python oop

我正在尝试制作游戏而且我真的被卡住了。问题是我无法弄清楚如何正确使用面向对象的编程。该程序应启动游戏板功能 每当数字不等于arv时。它应该用一个" O"返回新的电路板。 以下。

from random import randint
import time

class Game():    
    def __init__(self):
        pass
    def beginning(self):
        print("How are you, and why are you playing my game?")
        bla = str(input())
        time.sleep(2)
        print("Hello," + bla + ", I am glad to see you!")
        time.sleep(2)
        print("Anyways, the you have to guess a number from 1-20")


    def gameboard(self):
        self.__board = ["O","O","O","O","O"]
        print(self.__board)
        self.__board.pop()
        return self.__board   

    def game(self):
        number = randint(1,20)
        print(number)
        x = 1
        arv = input()
        self.arv__ = arv
        while 5 > x:
            if arv == number:
                print("Lucky")
                break
            elif arv != number:
                print ("haha, try again")
                print("one life gone")
                return gameboard()
                print(self.board())
            x += 1

def Main():
    math = Game()
    math.beginning()
    math.game()


Main()

1 个答案:

答案 0 :(得分:0)

当您只需要一个对象实例时,使用面向对象的编程往往会使程序过于复杂。我建议只有一个主要功能。

尽管如此,我修复了你的程序。尝试自己找到这些变化,因为我太懒了解释它们,抱歉。

from random import randint
import time

class Game():    
    def __init__(self):
        pass

    def beginning(self):
        print("How are you, and why are you playing my game?")
        bla = str(input())
        time.sleep(2)
        print("Hello," + bla + ", I am glad to see you!")
        time.sleep(2)
        print("Anyways, the you have to guess a number from 1-20")
        self.__board = ["O","O","O","O","O"]


    def gameboard(self):
        print(self.__board)
        self.__board.pop()
        return self.__board   

    def game(self):
        number = randint(1,20)
        print(number)
        x = 1
        while 5 > x:
            arv = input()
            self.arv__ = arv
            if arv == number:
                print("Lucky")
                break
            elif arv != number:
                print ("haha, try again")
                print("one life gone")
                self.gameboard()
                print(self.__board)
            x += 1

def Main():
    math = Game()
    math.beginning()
    math.game()


Main()

这是您的程序版本,它避免使用OO并且更加简化:

from random import randint

lives = 5
print("Guess a number from 1 to 20")
number = randint(1, 20)
while (lives > 1 and number != int(input())):
    print("incorrect")
    print("lives: " + "O" * lives)
    lives -= 1

if lives == 0:
    print("The number was actually " + str(number))
else:
    print("You were right")