用python编写一个卡牌战斗小游戏,附上代码
时间: 2023-09-06 14:11:29 浏览: 164
使用Python写一个小游戏
好的,以下是一个简单的Python卡牌战斗小游戏的代码:
```
import random
class Card:
def __init__(self, name, attack, defense):
self.name = name
self.attack = attack
self.defense = defense
class Player:
def __init__(self, name, deck):
self.name = name
self.deck = deck
self.hand = []
self.discard = []
self.life = 30
def draw_card(self):
if len(self.deck) == 0:
self.deck = self.discard
self.discard = []
random.shuffle(self.deck)
if len(self.deck) > 0:
card = self.deck.pop(0)
self.hand.append(card)
def play_card(self, card_index, opponent):
if card_index < len(self.hand):
card = self.hand[card_index]
self.hand.remove(card)
if card.attack > 0:
opponent.life -= card.attack
else:
self.life -= card.defense
self.discard.append(card)
def print_stats(self):
print("Name: {}".format(self.name))
print("Life: {}".format(self.life))
print("Hand: {}".format([card.name for card in self.hand]))
print("Deck: {}".format(len(self.deck)))
print("Discard: {}".format(len(self.discard)))
print("")
def create_deck():
deck = []
for i in range(10):
card = Card("Attack {}".format(i+1), i+1, 0)
deck.append(card)
for i in range(10):
card = Card("Defense {}".format(i+1), 0, i+1)
deck.append(card)
random.shuffle(deck)
return deck
def main():
deck1 = create_deck()
deck2 = create_deck()
player1 = Player("Player 1", deck1)
player2 = Player("Player 2", deck2)
for i in range(5):
player1.draw_card()
player2.draw_card()
while player1.life > 0 and player2.life > 0:
player1.print_stats()
player2.print_stats()
print("Player 1, choose a card to play (0-{}):".format(len(player1.hand)-1))
card_index = int(input())
player1.play_card(card_index, player2)
player1.draw_card()
player2.draw_card()
player1.print_stats()
player2.print_stats()
print("Player 2, choose a card to play (0-{}):".format(len(player2.hand)-1))
card_index = int(input())
player2.play_card(card_index, player1)
player1.draw_card()
player2.draw_card()
if player1.life <= 0:
print("Player 2 wins!")
else:
print("Player 1 wins!")
if __name__ == "__main__":
main()
```
这个游戏有两个玩家,每个玩家有一个牌库和30点生命值。每回合,玩家从牌库中抽一张牌,并选择一张手牌使用(如果是攻击牌,则对对手造成伤害;如果是防御牌,则自己获得相应的防御能力)。游戏结束条件是其中一个玩家的生命值降为零。在代码中,`Card`类表示卡牌,`Player`类表示玩家,`create_deck()`函数用于生成含有10张攻击牌和10张防御牌的牌库,`main()`函数为整个游戏的主逻辑。
阅读全文