def stack_to_queue(my_stack): s = deepcopy(my_stack) q = LinkedQueue() while not s.isEmpty(): q.add(s.peek()) s.pop() return q
class TicketCounterSimulation: # Create a simulation object. def __init__(self, numAgents, numMinutes, betweenTime, serviceTime): # Parameters supplied by the user. self._arriveProb = 1.0 / betweenTime self._serviceTime = serviceTime self._numMinutes = numMinutes # Simulation components. self._passengerQ = Queue() self._theAgents = Array(numAgents) for i in range(numAgents): self._theAgents[i] = TicketAgent(i + 1) # Computed during the simulation. self._totalWaitTime = 0 self._numPassengers = 0 # Run the simulation using the parameters supplied earlier. def run(self): for curTime in range(self._numMinutes + 1): self._handleArrive(curTime) self._handleBeginService(curTime) self._handleEndService(curTime) self.printResults() # Print the simulation results. def printResults(self): numServed = self._numPassengers - len(self._passengerQ) avgWait = float(self._totalWaitTime) / numServed print("") print("Number of passengers served = ", numServed) print("Number of passengers remaining in line = %d" % len(self._passengerQ)) print("The average wait time was %4.2f minutes." % avgWait) # Handles simulation rule #1. def _handleArrive(self, curTime): if random.randint(0.0, 1.0) <= self._arriveProb: self._numPassengers += 1 passenger = Passenger(self._numPassengers, curTime) self._passengerQ.add(passenger) # Handles simulation rule #2. def _handleBeginService(self, curTime): for agent in self._theAgents: if agent.isFree(): if not self._passengerQ.isEmpty(): agent.startService(self._passengerQ.pop(), curTime + self._serviceTime) # Handles simulation rule #3. def _handleEndService(self, curTime): for agent in self._theAgents: if agent.isFinished(curTime): passenger = agent.stopService() self._totalWaitTime += len(self._passengerQ)
def stack_to_queue(stack): """Return a queue that contains items from the stack.""" queue = LinkedQueue() item_list = [] for item in stack: item_list.insert(0, item) for item in item_list: queue.add(item) return queue
class Cashier(object): """Represents a cashier.""" def __init__(self, number): """Maintains a cashier number, a queue of customers, number of customers served, total customer wait time, and a current customer being processed.""" self._number = number self._totalCustomerWaitTime = 0 self._customersServed = 0 self._currentCustomer = None self._queue = LinkedQueue() def getLineLength(self): """Returns the number of customers in the line.""" return len(self._queue) def addCustomer(self, c): """Adds an arriving customer to my line.""" self._queue.add(c) def serveCustomers(self, currentTime): """Serves my cuatomers during a given unit of time.""" if self._currentCustomer is None: # No customers yet if self._queue.isEmpty(): return else: # Pop first waiting customer and tally results self._currentCustomer = self._queue.pop() self._totalCustomerWaitTime += \ currentTime - \ self._currentCustomer.arrivalTime() self._customersServed += 1 # Give a unit of service self._currentCustomer.serve() # If current customer is finished, send it away if self._currentCustomer.amountOfServiceNeeded() == 0: self._currentCustomer = None def __str__(self): """Returns my results: my number, my total customers served, my average wait time per customer, and customers left on my queue.""" if self._customersServed != 0: aveWaitTime = float(self._totalCustomerWaitTime) /\ self._customersServed else: aveWaitTime = 0.0 result = "%4d %8d %13.2f %8d" % (self._number, self._customersServed, aveWaitTime, len(self._queue)) return result
class Cashier(object): """Represents a cashier.""" def __init__(self): """Maintains a queue of customers, number of customers served, total customer wait time, and a current customer being processed.""" self._totalCustomerWaitTime = 0 self._customersServed = 0 self._currentCustomer = None self._queue = LinkedQueue() def addCustomer(self, c): """Adds an arriving customer to my line.""" self._queue.add(c) def serveCustomers(self, currentTime): """Serves my cuatomers during a given unit of time.""" if self._currentCustomer is None: # No customers yet if self._queue.isEmpty(): return else: # Pop first waiting customer and tally results self._currentCustomer = self._queue.pop() self._totalCustomerWaitTime += \ currentTime - \ self._currentCustomer.arrivalTime() self._customersServed += 1 # Give a unit of service self._currentCustomer.serve() # If current customer is finished, send it away if self._currentCustomer.amountOfServiceNeeded() == 0: self._currentCustomer = None def __str__(self): """Returns my results: my total customers served, my average wait time per customer, and customers left on my queue.""" result = "TOTALS FOR THE CASHIER\n" + \ "Number of customers served: " + \ str(self._customersServed) + "\n" if self._customersServed != 0: aveWaitTime = self._totalCustomerWaitTime /\ self._customersServed result += "Number of customers left in queue: " + \ str(len(self._queue)) + "\n" + \ "Average time customers spend\n" + \ "waiting to be served: " + \ "%5.2f" % aveWaitTime return result
def add(self, item): """Adds item to its proper place in the queue.""" if self.isEmpty() or item >= self._rear.data: LinkedQueue.add(self, item) elif item < self._front.data: self._front = Node(item, self._front) self._size += 1 else: probe = self._front trailer = probe while item >= data: trailer = probe probe = probe.next trailer.next = Node(item, probe)
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = LinkedQueue() vertQueue.add(start) while not vertQueue.isEmpty(): currentVert = vertQueue.pop() for nbr in currentVert.getConnections(): if (nbr.getColor()) == 'white': nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.add(nbr) currentVert.setColor('black')
def add(self, item): if self.isEmpty() or self._rear.data <= item: LinkedQueue.add(item) else: probe = self._front while probe.data <= item: trailer = probe probe = probe.next newnode = Node(item, probe) if probe == self._front: self._front = newnode else: trailer.next = newnode self._size += 1
class Cashier(object): def __init__(self): self._total_customer_wait_time = 0 self._customers_served = 0 self._current_customer = None self._queue = LinkedQueue() def add_customer(self, c): self._queue.add(c) def serve_customers(self, current_time): # 1. 当前顾客不存在, if self._current_customer == None: # 等待队列为空, 直接返回 if self._queue.isEmpty(): return else: # 不为空, 将队头顾客提升为当前顾客 self._current_customer = self._queue.pop() # 等待总时间加上当前顾客等待的时间 self._total_customer_wait_time += \ current_time - \ self._current_customer.arrival_time() self._customers_served += 1 # 2. 给当前顾客一个单位服务 self._current_customer.serve() # 如果当前顾客需要的单位服务已经满足, 则将当前顾客赋值为 None if self._current_customer.amount_of_service_needed() == 0: self._current_customer = None def __str__(self): """ Returns my results: my total customers served, my average wait time per customer, and customers left on my queue. """ result = "TOTALS FOR THE CASHIER\n" + \ "Number of customers served: " + \ str(self._customers_served) + "\n" if self._customers_served != 0: ave_wait_time = self._total_customer_wait_time /\ self._customers_served result += "Number of customers left in queue: " + \ str(len(self._queue)) + "\n" + \ "Average time customers spend\n" + \ "waiting to be served: " + \ "%5.2f" % ave_wait_time return result
def add(self, item): """Adds item to its proper place in the queue.""" if self.isEmpty() or item >= self._rear.data: LinkedQueue.add(self, item) else: probe = self._front trailer = None while item >= probe.data: trailer = probe probe = probe.next newNode = Node(item, probe) if trailer is None: self._front = newNode else: trailer.next = newNode self._size += 1
def breadthFirst(g, startLabel): """Returns a list of the vertex labels in the order in which the vertices were visited.""" result = list() g.clearVertexMarks() queue = LinkedQueue() queue.add(g.getVertex(startLabel)) while not queue.isEmpty(): vertex = queue.pop() if not vertex.isMarked(): vertex.setMark() result.append(vertex.getLabel()) for neighbor in g.neighboringVertices(vertex.getLabel()): if not neighbor.isMarked(): queue.add(neighbor) return result
def add(self, item): """Adds item to its proper place in the queue.""" if self.isEmpty() or item >= self.rear.data: LinkedQueue.add(self, item) else: probe = self.front trailer = None while item >= probe.data: trailer = probe probe = probe.next newNode = Node(item, probe) if trailer is None: self.front = newNode else: trailer.next = newNode self.size += 1
def levelorder(self): """Supports a levelorder traversal on a view of self.""" lyst = list() # need a first in first out order, so use LinkedQueue # add self._root to get while loop started nodeStack = LinkedQueue([self._root]) while nodeStack: currentNode = nodeStack.pop() lyst.append(currentNode.data) if currentNode.left: nodeStack.add(currentNode.left) if currentNode.right: nodeStack.add(currentNode.right) return iter(lyst)
class Cashier(object): def __init__(self): """ """ self._totalCustomerWaitTime = 0 self._customersServed = 0 self._currentCustomer = None self._queue = LinkedQueue() def addCustomer(self, c): self._queue.add(c) def serveCustomers(self, currentTime): """ :param currentTime: :type currentTime: :return: :rtype: """ if self._currentCustomer is None: # No customers yet if self._queue.isEmpty(): return else: # Pop first waiting customer and tally results self._currentCustomer = self._queue.pop() self._totalCustomerWaitTime += currentTime - self._currentCustomer.arrivalTime( ) self._customersServed += 1 # Give a unit of service self._currentCustomer.serve() # If current customer is finished, send it away if self._currentCustomer.amountOfServiceNeeded() == 0: self._currentCustomer = None def __str__(self): result = "TOTALS FOR THE CASHIER\n" + "Number of customers served: " + \ str(self._customersServed) + "\n" if self._customersServed != 0: aveWaitTime = self._totalCustomerWaitTime / self._customersServed result += "Number of customers left in queue: " \ + str(len(self._queue)) + "\n" + "Average time customers spend\n" + \ "waiting to be served: " + "%5.2f" % aveWaitTime return result
def levelorder(self): """Supports a levelorder traversal on a view of self.""" lyst = list() queue = LinkedQueue() def recurse(): if not queue.isEmpty(): node = queue.pop() lyst.append(node.data) if node.left != None: queue.add(node.left) if node.right != None: queue.add(node.right) recurse() if not self.isEmpty(): queue.add(self._root) recurse() return iter(lyst)
def levelorder(self): """Supports a levelorder traversal on a view of self.""" our_list = [] our_queue = LinkedQueue() def recurse(): if not our_queue.isEmpty(): node = our_queue.pop() our_list.append(node.data) if node.left is not None: our_queue.add(node.left) if node.right is not None: our_queue.add(node.right) recurse() if not self.isEmpty(): our_queue.add(self._root) recurse() return iter(our_list)
def add(self, new_item): """重写超类的add方法""" if self.isEmpty() or new_item >= self._rear.data: # 添加到队尾 LinkedQueue.add(self, new_item) else: # 遍历队列, 根据优先级插入 probe = self._front while new_item >= probe.data: tailer = probe # 当前probe节点的上一个节点 probe = probe.next new_node = Node(new_item, probe) if probe == self._front: # 只有一个节点 self._front = new_node else: # 多个节点 tailer.next = new_node self._size += 1
def add(self, newItem): """Insert newItem after items of greater or equal priority or ahead of item of lesser priority A has greater priority than B if A <B""" if self.isEmpty() or newItem >= self._rear.data: # New item goes at rear LinkedQueue.add(self, newItem) else: # Search for a position where it's less probe = self._front while newItem >= probe.data: trailer = probe probe = probe.next newNode = Node(newItem, probe) if probe == self._front: #new item does at front self._front = newNode else: # New item goes between two nodes trailer.next = newNode self._size += 1
def add(self, new_item): """重写超类的add方法""" # 在"急症室调度"示例中,data 是patient 对象 if self.isEmpty() or new_item._condition >= self._rear.data._condition: # 添加到队尾 LinkedQueue.add(self, new_item) else: # 遍历队列, 根据优先级插入 probe = self._front # 比较conditio 优先级 while new_item._condition >= probe.data._condition: tailer = probe # 当前probe节点的上一个节点 probe = probe.next new_node = Node(new_item, probe) if probe == self._front: # 只有一个节点 self._front = new_node else: # 多个节点 tailer.next = new_node self._size += 1
class Solution_32b(object): def __init__(self): self.queue = LinkedQueue() def print_tree(self, treeroot): if treeroot is None: return self.queue.add(treeroot) nextlevel, tobeprinted = 0, 1 print('Print the tree structure by level.') while not self.queue.isEmpty(): pnode = self.queue.peek() print('%d' % pnode.data_, end=' | ') if pnode.left_ is not None: self.queue.add(pnode.left_) nextlevel += 1 if pnode.right_ is not None: self.queue.add(pnode.right_) nextlevel += 1 self.queue.pop() tobeprinted -= 1 if tobeprinted == 0: print('\n') tobeprinted = nextlevel nextlevel = 0
class Memory(object): def __init__(self, numOfPlayers=2): self._numOfPlayers = numOfPlayers self._totalScore = 0 self._deck = Deck() self._queue = LinkedQueue() for player in range(self._numOfPlayers): self._queue.add(Player('Player ' + str(player + 1))) self._currentPlayer = self._queue.pop() def getPlayerName(self): return self._currentPlayer.getName() def setPlayerName(self, name): """sets current player name""" self._currentPlayer.setName(name) def addPlayerScore(self, points): """adds points to current player""" if self._totalScore + points > 30: while self._totalScore < 30: self._currentPlayer.addToScore(1) self._totalScore += 1 elif self._currentPlayer.getScore() + points >= 0: self._currentPlayer.addToScore(points) self._totalScore += points def nextPlayer(self): """moves to next player and puts previous player to back of queue""" self._queue.add(self._currentPlayer) self._currentPlayer = self._queue.pop() def checkGameOver(self): """checks if point add to 30""" if self._totalScore >= 30: return True return False def playerHigh(self): """finds player with high score""" for player in range(self._numOfPlayers): temp = self._queue.pop() if temp.getScore() > self._currentPlayer.getScore(): self._queue.add(self._currentPlayer) self._currentPlayer = temp else: self._queue.add(temp) return self._currentPlayer.getName()
class Solution_32(object): def __init__(self): self.queue = LinkedQueue() def printfromtoptobottom(self, treeroot): if treeroot is None: return None self.queue.add(treeroot) ret = [] while not self.queue.isEmpty(): node = self.queue.pop() ret.append(node.data_) if node.left_: self.queue.add(node.left_) if node.right_: self.queue.add(node.right_) return ret
class Stack(object): def __init__(self): self.stack1 = LinkedQueue() self.stack2 = LinkedQueue() def isEmpty(self): if self.__len__() == 0: return True else: return False def __len__(self): if self.stack1.size_ == 0: return self.stack2.size_ else: return self.stack1.size_ def peek(self): if self.isEmpty(): raise KeyError('The stack is empty.') elif not self.stack1.isEmpty(): item = self.stack1.peek() return item else: item = self.stack2.peek() return item def push(self, item): if self.isEmpty() or (not self.stack1.isEmpty() and self.stack2.isEmpty()): self.stack1.add(item) else: self.stack2.add(item) def pop(self): if self.isEmpty(): raise KeyError('The stack is empty.') if not self.stack1.isEmpty(): while self.stack1.front_.next is not None: self.stack2.add(self.stack1.pop()) item = self.stack1.pop() return item else: while self.stack2.front_.next is not None: self.stack1.add(self.stack2.pop()) item = self.stack2.pop() return item # def __iter__(self): # def travser_stack_recursive(sta, templist): # if sta.front_.next is not None: # templist = travser_stack_recursive(sta.front_.next, templist) # templist.append(sta.front_.data) # return templist # # templist = list() # if self.isEmpty(): # raise KeyError('The stack is empty.') # # if not self.stack1.isEmpty(): # travser_stack_recursive(self.stack1, templist) # return iter(templist) # else: # travser_stack_recursive(self.stack2, templist) # return iter(templist) def __iter__(self): if self.isEmpty(): raise KeyError('The stack is empty.') templist = list() if not self.stack1.isEmpty(): tempstack = copy.copy(self.stack1) while tempstack.front_.next is not None: templist.append(tempstack.pop()) templist.append(tempstack.pop()) templist.reverse() # ****** return iter(templist) else: tempstack = copy.copy(self.stack2) while tempstack.front_.next is not None: templist.append(tempstack.pop()) templist.append(tempstack.pop()).reverse() templist.reverse() # ****** return iter(templist)
import unittest from linkedqueue import LinkedQueue q = LinkedQueue() for i in range(7): q.add(i + 1) class UnitTests(unittest.TestCase): def test_unit_test(self): self.assertEqual(len(q), 7) q.clear() self.assertEqual(len(q), 0)
def stack_to_queue(StackObj): """ takes a stack and transformes it to queue""" queue = LinkedQueue() for el in StackObj: queue.add(el) return queue
class TravelPlan: """This class creates travel plan.""" def __init__(self, data1, data2, summary): """This method initializes.""" self.data1 = data1 self.data2 = data2 self.summary = summary self.queue = LinkedQueue() self.total_food = 0 self.total_transport = 0 self.extrainfo = "" self.see = "" def city_block(self): """This methods creates travel plan, including all flights, transit cities, final city, info about prices, transport and summary about travel total cost, links and ex. And add all of them to quque.""" lst = [] self.data2.append("Summary") print("Building your route...") print(self.data1[0][2]) lst.append(self.data1[0][2]) for i, city in zip(self.data1, self.data2): self.queue.add("\nfrom {} to {}\n{} ==> {}".\ format(i[2], i[3], i[1], i[0])) st = "" if city == "Summary": print(self.data1[0][2]) lst.append(self.data1[0][2]) self.queue.add("\n" + city) self.summary_result() self.visualisation() return self.queue, lst print(city[0]) lst.append(city[0]) st = "\n" + city[0] + "\n" + city[1][0][0:-3] + " ==> " \ + city[1][1][0:-3] + "\n" + "Total time: " + city[2][0:-3] + \ " hours" if city[3]: visit = ThingsToVisit(city[0]) st += "\nMost popular things to do in " + city[0] + ":" + "\n" \ + "\n".join(visit.find_attractions()) self.see += visit.link() + "\n" cost0 = CostOfLiving(city[0]) cost = cost0.estimate_food_expences(city[4]) self.total_food += cost[0] st += "\nCost of food in " + city[0] + ":" + \ "\nPrice of products for cooking: " + str(cost[0]) + "€\n" + \ "Price in MacDonald's: " + str(cost[1]) + "€" + \ "\nPrice in inexpensive restaurants: " + str(cost[2]) + "€" + \ "\nPrice in mid range restaurants: " + str(cost[3]) + "€" self.extrainfo += "\nPrice list in " + city[0] + ":\n"+ \ cost0.additional() tr = cost0.estimate_transport_expences(city[4]) self.total_transport += tr st += "\nCost of transport: " + str(tr) + "€" st += "\nAccommodation: visit https://www.couchsurfing.com/ \ for free stay." else: st += "\nWaiting in airport, not enough time to visit \ this city." self.queue.add(st) def summary_result(self): """This method creates summary about trip.""" sum_st = "\nMinimal budget for trip:\n1) Flights price: {}€\n2) Food \ expences: {}€\n3) Transport expences: {}€\n4) Accommodation expences: 0€\nTota\ l: {}€\n\nDetail food costs:\n{}\nThings to see links:\n{}\nFlight booking \ link1:\n{}\n\nFlight booking link2:\n{}".format(self.summary[0],\ round(self.total_food, 2), round(self.total_transport, 2), \ round(self.summary[0] + self.total_food + self.total_transport, 2),\ self.extrainfo, self.see, self.summary[1][0:62], self.summary[2][0:62]) self.queue.add(sum_st) def visualisation(self): """This method creates total expenxes visualisation.""" objects = ('Flights', 'Food', 'Transport', 'Accommodation') y_pos = np.arange(len(objects)) performance = [self.summary[0], self.total_food, self.total_transport, 0] plt.bar(y_pos, performance, align='center', alpha=0.5) plt.xticks(y_pos, objects) plt.ylabel('Price in €') plt.title('Minimal budget for trip') plt.savefig('static/visual.png')
class MemoryGUI(Frame): def __init__(self): Frame.__init__(self) self.master.title("Memory") self.grid() self._gridOfPictures = ArrayGrid(5, 5) self._gridOfCards = ArrayGrid(5, 5) self._gridOfButtons = ArrayGrid(5, 5) """pane that will contain the buttons thourghout the program""" self._mainPane = Frame(self) self._mainPane.grid(row=0, column=0) """info pane will hold scores and a button to start new game""" self._infoPane = Frame(self) self._infoPane.grid(row=0, column=1) """create buttons for opening screen""" self._buttonImage2 = PhotoImage(file='CARDS/2player.gif') self._2PlayerButton = Button(self._mainPane, image=self._buttonImage2, command=self._button2) self._2PlayerButton.grid(row=0, column=0) self._buttonImage3 = PhotoImage(file='CARDS/3player.gif') self._3PlayerButton = Button(self._mainPane, image=self._buttonImage3, command=self._button3) self._3PlayerButton.grid(row=0, column=1) self._buttonImage4 = PhotoImage(file='CARDS/4player.gif') self._4PlayerButton = Button(self._mainPane, image=self._buttonImage4, command=self._button4) self._4PlayerButton.grid(row=1, column=0) self._buttonImage5 = PhotoImage(file='CARDS/5player.gif') self._5PlayerButton = Button(self._mainPane, image=self._buttonImage5, command=self._button5) self._5PlayerButton.grid(row=1, column=1) def _button2(self): self._mainButtons(2) def _button3(self): self._mainButtons(3) def _button4(self): self._mainButtons(4) def _button5(self): self._mainButtons(5) def _mainButtons(self, numOfPlayers): """create all the buttons""" self._numberOfPlayers = numOfPlayers self._2PlayerButton.grid_forget() self._3PlayerButton.grid_forget() self._4PlayerButton.grid_forget() self._5PlayerButton.grid_forget() self._memory = Memory(numOfPlayers) self._listOfPressed = [] for x in range(5): for y in range(5): self._gridOfCards[x][y] = self._memory._deck.deal() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) x = 0 y = 0 self._cardButton1 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress1) self._cardButton1.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton1 y += 1 self._cardButton2 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress2) self._cardButton2.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton2 y += 1 self._cardButton3 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress3) self._cardButton3.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton3 y += 1 self._cardButton4 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress4) self._cardButton4.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton4 y += 1 self._cardButton5 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress5) self._cardButton5.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton5 y = 0 x += 1 self._cardButton6 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress6) self._cardButton6.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton6 y += 1 self._cardButton7 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress7) self._cardButton7.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton7 y += 1 self._cardButton8 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress8) self._cardButton8.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton8 y += 1 self._cardButton9 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress9) self._cardButton9.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton9 y += 1 self._cardButton10 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress10) self._cardButton10.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton10 y = 0 x += 1 self._cardButton11 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress11) self._cardButton11.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton11 y += 1 self._cardButton12 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress12) self._cardButton12.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton12 y += 1 self._cardButton13 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress13) self._cardButton13.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton13 y += 1 self._cardButton14 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress14) self._cardButton14.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton14 y += 1 self._cardButton15 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress15) self._cardButton15.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton15 y = 0 x += 1 self._cardButton16 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress16) self._cardButton16.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton16 y += 1 self._cardButton17 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress17) self._cardButton17.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton17 y += 1 self._cardButton18 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress18) self._cardButton18.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton18 y += 1 self._cardButton19 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress19) self._cardButton19.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton19 y += 1 self._cardButton20 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress20) self._cardButton20.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton20 y = 0 x += 1 self._cardButton21 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress21) self._cardButton21.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton21 y += 1 self._cardButton22 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress22) self._cardButton22.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton22 y += 1 self._cardButton23 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress23) self._cardButton23.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton23 y += 1 self._cardButton24 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress24) self._cardButton24.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton24 y += 1 self._cardButton25 = Button(self._mainPane, image=self._gridOfPictures[x][y], command=self._cardButtonPress25) self._cardButton25.grid(row=x, column=y) self._gridOfButtons[x][y] = self._cardButton25 """adding labels and buttons to info pane""" self._playerLabelQueue = LinkedQueue() for label in range(numOfPlayers): self._playerScore = Label(self._infoPane, text='Player ' + str(label + 1) + ': 0') self._playerScore.grid(row=label + 2, column=0) self._playerLabelQueue.add(self._playerScore) self._currentLabel = self._playerLabelQueue.pop() self._rulesButton = Button(self._infoPane, text='Rules', command=self._rules) self._rulesButton.grid(row=0, column=0) self._resetButton = Button(self._infoPane, text='New Game', command=self._reset) self._resetButton.grid(row=1, column=0) self._popupMsg('Player 1 turn') def _reset(self): self._mainButtons(self._numberOfPlayers) def _rules(self): messagebox.showinfo( "Rules", '1. The first player turns over 2 cards, looking for matching cards. If the two Treasures match, turn over another card to try to find an additional match, Keep going until you do not find a matching card. \n2. For each matching card uncovered, he or she is rewarded with 1 point! \n3. If a player turns up a headstone that he or she wasnt looking for, he or she looses his or her turn and must give 1 point back unless player has none. \n4. When a player finds a non-matching card, or a headstone, the cards are turned face down except for the last card that was found, which is kept face up. \n5. Play continues with the next player trying to find a match for the card that is face up. \n6. Continue until the total of all players points add up to 30.' ) def _cardButtonPress1(self): x = 0 y = 0 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress2(self): x = 0 y = 1 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress3(self): x = 0 y = 2 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress4(self): x = 0 y = 3 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress5(self): x = 0 y = 4 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress6(self): x = 1 y = 0 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress7(self): x = 1 y = 1 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress8(self): x = 1 y = 2 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress9(self): x = 1 y = 3 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress10(self): x = 1 y = 4 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress11(self): x = 2 y = 0 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress12(self): x = 2 y = 1 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress13(self): x = 2 y = 2 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress14(self): x = 2 y = 3 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress15(self): x = 2 y = 4 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress16(self): x = 3 y = 0 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress17(self): x = 3 y = 1 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress18(self): x = 3 y = 2 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress19(self): x = 3 y = 3 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress20(self): x = 3 y = 4 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress21(self): x = 4 y = 0 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress22(self): x = 4 y = 1 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress23(self): x = 4 y = 2 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress24(self): x = 4 y = 3 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonPress25(self): x = 4 y = 4 if tuple([x, y]) not in self._listOfPressed: self._listOfPressed.append(tuple([x, y])) self._gridOfCards[x][y].turn() self._gridOfPictures[x][y] = PhotoImage( file=self._gridOfCards[x][y].getCardFileName()) self._gridOfButtons[x][y].config(image=self._gridOfPictures[x][y]) self._cardButtonMain() def _cardButtonMain(self): """checks if card is the same as last""" if len(self._listOfPressed) > 1: x, y = self._listOfPressed[-1] x1, y1 = self._listOfPressed[-2] if str(self._gridOfCards[x][y]) != str(self._gridOfCards[x1][y1]): if str(self._gridOfCards[x][y]) == 'Headstone': """-1 point if you turned over a headstone""" self._memory.addPlayerScore(-1) elif len(self._listOfPressed) > 2: self._memory.addPlayerScore(len(self._listOfPressed) - 1) if self._memory.checkGameOver(): self._resetButtons() self._popupMsg( str(self._memory.playerHigh() + ' Won', True)) if not self._memory.checkGameOver(): self._resetButtons(tuple([x, y])) self._currentLabel[ 'text'] = self._memory._currentPlayer.getName( ) + ': ' + str(self._memory._currentPlayer.getScore()) self._playerLabelQueue.add(self._currentLabel) self._currentLabel = self._playerLabelQueue.pop() self._memory.nextPlayer() self._popupMsg( str(self._memory._currentPlayer.getName() + ' Turn')) if self._memory.checkGameOver(): self._mainButtons(self._numberOfPlayers) def _resetButtons(self, xy=tuple([5, 5])): """resets buttons but leaves last one pressed untuched""" for xandy in self._listOfPressed[::-1]: x1, y1 = xandy if xy != xandy: self._gridOfCards[x1][y1].turn() self._gridOfButtons[x1][y1].state = 'Normal' self._gridOfPictures[x1][y1] = PhotoImage( file=self._gridOfCards[x1][y1].getCardFileName()) self._gridOfButtons[x1][y1].config( image=self._gridOfPictures[x1][y1]) self._listOfPressed.remove(xandy) def _popupMsg(self, msg, done=False): messagebox.showinfo("Information", msg)