Hallo,
und danke erst einmal an alle die sich die Zeit für mein Problem nehmen.
Ich habe ein simples Kartenspiel erstellt, aber bin noch nicht so vertiert was Python angeht und weiß nicht,
warum mein Programm nach einer gewissen Zeit abbricht. Da ich nicht weiß wie man die Dateien anhängen kann und es zu viele Bilder wären, habe ich die beiden Dateien mit in diese Nachricht gepackt. Ich will im Prinzip erreichen, dass alle Karten in meinem Deck ausgespielt werden und dann ein Gesammtsieger ermittelt wird. Nach ein paar ausgespielten Karten bricht das Programm aber ab, wie könnte ich das am Besten mit Schleifen lösen bzw. was sind meine Fehler? (Die Fehlermeldung ist im Bild zu sehen: https://ibb.co/vq4bVpJ , ist ein Link für ImgBB)
Danke
Cards.py:
# cards
import random
import time
# definition of the deck
deck = [["Warrior",12,10,False],["Guard",7,6,False],["Wizard",15,5,False], \
["Witch",13,9,False], ["Thief",8,4,False],["Dragon",15,14,False], \
["Dwarf",10,11,False],["Mercenary",11,8,False], \
["Witcher",13,13,False],["Assassin",12,10,False], \
["Troll",9,13, False],["Basilisk",11,14,False],["Ork",13,12],["Centaur",23,1], ["Jester",1,3],["Giant",15,15]]
# main menu
def show_menu():
print("Menu")
print("====")
print("0: Quit")
print("1: show card")
print("2: add your own card to deck")
print("3: Start a new game")
print("4: Show Card Deck")
choice = -1
while not(choice in [0,1,2,3,4,5]):
choice = int(input("Your choice "))
return choice
# show a card
def show_card(number):
# card_name
first_line = "║ " + deck[number][0]
while len(first_line)<25:
first_line = first_line+" "
first_line = first_line + "║"
second_line = "║ offense power: " + str(deck[number][1])
while len(second_line)<25:
second_line = second_line+" "
second_line = second_line + "║"
third_line = "║ defense power: " + str(deck[number][2])
while len(third_line)<25:
third_line = third_line+" "
third_line = third_line + "║"
#
print("╔════════════════════════╗")
print(first_line)
print("╠════════════════════════╣")
print("║ ║")
print(second_line)
print("║ ║")
print(third_line)
print("║ ║")
print("╚════════════════════════╝")
#show all cards
def show_deck():
for i in range(0,len(deck)-1):
show_card(i)
# add a card to deck
def add_card():
print(" ")
cardname=input("Choose the name of your card")
defense=input("Choose the defense power of your char")
offense=input("Choose the offense power of your char")
new_card=[name, defense, offense]
deck.append(new_card)
# reset for new game: set all cards as non-played,
def deck_reset():
for card in deck:
card[3] = False
return len(deck)
# play a card
def play_card(rest):
number = random.randint(0,len(deck)-1)
while deck[number][3]==True:
number = random.randint(0,len(deck)-1)
deck[number][3] = True
show_card(number)
return deck[number], rest-1
#def play_random(rest):
#random_point = random.choice(card_points)
#random_sign = random.choice(card_signs)
#random_card = random_point,random_sign
#print(random_card, show_card)
#Abfrage der Karten im Deck
e = len(deck)
#start a new game
def starta_game():
while e >=0:
for i in range(1):
random1_card = random.choice(deck)
print("You are playing the card: ", random1_card)
#time.sleep(2)
for i in range(1):
random2_card = random.choice(deck)
print("The computer is playing the card: ", random2_card)
#time.sleep(2)
computer = random2_card
player = random1_card
winnerscore = 0
winnerscore = random2_card[1]-random1_card[2]
print("What an exciting battle!...", "difference: ", winnerscore, "...The fight is over.")
#time.sleep(1)
#points
ComputerPoints = 0
PlayerPoints = 0
if winnerscore >=0:
print("The computer beated you")
#time.sleep(2)
deck.remove(random2_card)
deck.remove(random1_card)
print("The cards were removed from the deck and the next round will start")
#time.sleep(2)
ComputerPoints = ComputerPoints+1
print("The Computer has ", ComputerPoints, "point/s.")
#time.sleep(1)
print("You have ", PlayerPoints, "point/s.")
#time.sleep(1)
for i in range(1):
random2_card = random.choice(deck)
print("The computer is playing the card, because he won the last round: ", random2_card)
#time.sleep(2)
for i in range(1):
random1_card = random.choice(deck)
print("You are playing the card: ", random1_card)
#time.sleep(2)
computer = random2_card
player = random1_card
winnerscore = 0
winnerscore = random1_card[1]-random2_card[2]
print("What an exciting battle!...", "difference: ", winnerscore, "...The fight is over.")
if winnerscore >=0:
print("You have won the round.")
#time.sleep(2)
deck.remove(random2_card)
deck.remove(random1_card)
print("The cards were removed from the deck and the next round will start")
#time.sleep(2)
ComputerPoints = ComputerPoints+1
print("The Computer has ", ComputerPoints, "point/s.")
#time.sleep(1)
print("You have ", PlayerPoints, "point/s.")
#time.sleep(1)
elif winnerscore >0:
print("The Computer beated you.")
#time.sleep(2)
deck.remove(random2_card)
deck.remove(random1_card)
print("The cards were removed from the deck and the next round will start")
#time.sleep(2)
ComputerPoints = ComputerPoints+1
print("The Computer has ", ComputerPoints, "point/s.")
#time.sleep(1)
print("You have ", PlayerPoints, "point/s.")
#time.sleep(1)
#___________________________________________________________________________________________________________
elif winnerscore <=0:
print("You won ")
#time.sleep(2)
deck.remove(random2_card)
deck.remove(random1_card)
print("The cards were removed from the deck and the next round will start.")
#time.sleep(2)
PlayerPoints2 = PlayerPoints+1
print("You have ", PlayerPoints, "point/s.")
#time.sleep(1)
print("The Computer has ", ComputerPoints, "point/s.")
#time.sleep(1)
for i in range(1):
random1_card = random.choice(deck)
print("You are playing a card, because you won the last round: ", random1_card)
#time.sleep(2)
for i in range(1):
random2_card = random.choice(deck)
print("The computer is playing the card: ", random2_card)
#time.sleep(2)
computer = random2_card
player = random1_card
winnerscore = 0
winnerscore = random2_card[1]-random1_card[2]
print("What an exciting battle!...", "difference: ", winnerscore, "...The fight is over.")
if winnerscore >=0:
print("The Computer beated you.")
print("The Computer beated you.")
#time.sleep(2)
deck.remove(random2_card)
deck.remove(random1_card)
print("The cards were removed from the deck and the next round will start")
#time.sleep(2)
ComputerPoints = ComputerPoints+1
print("The Computer has ", ComputerPoints, "point/s.")
#time.sleep(1)
print("You have ", PlayerPoints, "point/s.")
#time.sleep(1)
elif winnerscore <0:
print("You have won the round.")
print("The Computer beated you.")
#time.sleep(2)
deck.remove(random2_card)
deck.remove(random1_card)
print("The cards were removed from the deck and the next round will start")
#time.sleep(2)
ComputerPoints = ComputerPoints+1
print("The Computer has ", ComputerPoints, "point/s.")
#time.sleep(1)
print("You have ", PlayerPoints, "point/s.")
#time.sleep(1)
if PlayerPoints>ComputerPoints:
print("You have won :>")
elif ComputerPoints>PlayerPoints:
print("The Computer won :<, try it again :>")
main.py:
# battlecards
import cards
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# main
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
action = -1
while action !=0:
action = cards.show_menu()
if action == 1:
card_number = int(input("Which card? "))
cards.show_card(card_number)
elif action == 2:
#cards.add_card()
print("add a card")
cards.add_card()
elif action==3:
# start a new game
print("Start a new game")
print("Card Deck")
cards.starta_game()
elif action==4:
#show all cards
print("Show all Cards in deck")
cards.show_deck()
Python Kartenspiel mit Listen
Die vielen Leerzeilen an den unpassendsten Stellen machen den Code schwer lesbar.
Eingerückt wird immer mit 4 Leerzeichen pro Ebene, das ist nicht überall so.
Variablennamen und Funktionen werden komplett klein geschrieben.
Benutze keine globalen Variablen. `deck` sollte in allen Funktionen wo es gebraucht wird auch als Parameter übergeben werden.
In `show_menu`: wenn man einer Variable einen Dummy-Wert geben muß, damit eine Schleife überhaupt losläuft, dann will man eigentlich eine while-True-Schleife benutzen. not ist keine Funktion und sollte auch nicht wie eine geschrieben werden. Was ist denn die geheimnisvolle 5, die man auch eingeben kann?
`show_card` sollte man keine Nummer übergeben, sondern direkt die Karte, denn sonst müßte man ja neben der Nummer auch noch das Deck übergeben.
Statt Zeilen per while-Schleife mit Leerzeichen zu füllen, benutzt man Stringformatierung.
Über einen Index zu iterieren, macht man in Python nicht, weil man auch direkt über die Elemente des decks iterieren kann:
In `add_card` werden die Eingaben nicht in den richtigen Typ umgewandelt, außerdem gibt es Karten mit 4 Elementen, Du fügst aber nur eine mit drei Elementen hinzu (was auch Deine Fehlermeldung erklärt):
In `play_card` würde man random.choice benutzen, dort hat man aber das Problem, dass Du eine Endlos-Schleife bekommst, wenn keine Karte mehr übrig ist.
In `start_a_game` hast Du ein `e`, das eine globale Variable ist, die sich aber nie ändert.
Eine for-Schleife, die genau einmal durchlaufen wird, ist irgendwie überflüssig.
Warum nennst Du random1_card in player und random2_card in computer um? Warum verwendest Du nicht gleich gute Variablennamen, z.B. player_card und computer_card?
Warum setzt Du winnerscore mit 0 um es sofort mit einem anderen Wert überschrieben?
Wenn Du eine if-Bedingung hast und eine elif-Bedingung, die genau das Gegenteil ist, dann benutzt man statt elif else.
In den if-Blöcken hast Du nochmal den selben Code kopiert, das kann man also viel einfacher schreiben. Da sind auch ein paar Tippfehler drin.
Entsprechend muß man main auch anpassen:
Eingerückt wird immer mit 4 Leerzeichen pro Ebene, das ist nicht überall so.
Variablennamen und Funktionen werden komplett klein geschrieben.
Benutze keine globalen Variablen. `deck` sollte in allen Funktionen wo es gebraucht wird auch als Parameter übergeben werden.
In `show_menu`: wenn man einer Variable einen Dummy-Wert geben muß, damit eine Schleife überhaupt losläuft, dann will man eigentlich eine while-True-Schleife benutzen. not ist keine Funktion und sollte auch nicht wie eine geschrieben werden. Was ist denn die geheimnisvolle 5, die man auch eingeben kann?
Code: Alles auswählen
def show_menu():
print("Menu")
print("====")
print("0: Quit")
print("1: show card")
print("2: add your own card to deck")
print("3: Start a new game")
print("4: Show Card Deck")
while True:
not():
choice = int(input("Your choice "))
if choice in [0,1,2,3,4,5]:
break
return choice
Statt Zeilen per while-Schleife mit Leerzeichen zu füllen, benutzt man Stringformatierung.
Code: Alles auswählen
def show_card(card):
print("╔════════════════════════╗")
print(f"║ {card[0]:20s} ║")
print("╠════════════════════════╣")
print("║ ║")
print(f"║ offense power: {card[1]:<5d} ║")
print("║ ║")
print(f"║ defense power: {card[2]:<5d} ║")
print("║ ║")
print("╚════════════════════════╝")
Code: Alles auswählen
def show_deck(deck):
for card in deck:
show_card(card)
Code: Alles auswählen
def add_card(deck):
print(" ")
cardname = input("Choose the name of your card")
defense = int(input("Choose the defense power of your char"))
offense = int(input("Choose the offense power of your char"))
new_card = [name, defense, offense, False]
deck.append(new_card)
Code: Alles auswählen
def play_card(deck):
available_cards = [card for card in deck if not card[3]]
card = random.choice(available_cards)
card[3] = True
show_card(card)
return card
Eine for-Schleife, die genau einmal durchlaufen wird, ist irgendwie überflüssig.
Warum nennst Du random1_card in player und random2_card in computer um? Warum verwendest Du nicht gleich gute Variablennamen, z.B. player_card und computer_card?
Warum setzt Du winnerscore mit 0 um es sofort mit einem anderen Wert überschrieben?
Wenn Du eine if-Bedingung hast und eine elif-Bedingung, die genau das Gegenteil ist, dann benutzt man statt elif else.
In den if-Blöcken hast Du nochmal den selben Code kopiert, das kann man also viel einfacher schreiben. Da sind auch ein paar Tippfehler drin.
Code: Alles auswählen
def start_a_game(deck):
game_round = 0
computer_points = player_points = 0
deck.shuffle()
while deck:
player_card = deck.pop()
computer_card = deck.pop()
print("You are playing the card: ", player_card)
print("The computer is playing the card: ", computer_card)
if game_round % 2 == 0:
winnerscore = computer_card[1] - player_card[2]
computer_wins = winnerscore >= 0
else:
winnerscore = player_card[1] - computer_card[2]
computer_wins = winnerscore < 0
print("What an exciting battle!...", "difference: ", winnerscore, "...The fight is over.")
if computer_wins:
computer_points += 1
print("The computer beated you")
else:
player_points += 1
print("You have won the round.")
print("The cards were removed from the deck and the next round will start")
print(f"The Computer has {computer_points} point/s.")
print(f"You have {player_points} point/s.")
game_round += 1
if player_points > computer_points:
print("You have won :>")
elif computer_points > player_points:
print("The Computer won :<, try it again :>")
Code: Alles auswählen
def initialize_deck():
return [
["Warrior",12,10,False],
["Guard",7,6,False],
["Wizard",15,5,False],
["Witch",13,9,False],
["Thief",8,4,False],
["Dragon",15,14,False],
["Dwarf",10,11,False],
["Mercenary",11,8,False],
["Witcher",13,13,False],
["Assassin",12,10,False],
["Troll",9,13, False],
["Basilisk",11,14,False],
["Ork",13,12,False],
["Centaur",23,1,False],
["Jester",1,3,False],
["Giant",15,15,False]
]
def main():
deck = initialize_deck()
while True:
action = show_menu()
if action == 1:
card_number = int(input("Which card? "))
show_card(deck[card_number])
elif action == 2:
print("add a card")
add_card(deck)
elif action==3:
print("Start a new game")
print("Card Deck")
start_a_game(deck)
elif action==4:
print("Show all Cards in deck")
show_deck(deck)
if __name__ == '__main__':
main()
Offtopic: Die Vergangenheitsformen von "beat" lauten "beat" und "beaten". Es gibt kein "beated".
Also entweder
print("The computer beat you.")
oder
print("The computer has beaten you.")
Also entweder
print("The computer beat you.")
oder
print("The computer has beaten you.")
Ich bin Pazifist und greife niemanden an, auch nicht mit Worten.
Für alle meine Code Beispiele gilt: "There is always a better way."
https://projecteuler.net/profile/Brotherluii.png
Für alle meine Code Beispiele gilt: "There is always a better way."
https://projecteuler.net/profile/Brotherluii.png