The following contains abridged version of the code for a text card game I am trying to run. It should get a random string for a card from a random line in "cards.txt", and add it to a user's collection at "user.txt" (user would be the name of the user). A sample line from "users.txt" should look like:
X* NameOfCard
If "user.txt" already contains an entry for a card, it changes the number before the name by 1. If "user.txt" had:
1* Hyper Dragon
then got another Hyper Dragon, the line would look like:
2* Hyper Dragon
If there is no version already in there, it should append a newline that says:
1* NameOfCard
The code however, is flawed. No matter what, it will always change the contents of "users.txt" to:
1* NameOfCard
(followed by 3 blank lines)
I believe the issue to lie in the marked for loop in the following code:
from random import choice
def check(e, c):
if (c in e):
return True
else:
return False
username = input("What is the username?: ")
collectionPath = f"collections\\{username}.txt"
while True:
with open("cards.txt", "r") as cards:
card_drew = f"{choice(cards.readlines())}\n"
print("Card drawn: "+card_drew)
with open(collectionPath, "w+") as file:
copyowned = False
print("Looking for card")
currentline = 0
for line in file:
# this is the marked for loop.
print("test")
print("checking "+line)
currentline += 1
if (check(card_drew, line)):
print("Found card!")
copyowned = True
strnumof = ""
for i in line:
if (i.isdigit()):
strnumof = strnumof+i
numof = int(strnumof)+1
line = (f"{numof}* {card_drew}")
print("Card added, 2nd+ copy")
if (not copyowned):
with open(collectionPath, "a") as file:
file.write(f"1* {card_drew}\n")
print("Card Added, 1st copy")
input(f"{username} drew a(n) {card_drew}")
When I run it, the for loop act as if it's not there. It wont even run a print function, though an error message never appears. After using try and except statements, the loop still doesn't porvide an error. I have no clue why it's doing this.
Some help would be greatly appreciated.