War Card Game Python

Posted on  by 

War is a classic kids card game. I spent many an hour wiling away the time playing war growing up. Enough so that I actually developed a strategy for the game. A strategy for the game of war? That's crazy talk.

  1. War Card Game In Python
  2. Card Games In Python
  3. War Card Game Python 3
  4. War Game In Python

For those who've never encounter the game of war here are the rules. A standard deck of 52 cards is shuffled and split between two equal stacks which are then given to the two players. The players then turn over the top card of their stacks and the player with the higher rank card 'wins' and gets to take the two cards and place them at the bottom of their stack. If the cards end up being the same rank, then a 'war' occurs. The players each deal two cards face down (it doesn't really matter that they are face down. Variants of the game include dealing one card face down instead of two.) They then each deal a face up card and the player with the higher rank of these cards wins. If the ranks are the same, then another war ensues. If at any time during a war, a player runs out of cards, then the last card they can play is used as the face up card for the war (this could even be the card which started the war.) The goal, of course, is to be the person who ends up with all the cards (this is war, after all.)

Question: Use Python 3: War Card Game.(note Please Use The SKELETON CODE Provided).Drag The Picture To Webpage Box To Expand. Skeleton Code For Program: # War Game Import Random Class CircularQueue: # Constructor, Which Creates A New Empty Queue: Def init(self, Capacity): If Type(capacity)!= Int Or Capacity. War Card Game in Python December 2, 2012. Python (59) While cleaning out my code repository on my laptop I ran into an implementation of the card game War I wrote during a programming interview.

War card game python 3

WAR Demo Rules of the game. Each player is dealt half of the cards. Each player plays top card. – whichever is higher captures both cards – in event of tie, WAR Repeat until one player has all the cards. 5 Before You Write Any Code Determine a high-level view of the code you plan to write. Break it up into manageable pieces. USE PYTHON PROGRAMING, do not use 'def' functions for this assignemt. Introduction Come on admit it. Somewhere along the line as a kid (at least those of you who grew up in the US) you played the card game called War. Whenever cards are 'won', they should be shuffled together and placed on the bottom of the winner's deck. Wars occur when the initial cards are identical. Each player deals three cards face down and picks one of those three at random to decide the war. If it's another tie, the process is repeated.

So how in the world could there be a strategy for war? Well it all comes from the fact that when you win, you get to place cards at the bottom of the deck in an order which you get to choose. Of course if both players randomly place the winning bounty of cards onto the bottom of their deck, the game is symmetric and no one has an advantage. But what if you are playing against someone who randomly places cards at the bottom of the deck. Is there then a strategy which can give you an advantage?

When I was a kid I came up with just such a simple strategy for winning the game of war. My idea was that wars were very important in the game of war (whoda thunk?) and in particular it was important to try to setup your cards in such a was as to win as many wars as possible. The strategy thus worked by attempting to make the cards as close as possible to the template high, low, low, high, low, low, high, etc. One can do this by keeping track of where you are in such a template and then everytime you win ordering your cards so as to best match this template. There is some arbitrariness in this idea: for example if you win and get two cards which should be low, low in the sequence, which one do you put first? One could arbitrarily break ties for this problem or one could use a fixed strategy there as well. Yeah, all good and such, but does this strategy really provide any advantage?

Well, the question is, does my childhood strategy actually provide any advantage against a player that is randomizing the cards they put at the bottom of their deck? Today after many years of procrastination I cranked out a little python code to test this. The code implemented the strategy in a manner such that for any given sequence of high/lows that it was trying to match, the cards were sorted in such a way that the high's were sorted in descending order and the lows in descending order. Thus if you win the cards 1,5,10,7,8,9,6,12 and were trying to match high, low, low, high, low, low, high, low the order would be 12,1,5,10,6,7,9,8.

And what are the results? Well it turns out that indeed this strategy does give you an advantage. After one million games of war, the player implementing this strategy won 548330 times. Okay, not a huge advantage, but not insignificant either.

But this got me thinking, what about other simple strategies? Suppose you follow a repeated template of high,low, for example? Or high,high,low? Note that because of the way I coded up the program there is sorting going on. Thus a high, high, template causes you to order your cards in increasing order and a low, low template causes you to order your cards in decreasing order. Here are the results of simulations of 100000 games:


TemplateWinsNotes
[high]51336 decreasing sort
[low]40632increasing sort
[high,low]42102
[hi,lo,lo]54854
[high,high,low]58190
[low,low,low,high]40653
[low,low,high,high]46947
[low,high,high,high]50196
Wins for the player using the strategy given in the template.

An interesting high performing strategy on this list is the high,high,low strategy. It's not obvious to me why this strategy performs so well, but it gives you a pretty significant edge against a random ordering player.

So that's my basic strategy for winning the card game of war. So go out and defeat the average uninformed war player! Fame and fortune will certainly surely then be yours.

David Lightman: What is the primary goal?
Joshua: You should know, Professor. You programmed me.
David Lightman: C'mon. What is the primary goal?
Joshua: To win the game.

  • Log in to post comments

Use python 3: War card game .(note Please use theSKELETON CODE provided).Drag the picture to webpage box toexpand.

Skeleton code for program :

# War Game

import random
class CircularQueue:
# Constructor, which creates a new empty queue:
def __init__(self, capacity):
if type(capacity) != int or capacity<=0:
raise Exception (‘Capacity Error’)
self.items = []
self.capacity = capacity
self.count=0
self.head=0
self.tail=0
# Adds a new item to the back of the queue, and returnsnothing:
def enqueue(self, item):
if self.count self.capacity:
raise Exception(‘Error: Queue is full’)
if len(self.items) < self.capacity:
self.items.append(item)
else:
self.items[self.tail]=item
self.count +=1
self.tail=(self.tail +1) % self.capacity
# Removes and returns the front-most item in the queue.
# Returns nothing if the queue is empty.
def dequeue(self):
if self.count 0:
raise Exception(‘Error: Queue is empty’)
item= self.items[self.head]
self.items[self.head]=None
self.count -=1
self.head=(self.head+1) % self.capacity
return item
# Returns the front-most item in the queue, and DOES NOT change thequeue.
def peek(self):
if self.count 0:
raise Exception(‘Error: Queue is empty’)
return self.items[self.head]
# Returns True if the queue is empty, and False otherwise:
def isEmpty(self):
return self.count 0
# Returns True if the queue is full, and False otherwise:
def isFull(self):
return self.count self.capacity
# Returns the number of items in the queue:
def size(self):
return self.count
# Returns the capacity of the queue:
def capacity(self):
return self.capacity

# Removes all items from the queue, and sets the size to 0
# clear() should not change the capacity
def clear(self):
self.items = []
self.count=0
self.head=0
self.tail=0
# Returns a string representation of the queue:
def __str__(self):
str_exp = “]”
i=self.head
for j in range(self.count):
str_exp += str(self.items[i]) + ” “
i=(i+1) % self.capacity
return str_exp + “]”
# # Returns a string representation of the objectCircularQueue
def __repr__(self):
return str(self.items) + ‘ Head=’ + str(self.head) + ‘Tail=’+str(self.tail) + ‘(‘+str(self.count)+’/’+str(self.capacity)+’)’
# START WRITING YOUR PROGRAM HERE
def read_and_validate_cards():
# TASK 1 Reading and Validating cards
# Three Conditions
# File Exists – raises Exception if it does not.
# 1.Exactly 52 2.Not repeated 3.Correct Format Raises Exception ifany of the
# above is not correct.
# TODO
pass

War Card Game In Python

def distribute_cards(cards):
# Task 2 Distributing cards
# Creates Two circular Queues and return them
# – cards is a list of valid cards that has been read from thefile
# TODO
pass

def get_user_input():
# Task 3 Asking user for input
# prompt the user to enter the number of cards that would befacedown for war
# will repeatedly ask the user to enter a valid value if any numberother than 1 or 2 or 3
# is entered
# returns the number entered by the user
# TODO
pass

def compare_cards(card1,card2):
# Task 4 Comparing Cards
# compares card1 of player 1 with card2 of player2
# if card1 has higher rank return 1
# if card2 has higher rank return 2
# if card1 is equal to card2 reurn 0
# – card 1 is a string representing a card of player1
# – card 2 is a string representing a card of player2
# TODO
pass

class onTable:
# Task 5 Create a class to represent the table
# an instance of this class represents the table
def __init__(self):
# self is the onTable object
# TODO
pass
def place(self,player,card,hidden):
# places the given card on the table
# -self is the onTable object
# -player is an object of type int. It is 1 for player1 or 2 forplayer 2
# -card is an object of type str. It is the card being placed onthe table
# -hidden is an object of type bool. False when the card is faceupand True when facedown
# TODO
pass
def cleanTable(self):
# cleans the table by initializing the instance attributes
# -self is the onTable object
# TODO
pass
def __str__(self):
# returns the representation of the cards on the table
# -self is the onTable object
# TODO
pass

def main():
# TODO – IMPLEMENT ALGORITHM HERE
pass

main()
———————————————————————————————————————————————————————————————————————————————

# separate program that creates a file representing deckof cards, doesn’t need to be changed.

War Card Game Python

from random import shuffle

Card

suits=[“D”, “C”, “H”, “S”]
ranks=[“K”,”Q”,”J”,”A”,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”0″]

cards=[]
for rank in ranks:
for suit in suits:
cards.append(rank+suit)
shuffle(cards)
try:
cardFile= open(“shuffledDeck.txt”, “w”)
for card in cards:
cardFile.write(card+”n”)
except IOError as e:
print (“I/O error({0}: {1}”.format(e.errno, e.strerror))
except:
print (“Unexpected error”)
finally:
cardFile.close()
print (“The following shuffled 52 card deck was saved inshuffledDeck.txt”)
print (cards)

Card Games In Python

War Card Game Python

War Card Game Python 3

Expert Answer

War Game In Python

: Ps2 Iso Collection Torrent

  • : Simply Piano App
  • : Vst Plugin Bc Chorus 4 Vst Stereo
  • : Mod Central Mac
  • : Project X Love Potion Disaster Save Game