【问题标题】:Python memory matching game loop/logic issuePython内存匹配游戏循环/逻辑问题
【发布时间】:2018-03-18 20:27:04
【问题描述】:

我正在制作一个基本的记忆匹配游戏。这个想法是,通过用户输入,可以用卡片创建一个板。这些卡都在棋盘上的某个地方匹配。基本上输入是板的尺寸,然后是坐标以识别可能的匹配。但是,每次我输入输入时,即使代码有效,代码似乎也会遵循无效输入。但是,当我输入两个相同的坐标时,我的代码部分将针对这种情况执行。我不确定这里发生了什么。

import random
class Card():
    """Card object """
    def __init__(self, val):
        self.val = val 
        self.face = False

    def isFaceUp(self):
        """check to see if the cards face up"""
        return self.face

    def getVal(self):
        return self.val

    def makeFaceUp(self):
        self.face = True

    def __str__(self):
        return ", ".join(("Value: ", str(self.val), "Face: ", str(self.face)))

class Deck():
    def __init__(self, pairs):
        self._pairs = pairs
        self._cards = []
        for cards in range(self._pairs):
            card1 = Card(cards + 1)
            self._cards.append(card1)
            card2 = Card(cards+1)
            self._cards.append(card2)

    def deal(self):
        if len(self) ==0:
            return None
        else:
            return self._cards.pop(0)

    def shuffle(self):
        random.shuffle(self._cards)

    def __len__(self):
        return len(self._cards)

class Game():
    def __init__(self, rows, columns):
        self._deck = Deck((rows*columns)//2)
        self._rows = rows 
        self._columns = columns
        self._board = []
        for row in range(self._rows):
            self._board.append([0] * self._columns)
        self.populateBoard()

    def populateBoard(self):
        """Puts all cards in the board random"""
        self._deck.shuffle()

        for columns in range(self._columns):
            for rows in range(self._rows):
                self._board[rows][columns] = self._deck.deal()

    def revealBoard(self):
        """checks the values on the board making sure theres pairs"""
        for rows in range(self._rows):
            for columns in range(self._columns):
                print(str(self._board[rows][columns].getVal()) + \
                      " ", end="")
                print("")

    def displayGame(self):
        """Displays the game in a 2d list"""
        for rows in range(self._rows):
            for columns in range(self._columns):
                if self._board[rows][columns].isFaceUp() == False:
                    print("*", end = "")
                else:
                    print(str(self._board[rows][columns].getVal() + \
                              " ", end = ""))
                    print("")

    def play(self):
        """Allows the game to play setting the cards into a double list """
        while not self.isGameOver():
            self.displayGame()
            c1 = input("Enter coordinates, (row, column) of card: ")
            c2 = input("Enter the coordinates of match: ")
            newC1 = list(map(int, c1.split()))
            newCard1 = self._board[(newC1[0])-1][(newC1[1])-1] #Get value here??? 
            newC2 = list(map(int, c2.split()))
            newCard2 = self._board[(newC2[0])-1][(newC2[1])-1]

            try:
                if newCard1 != newCard2:
                    print("Not a pair", "Found: ",newCard1, "at", "(" + newC1, ", ", newC2, ")")
                elif newC1 == newC2:
                    print("Identical Coordinate Entery")
                elif newCard1.getVal() == newCard2.getVal():
                    self._board[newC1[0]-1][newC1[1]-1].makeFaceUp()
                    self._board[newC2[0]-1][newC2[1]-1].makeFaceUp()
                    print("pair found")
            except:
                print("invalid input")

        print("Game Over")
        self.displayGame

    def isGameOver(self):
        """Test to determine if all the cards are facing up and revelied the game will be over"""
        for rows in range(self._rows):
            if not all(card.isFaceUp() for card in self._board[rows]):
                return False
        return True

def main():
    while True:
        # Force user to enter valid value for number of rows
        while True:
            rows = input("Enter number of rows ")
            if rows.isdigit() and ( 1 <= int(rows) <= 9):
                rows = int(rows)
                break
            else:
                print ("    ***Number of rows must be between 1 and 9! Try again.***")
                # Adding *** and indenting error message makes it easier for the user to see

        # Force user to enter valid value for number of columns
        while True:
            columns = input("Enter number of columns ")
            if columns.isdigit() and ( 1 <= int(columns) <= 9):
                columns = int(columns)
                break
            else:
                print ("    ***Number of columns must be between 1 and 9! Try again.***")

        if rows * columns % 2 == 0:
            break
        else:
            print ("    ***The value of rows X columns must be even. Try again.***")

    game = Game(rows, columns)
    game.play()

if __name__ == "__main__":
    main()

感谢任何帮助,如果有人需要查看我的代码的其他部分,只需询问我很乐意将它们放在那里,如果它有助于发现此错误。

编辑:继续添加整个代码进行测试。

【问题讨论】:

  • 嗯,请发布整个代码,以便我们重现它以及 2 个测试用例:一个返回预期行为,一个不返回。
  • @LeviLesches 完成!
  • 好的,正在处理中...
  • @LeviLesches 如果尚未分配任何内容,如何在 newC1 的分配中调用 newC1?

标签: python arrays class logic subclass


【解决方案1】:

好的,所以据我推断,错误是您在Game.play() 中的非常广泛的错误处理。它检查 any 错误,但是当您删除该语句时,您会看到您正在尝试将列表添加到字符串中。要解决这个问题,请添加:

newC1 = "(" + ", ".join (list (map (str, newC1))) + ")"

对 newC2 执行相同的操作。这只是将列表更改为看起来像坐标的字符串。

【讨论】:

  • 如果 newC1 尚未分配任何内容,如何在 newC1 的分配中调用它? @LeviLesches
  • 不要用此行替换分配,在分配后添加此行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多