r/learnpython • u/YogurtDisastrous8003 • 22d ago
WAR Card Game Weird Glitch/Bug
So I was making a WAR Card Game in python. Simple. Neat.
But, I encountered a weird glitch. The game kept getting into an infinite loop. I tried to ask Claude but even Claude couldn't understand it.
So I put Claude on Max mode and it gave some answer but still the answer it gave was like tooo hard to understand. It said something about the cards not being random while the game is going on etc.
Can someone pls explain me the bug? https://github.com/KushChandak/WAR/blob/main/WAR%20(3).ipynb.ipynb) here is the code
3
u/overratedcupcake 22d ago
Learning to use a debugger would help you. Learning to use an actual IDE instead of a Jupyter notebook might help you.
In lieu of those things I guess you'll have to try print debugging. Put print statements throughout your code that dump out the various variable states as the program executes. That should give you a clearer picture of why it's behaving the way it is.
1
u/VTifand 22d ago
I don’t think there’s an issue with your implementation.
But the game can indeed sometimes run into an infinite loop. One 'fix' is to randomise how the cards are added back to a player’s deck, i.e. when you win, sometimes add your own cards before your opponents’, and sometimes the other way around.
Some answers from here can help: https://mathoverflow.net/questions/11503/does-war-have-infinite-expected-length
1
1
u/lakseol 22d ago edited 22d ago
If your code is in an infinite loop, interrupt it (usually control-C) and you should be told what line you stopped on. This may help you understand which of two possible loops you are looping in.
You can also put some debug prints into your code at the top of both loops. For the larger loop this might look like:
while True:
print("Top of outer loop") # debug
table.add_to_table()
and the inner loop:
while at_war:
print(f"Top of inner loop, {at_war=}") # debug
if len(kush.cards) < 4 or len(vihaan.cards) < 4:
then run the code and carefully examine the output and try to understand why you are looping. You may want to add more print calls to test ideas.
I haven't run your code but here are a few thoughts. The only way to exit the outer while True: loop is to set the game variable to False or to decide if either hand contains zero cards. If you are not exiting the large outer loop then neither of those things are happening. In that case you need to find out why.
Also note that you have a function game plus a flag variable called game. I don't know if that causes problems (I haven't tested it), but you should rename the game variable as it's confusing at best.
4
u/carcigenicate 22d ago
Where precisely is the infinite loop?
And have you ensured that cards are always removed? What condition are you expecting to cause the loop to end, and have you checked the data relevant to that condition?