Tôi phải thực hiện sửa đổi nào để nó không in gì? (dùng danh sách liên kết)

lập trình


# Snake_ladder game using doubly linked list

class Empty(Exception):
    """ Error attempting to access an element from an empty container."""
    pass


class DoublyLinkedBase:
    """Queue implementation using circularly linked list for storage."""

    # -------------------------- nested Node class --------------------------
    class _Node:
        """ Lightweight, nonpublic class for storing a doubly linked node. """
        __slots__ = '_element', '_prev', '_next'  # streamline memory usage

        def __init__(self, element, prev, next):  # initialize node’s fields
            self._element = element  # reference to user’s element
            self._prev = prev  # previous node reference
            self._next = next  # next node reference

    # ------------------------------- methods -------------------------------

    def __init__(self):
        """ Create an empty list."""
        self._header = self._Node(None, None, None)
        self._trailer = self._Node(None, None, None)
        self._header._next = self._trailer  # trailer is after header
        self._trailer._prev = self._header  # header is before trailer
        self._size = 0  # number of elements

    def __len__(self):
        """Return the number of elements in the list."""
        return self._size

    def is_empty(self):
        """Return True if list is empty."""
        return self._size == 0

    def insert_between(self, e, predecessor, successor):
        """Add element e between two existing nodes and return new node."""
        newest = self._Node(e, predecessor, successor)  # linked to neighbors
        predecessor._next = newest
        successor._prev = newest
        self._size += 1
        return newest

    def delete_node(self, node):
        """ Delete nonsentinel node from the list and return its element."""
        predecessor = node._prev
        successor = node._next
        predecessor._next = successor
        successor._prev = predecessor
        self._size -= 1
        element = node._element  # record deleted element
        node._prev = node._next = node._element = None  # deprecate node
        return element  # return deleted element

    def display_board(self):
        current = self._header._next
        while current != self._trailer:
            print(current._element, end=" ")
            current = current._next
        print()

    def dice_roll_sequance(self, case):  # not a random sequance
        if case == 1:
            self._dice_seq = [1, 5, 3]  # 84
            self.move_()
            print("case %d, ans = 84" % case)
        if case == 2:
            self._dice_seq = [4, 3, 6, 1]  # 38
            self.move_()
            print("case %d, ans = 38" % case)
        if case == 3:
            self._dice_seq = [5, 2, 6, 6, 3, 6, 5, 5]  # 100 win
            self.move_()
            print("case %d, ans = 100 win" % case)
        if case == 4:
            self._dice_seq = [5, 2, 6, 6, 3, 6, 5, 1]  # 61
            self.move_()
            print("case %d, ans = 61 " % case)
        if case == 5:
            self._dice_seq = [5, 2, 6, 6, 3, 6, 5, 6]  # 95
            self.move_()
            print("case %d, ans = 95" % case)
        if case == 6:
            self._dice_seq = [1]  # 38
            self.move_()
            print("case %d, ans = 38" % case)
        if case == 7:
            self._dice_seq = [6, 1, 2]  # 5
            self.move_()
            print("case %d, ans = 5" % case)
        if case == 8:
            self._dice_seq = [6, 1, 2, 3]  # 31
            self.move_()
            print("case %d, ans = 31" % case)
        if case == 9:
            self._dice_seq = [1, 6, 6, 1, 6, 2]  # 99
            self.move_()
            print("case %d, ans =99" % case)

    def inistialize_board(self):
        for i in range(1, 101):

            if i == 2:
                self.insert_last(i, 36)
            elif i == 8:
                self.insert_last(i, 23)
            elif i == 17:
                self.insert_last(i, 6)
            elif i == 21:
                self.insert_last(i, 21)
            elif i == 33:
                self.insert_last(i, -28)
            elif i == 46:
                self.insert_last(i, 38)
            elif i == 51:
                self.insert_last(i, 16)
            elif i == 54:
                self.insert_last(i, -20)
            elif i == 63:
                self.insert_last(i, -47)
            elif i == 69:
                self.insert_last(i, i + 2)
            elif i == 71:
                self.insert_last(i, 20)
            elif i == 75:
                self.insert_last(i, 5)
            elif i == 80:
                self.insert_last(i, 19)
            elif i == 93:
                self.insert_last(i, -19)
            elif i == 96:
                self.insert_last(i, 1)
            elif i == 97:
                self.insert_last(i, -36)
            else:
                self.insert_last(i, 0)

    def move_(self):
      current = self._header or self._trailer
      if current is not None:
          for roll in self._dice_seq:
              for _ in range(roll):
                  if current._next is not None and current._next._element is not None and current._next != self._trailer:
                      current = current._next
                      print("Moved to square", current._element)
                  else:
                      break
          if current is not None and current != self._trailer:
              self._header = current
              print("Current position:", current._element)
          else:
              print("Current position: None")
      else:
          print("Current position: None")


    def check_win(self):
        return self._header._element == 100

    # Add this method inside the DoublyLinkedBase class

    def insert_last(self, square_id, move_shift):
        current = self._header._next
        while current:
            if current._element == square_id:
                current._element += move_shift
                # Ensure the circular behavior
                if current._element > 100:
                    current._element = 200 - current._element
                print("Moved to square", current._element)
                self._header = current  
                return
            current = current._next

     
# Main dirver

dl = DoublyLinkedBase()

dl.inistialize_board()

dl.display_board()

for i in range(1, 10):
    dl.dice_roll_sequance(i)

Những gì tôi đã thử:

Tôi phải thực hiện sửa đổi nào để nó không in gì? (danh sách liên kết mã)
đầu ra :

Current position: None
case 1, ans = 84
Current position: None
case 2, ans = 38
Current position: None
case 3, ans = 100 win
Current position: None
case 4, ans = 61 
Current position: None
case 5, ans = 95
Current position: None
case 6, ans = 38
Current position: None
case 7, ans = 5
Current position: None
case 8, ans = 31
Current position: None
case 9, ans =99

Giải pháp 1

Trước tiên, hãy bắt đầu bằng cách tìm ra nơi nó đang in “Vị trí hiện tại: Không có” – có hai nơi in rõ ràng điều đó và một nơi có thể in điều đó nếu người định giá của current._element đã từng là None. Bạn có thể sử dụng trình gỡ lỗi để xem qua mã của mình và tìm ra điều đó: pdb — Trình gỡ lỗi Python — Tài liệu Python 3.12.1[^] sẽ giúp ích nếu bạn không biết cách sử dụng nó.

Sau đó hãy xem tại sao nó lại đạt đến vị trí đó, nếu đi theo con đường nào và tại sao. Điều gì đã khiến nó đi theo hướng đó? Những biến nào không có giá trị mong đợi? Họ đã đặt mục tiêu gì; chúng nên chứa những gì? Lẽ ra chúng phải được đặt ở đâu? Tại sao họ lại không?

Khi bạn biết tất cả những điều đó, tác giả sẽ khá rõ ràng rằng mã (tức là bạn) vấn đề là gì và bạn có thể khắc phục nó.

Nhưng việc làm cho mã của bạn chạy đúng cách là một phần quan trọng của nhiệm vụ và bạn sẽ không học được cách sửa mã phức tạp cho đến khi bạn có thể sửa mã đơn giản như thế này!

コメント

タイトルとURLをコピーしました