#!/usr/bin/python # CSE 143 Python session #2 (objects) # Author: David Mailhot # # This provided main program uses your TreasureManager class. # It displays a DrawingPanel, reads from a txt file of treasures, and # randomly 'buries' them as Treasure objects by adding them to your # manager. It also listens for mouse clicks, notifying # your rectangle manager when the mouse buttons are pressed. # # A left-click 'digs' a hole and reveals any buried treasures in the area. # A right-click (or a Ctrl-left-click for Mac people) on a found treasure # displays the contents of that treasure. from drawingpanel import * from random import * from treasure import * from treasuremanager import * # constants for the drawing panel size, rectangle sizes, and # of rects FILE = "bootylist.txt" WIDTH = 400 HEIGHT = 400 DIRT = 50 MIN_SIZE = 15 MAX_SIZE = 20 manager = TreasureManager() panel = DrawingPanel(WIDTH, HEIGHT) # functions to respond to mouse events def event_handler2(event): event_handler(event, True) def event_handler(event, right=False): shift = event.state & 0x001 != 0 ctrl = event.state & 0x004 != 0 # ctrl-click ~= right-click (Mac) right = right or ctrl print("Arr, we dug at x=" + str(event.x) + ", y=" + str(event.y)) #+ ", right=" + str(right) + ", shift=" + str(shift) + ", ctrl=" + str(ctrl) + ", state=" + str(event.state)) if right: manager.open_treasure(event.x, event.y) else: manager.dig(event.x, event.y) # draw the background of the game panel.clear() panel.canvas.create_rectangle(0, DIRT, WIDTH, HEIGHT, fill="brown") # repaint any revealed treasures manager.draw_all(panel) # main # create treasures for each line in the input file and put them into a manager for line in open(FILE): w = randint(MIN_SIZE, MAX_SIZE) # random coordinates h = randint(MIN_SIZE, MAX_SIZE) x = randint(0, WIDTH - w - 1) y = randint(DIRT, HEIGHT - h - 1) r = randint(0, 255) # random color g = randint(0, 255) b = randint(0, 255) color = ("#%02x%02x%02x" % (r, g, b)) # print("treasure at x=" + str(x) + ", y=" + str(y)) for debugging # add random treasure to manager chest = Treasure(x, y, w, h, color, line.strip()) # strip removes \n manager.add_treasure(chest) # draw the panel first panel.canvas.create_rectangle(0, DIRT, WIDTH, HEIGHT, fill="brown") # listen for mouse clicks panel.canvas.bind("", event_handler) panel.canvas.bind("", event_handler2) panel.canvas.bind("", event_handler2) panel.mainloop()