Nhờ giải thích code python

chào mng e/mình đang học python và code theo hướng dẫn. Nhưng trong bài có đoạn code làm e/mình hơi khó hiểu nhờ mọi người giải đáp ạ.

RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()

if card_comp[1]==card_user[1]:
    war_count+=1

    print 'war'

    table_cards.extend(player_user.cards_for_war())
    table_cards.extend(player_comp.cards_for_war())

    if RANKS.index(card_comp[1])<RANKS.index(card_user[1]):
        player_user.hand.add_card(table_cards)
    else:
        player_comp.hand.add_card(table_cards)

trong đoạn code trên thì đoạn

if card_comp[1]==card_user[1]:

if RANKS.index(card_comp[1])<RANKS.index(card_user[1]):

e/mình cảm thấy nó kiểu đá nhau và không hiểu nó sẽ chạy đoạn dưới như thế nào.
Nhờ mng chỉ giúp ạ. E/mình cảm ơn!

1 Like

Thuật toán của code này là gì vậy bạn? Tự nhiên bạn đưa 1 đoạn code ở giữa chừng như vậy, khó đọc được lắm.

2 Likes

tại code hơi dài e sợ đăng lên mọi ng ngại đọc nên chiết ra như vậy
còn đây là full code ạ

from random import shuffle

 # variables for creating Cards.
SUITE = 'H D S C'.split()       # mean rô cơ trù bích
RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()

class Deck:

    """
    Create a deck of cards to initiate play
    """

    def __init__(self):
        'crating Deck'
        self.items = [(s,r) for s in SUITE for r in RANKS]

    # mix all card
    def  shuffle_deck(self):
        print("shuffle cards")
        shuffle(self.items)

    # deck(4*13 =52 cards) was devided for 2 people
    def split_deck(self):
        print("split Deck")
        return(self.items[:26], self.items[26:])

class Hand(Deck):
    """ add or remove cards from that hand"""

    def __init__(self, cards):
        self.cards = cards

    def add_card(self, card):
        print("add a card to deck")
        self.cards.extend(card)

    def remove_card(self):
        return self.cards.pop()

class Player:

    """ check cards, takes in a name and instance of Hand class"""

    def __init__(self, name, hand):
        self.name = name
        self.hand = hand

    def play_card(self):
        card = self.hand.remove_card()
        print("{} card to be played by {}".format(card, self.name))
        return card

    def card_for_war(self):
        war_cards = []
        if len(self.hand.cards) < 3:
            return war_cards
        else:
            for i in range(3):
                war_cards.append(self.hand.remove_card())
            return war_cards

    def still_has_cards(self):
        return len(self.hand.cards) != 0

#GAME Play

print("Welcome to War, let's begin...")

# Use the 3 classes along with some logic to play a game of war

deck = Deck()
deck.shuffle_deck()
name = input("What is your name?")
half1, half2 = deck.split_deck()

player_comp = Player('computer', Hand(half1))
player_user = Player(name, Hand(half2))

war_count = 0
rounds = 0

while(player_comp.still_has_cards() and player_user.still_has_cards()):
    print("It is time for a new round!")
    print("here are the current standings: ")
    print(player_user.name+" cout: "+str(len(player_user.hand.cards)))
    print(player_comp.name+" cout: "+str(len(player_comp.hand.cards)))
    print("Both players play a card!")
    print('\n')

    rounds += 1
    card_user = player_user.play_card()
    card_comp = player_comp.play_card()

    #comparing Both
    table_cards = []

    table_cards.append(card_comp)
    table_cards.append(card_user)

    if card_comp[1] == card_user[1]:
        war_count += 1

        print("war")

        table_cards.extend(player_user.card_for_war())
        table_cards.extend(player_comp.card_for_war())

        if RANKS.index(card_comp[1]) < RANKS.index(card_user[1]):
            player_user.hand.add_card(table_cards)
        else:
            player_comp.hand.add_card(table_cards)
    else:
        if RANKS.index(card_comp[1]) < RANKS.index(card_user[1]):
            player_user.hand.add_card(table_cards)
        else:
            player_comp.hand.add_card(table_cards)


print('rounds were ' + str(rounds))
print('wars were ' + str(war_count))

e nhờ mọi ng chỉ giúp ạ

Chắc là có sự “thiên vị” nào đó.
Các lá bài luôn được thêm vào cho comp khi chỉ số lá bài (rank) bằng nhau.

Kết quả luôn là người chơi hết bài, còn comp thì ôm trọn 52 quân.

1 Like

e không hiểu là chỉ số đã bằng nhau rồi lại so sánh lại có chăng thì e nghĩ đó là số 0 thì đúng hơn tại vì xét theo chỉ số bằng nhau rồi thì chuyển sang so sánh chất bài kiểu cơ rô bích tép :frowning:

2 Likes

Chạy code thấy hư cấu quá, code lởm rồi :v

1 Like

really?? e chạy sao thấy cũng ok nhỉ :frowning:

bonus là cái này trên udemy có lẽ nào nó sai tai hại như vậy k ạ

Có thể là như vậy. Không lý gì đã bằng nhau, lại phải so sánh lớn/nhỏ hơn được nữa.

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?