Last active
February 9, 2020 03:26
-
-
Save g-w1/ef6a64f1e6efe389fcc135e894eb8c62 to your computer and use it in GitHub Desktop.
a program that when given 2 decks of 26 for the card game war can return the output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random | |
| import time | |
| def decksplit(): | |
| deck = list(range(13))*4 | |
| random.shuffle(deck) | |
| p1 = deck[:26] | |
| p2 = deck[26:] | |
| return (p1,p2) | |
| def printb(p1,p2, time, war = False): | |
| print(p1) | |
| print(p2) | |
| print(f'lengths = {len(p1)}, {len(p2)}, sum = {len(p1)+len(p2)}') | |
| print(f'{time}\'th time') | |
| if war: | |
| print('There is a war') | |
| if len(p1)+len(p2)!=52: | |
| raise Exception('the lengths are not equal. this is for debugging') | |
| print('\n') | |
| def recwar(p1,p2,runcount,spoils=[]): | |
| if p1[0]>p2[0]: | |
| try: | |
| p1+=spoils+[p1.pop(0),p2.pop(0)] | |
| except: | |
| return 'error' | |
| runcount+=1 | |
| return (p1,p2,runcount) | |
| elif p2[0]>p1[0]: | |
| try: | |
| p2+=spoils+[p2.pop(0),p1.pop(0)] | |
| except: | |
| return 'error' | |
| runcount+=1 | |
| return (p1,p2,runcount) | |
| else: | |
| runcount+=1 | |
| try: | |
| spoils += [p1.pop(0) for x in range(4)] + [p2.pop(0) for x in range(4)] | |
| except: | |
| return "error" | |
| return recwar(p1,p2,runcount,spoils=spoils) | |
| runcount = 0 | |
| start = time.time() | |
| with open('out.csv','w') as f: | |
| pass | |
| def war(p1,p2): | |
| for i in range(1):#or how many times you want to run it | |
| error = True | |
| runcount = 0 | |
| while len(p1)>3 and len(p2)>3 and error: | |
| try: | |
| p1,p2,runcount = recwar(p1,p2,runcount,spoils=[]) | |
| except: | |
| error=False | |
| if len(p1)<len(p2): | |
| winner = 1 | |
| else: | |
| winner = 0 | |
| return (winner,runcount) | |
| print(f"took {time.time()-start} seconds") | |
| p1,p2=decksplit() | |
| print(war(p1,p2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment