def __init__(self, screen, bg_color=(0, 0, 0), font=None, font_size=35, font_color=(255, 255, 255)): """Set up all variables, choose colors and fonts and preparing list of items in menu with functions which them called""" self.screen = screen self.scr_width = self.screen.get_rect().width self.scr_height = self.screen.get_rect().height self.bg_color = bg_color self.clock = pygame.time.Clock() self.font = pygame.font.SysFont(font, font_size) self.font_color = font_color self.items = [] self.funcs = OrderedDict() self.funcs["Start Game"] = self.startgame self.funcs["Instruction"] = self.instruction self.funcs["Authors"] = self.showauthors self.funcs["Quit"] = sys.exit items = self.funcs.keys() for index, item in enumerate(items): menu_item = MenuItem(item) t_h = len(items) * menu_item.height pos_x = (self.scr_width / 2) - (menu_item.width / 2) pos_y = (self.scr_height / 2) - (t_h / 2) + ( (index * 2) + index * menu_item.height) menu_item.set_position(pos_x, pos_y) self.items.append(menu_item) self.mouse_is_visible = True self.cur_item = None
def __init__(self, screen, bg_color=(0, 0, 0), font=None, font_size=35, font_color=(255, 255, 255)): """set up all variables, prepare basic navigation""" self.screen = screen self.scr_width = self.screen.get_rect().width self.scr_height = self.screen.get_rect().height self.bg_color = bg_color self.clock = pygame.time.Clock() self.font = pygame.font.SysFont(font, font_size) self.font_color = font_color self.items = [] self.funcs = OrderedDict() self.text_color = (255, 255, 255) self.funcs["Back"] = self.menu self.funcs["Quit"] = sys.exit items = self.funcs.keys() for index, item in enumerate(items): menu_item = MenuItem(item) t_h = len(items) * menu_item.height pos_x = (self.scr_width / 2) - (menu_item.width / 2) pos_y = (self.scr_height / 2) - (t_h / 2) + ( (index * 2) + index * menu_item.height) + 120 menu_item.set_position(pos_x, pos_y) self.items.append(menu_item) self.mouse_is_visible = True self.cur_item = None self.text_wall = TextWall() self.text_wall.parse_text(instruction_text)
def updateMenuItems(self): self.menu_items = [] # Store keys in an array to fix order and make easier to identify selected key for this_key in self.game_controls.getKeys(): self.menu_items.append(MenuItem(this_key+" ("+str(self.game_controls.getKeyString(this_key))+")", this_key, 'control')) # Dummy entry - blank line self.menu_items.append(MenuItem("","","controls")) # Last Menu item is to save and return self.menu_items.append(MenuItem("Save settings", 'save', 'menu'))
class MenuItemTest (unittest.TestCase): def setUp(self): self.menuitem = MenuItem('Small',"Burger",3.00,2) def test_GetItemSize(self): self.assertEqual(self.menuitem.getItemSize(), 'small') def test_GetItemName(self): self.assertEqual(self.menuitem.getItemName(), 'Burger') def test_GetItemPrice(self): self.assertEqual(self.menuitem.getItemPrice(), 3.00) def test_GetItemQuantity(self): self.assertEqual(self.menuitem.getItemQuantity(), 2)
class OrderItemTest(unittest.TestCase): def setUp(self): self.item = MenuItem(15, 'Cheeseburger', 'Large', 3.79) def test_GetItemName(self): self.assertEqual(self.item.getItemName(), 'Cheeseburger') def test_GetItemID(self): self.assertEqual(self.item.getItemID(), 15) def test_GetItemSize(self): self.assertEqual(self.item.getItemSize(), 'Large') def test_GetItemPrice(self): self.assertEqual(self.item.getItemPrice(), 3.79)
def createMenu(callback): """Displays 6 menu items to respond to the given callback function.""" x = -(window_width() / 2) + INDENT y = START_Y colors = ("red", "green", "blue", "yellow", "purple", "black") shape = "circle" for color in colors: MenuItem(x, y, shape, color, callback) y -= ITEM_SPACE
def add_item(self, desktop_entry): if desktop_entry.has_option_default('NoDisplay') and desktop_entry.no_display: return item = MenuItem(desktop_entry) item.connect('button-release-event', self.button_release_cb) item.show() if self.single_columned: self.layout.pack_start(item, False, True) else: if self.wrapper_children == 2: self.wrapper = gtk.HBox() self.layout.pack_start(self.wrapper, False, True) self.wrapper_children = 0 self.wrapper.pack_start(item, False, True) self.wrapper_children += 1
class InventoryTest(unittest.TestCase): def setUp(self): self.menuitem = MenuItem(1, 'item1', 1.50) self.orderitem = OrderItem(self.item, 1) def test_Quantity(self): self.assertEqual(self.menuitem.getQuantity(), 2) def test_item(self): item = self.orderitem.getItem() self.assertEqual(str(item), 'item1')
def main(): item1 = Menu(1, 'fries', 2.25) item2 = Menu(2, 'cookies', 4.43) item3 = Menu(3, 'Cheese Burger', 2.45) inventory = Inventory() inventory.addItem(item1) inventory.addItem(item2) inventory.addItem(item3) orderitem1 = MenuItem(inventory.getItemByNumber(1), 1) orderitem2 = MenuItem(inventory.getItemByNumber(2), 2) orderitem3 = MenuItem(inventory.getItemByNumber(3), 1) order = OrderTotal() order.addOrderItems(orderitem1) order.addOrderItems(orderitem2) order.addOrderItems(orderitem3) payment = order.calcTotal() print(payment)
def init(self, **kws): # request some surface space from the parent. X, Y = SCREEN_SIZE self.surface = self.parent.reserve(child=self, topleft=(X/2 - 50, Y/2 - 50), size=(100, 100)) self.events = Queue.Queue() self.parent.listen(self, (KEYDOWN, MOUSEBUTTONDOWN)) self.surface.fill(WHITE) buttons = ['Play Game!', 'Exit Game!'] self.buttons = pygame.sprite.Group() # set up the buttons. play = MenuItem(parent=self, controller=self.controller, text=buttons[0], containers=[self.buttons]) play.topleft = (20, 20) quit_ = MenuItem(parent=self, controller=self.controller, text=buttons[1], containers=[self.buttons]) quit_.topleft = (20, 60) # bind button state to an event. self.bind('button', self.on_play, play) self.bind('button', self.on_quit, quit_)
def init(self, levels, prev=None, **kws): X, Y = SCREEN_SIZE w, h = (100, 300) # topleft. x, y = ((X - w) / 2, (Y - h) / 2) self.surface = self.parent.reserve(child=self, topleft=(x, y), size=(w,h)) self.parent.listen(self, (KEYDOWN, MOUSEBUTTONDOWN)) self.surface.fill(WHITE) self.buttons = pygame.sprite.Group() self.levels = {} # save the previous menu. self.prev = prev if prev: back = MenuItem(parent=self, controller=self.controller, text='back', containers=[self.buttons]) back.topleft = (20, 20) self.bind('button', self.on_back, back) h = 60 else: h = 20 # set up each of the buttons. for level in levels: b = MenuItem(parent=self, controller=self.controller, text=level.name, containers=[self.buttons], maxwidth=10) b.topleft = (20, h) h += b.size[1] + 20 self.bind('button', self.on_button, b) # now map the button to the level. self.levels[id(b)] = level # add a select button. select = MenuItem(parent=self, controller=self.controller, text='ok!', containers=[self.buttons]) select.topleft = (20, h) self.bind('select_level', self.on_select, select) # description boxes. self.active_desc = 'None'
def add_item(self, desktop_entry): if desktop_entry.has_option_default( 'NoDisplay') and desktop_entry.no_display: return item = MenuItem(desktop_entry) item.connect('button-release-event', self.button_release_cb) item.show() if self.single_columned: self.layout.pack_start(item, False, True) else: if self.wrapper_children == 2: self.wrapper = gtk.HBox() self.layout.pack_start(self.wrapper, False, True) self.wrapper_children = 0 self.wrapper.pack_start(item, False, True) self.wrapper_children += 1
def setUp(self): self.item = MenuItem(15, 'Cheeseburger', 'Large', 3.79)
from setmenu import SetMenu from menuitem import MenuItem menuItem1 = MenuItem('Chicken Popcorn', 98, 4.1) menuItem2 = MenuItem('Zinger Burger', 258, 4.6) menuItem3 = MenuItem('Chicken Pizza', 298, 4.0) menuItem4 = MenuItem('Lime Krusher', 75, 4.3) menuItem5 = MenuItem('Chicken Popcorn', 60, 4.1) menuItem6 = MenuItem('Chicken Popcorn', 60, 4.1) print(menuItem1) print(menuItem1 == menuItem5) print(menuItem5 == menuItem6) setmenu = SetMenu( [menuItem1, menuItem2, menuItem3, menuItem4, menuItem5, menuItem6]) print(len(setmenu)) print(setmenu) sortedList = sorted(setmenu.menuitems, reverse=True) for element in sortedList: print(element)
def setUp(self): self.menuitem = MenuItem('Small',"Burger",3.00,2)
if item.isText: item.font.render_to(screen, item.pos, item.text) else: screen.blit(item.image) def update(self, screen): self.render(screen) for layer in self.layers: layer.update(screen) # GAME-SPECIFIC #TODO mmSinglePlayer = MenuItem(pos=(0.43 * 1280, 0.395 * 720), itemid=1, text="1 PLAYER", font=pg.freetype.Font(graphic.fontArcade, size=24), hlSound=sound.menuSelect) mmOnline = MenuItem(pos=(0.43 * 1280, 0.465 * 720), itemid=2, text="ONLINE", font=pg.freetype.Font(graphic.fontArcade, size=24), hlSound=sound.menuSelect) mmEditMode = MenuItem(pos=(0.43 * 1280, 0.535 * 720), itemid=3, text="EDIT MODE", font=pg.freetype.Font(graphic.fontArcade, size=24), hlSound=sound.menuSelect) mmOptions = MenuItem(pos=(0.43 * 1280, 0.605 * 720), itemid=4, text="OPTIONS",
ITEM_LEVEL_SELECT = "LEVEL_SELECT" ITEM_OPTIONS = "OPTIONS" ITEM_EXIT = "EXIT" # difficulty ITEM_EASY = "EASY" ITEM_MEDIUM = "MEDIUM" ITEM_HARD = "HARD" # levels ITEM_LEVEL_1 = "LEVEL_1" ITEM_LEVEL_2 = "LEVEL_2" ITEM_BONUS_LEVEL = "BONUS_LEVEL" top_menu = [ MenuItem("New Game", ITEM_NEW_GAME), MenuItem("Level Select", ITEM_LEVEL_SELECT), MenuItem("Options", ITEM_OPTIONS), MenuItem("Exit", ITEM_EXIT) ] difficulty_menu = [ MenuItem("Easy", ITEM_EASY), MenuItem("Medium", ITEM_MEDIUM), MenuItem("Hard", ITEM_HARD) ] level_select_menu = [ MenuItem("Level 1", ITEM_LEVEL_1), MenuItem("Level 2", ITEM_LEVEL_2), MenuItem("Bonus Level", ITEM_BONUS_LEVEL)
def setUp(self): self.menuitem = MenuItem(1, 'item1', 1.50) self.orderitem = OrderItem(self.item, 1)
class GameMenu: # Menu item details, perhaps consider putting this in a configuration # file in future menu_items = [ MenuItem('Start game', 'start', 'command'), MenuItem('Instructions', 'instructions', 'textpage'), MenuItem('Customize character', 'character', 'subcommand'), MenuItem('Game controls', 'controls', 'subcommand'), MenuItem('View high scores', 'highscore', 'subcommand'), MenuItem('Credits', 'credits', 'textpage'), MenuItem('Quit', 'quit', 'command') ] # Dictionary of text pages for menu entries # Note currently no word wrapping - needs \n to be added in advance menu_pages = { 'instructions':"INSTRUCTIONS\n\nFollow the direction at the top centre\nof the screen.\n\nMove the character using a joystick (Picade)\n or cursor keys (keyboard).\nPress top button or SPACE to duck\nPress RIGHT SHIFT to view the map\n\nAvoid the obstacles that appear on later levels\n", 'credits':"CREDITS\n\nCreate by Stewart Watkiss\nMade available under GPL v3 License\nSee: www.penguintutor.com/compassgame" } menu_spacing = 50 # distance between menu items top_spacing = 20 # distance between top of menu and start of menu left_spacing = 20 # distance between left and text for page text / command text menu_font_size = 45 # size of font for menu items menu_font_page = 32 # size of font for text page display status = STATUS_MENU # Track whether to display menu or in menu etc. # Requires width and height - these can be the same as the screen or smaller if need to constrain menu # Offset and border determine distance from origin of screen and any fixed area to avoid respectively def __init__(self, game_controls, width, height, offset=(0,0), border=100): self.game_controls = game_controls self.width = width # width of screen self.height = height # height of screen self.offset = offset # tuple x,y for offset from start of screen self.border = border # single value same for x and y # Start position of the menu area and size self.start_pos = (self.offset[0]+self.border, self.offset[1]+self.border) self.size = (self.width-2*self.start_pos[0], self.height-2*self.start_pos[1]) # Create a menu surface - this involves using pygame surface feature (rather than through pygame zero) # Allows for more advanced features such as alpha adjustment (partial transparency) self.menu_surface = Surface(self.size) # 75% opacity self.menu_surface.set_alpha(192) # Position of rect is 0,0 relative to the surface, not the screen self.menu_box = Rect((0,0),self.size) # Uses pygame rect so we can add it to own surface self.menu_rect = pygame.draw.rect(self.menu_surface , (200,200,200), self.menu_box) self.menu_pos = 0 # Tracks which menu item is selected # Timer restrict keyboard movements to prevent multiple presses self.menu_timer = Timer(0.12) # Finish setting up MenuItems # At the moment this doesn't provide much extra functionality, but by # placing it into the MenuItem object then makes it easier if we load # MenuItems from a configuration file in future for i in range (0,len(self.menu_items)): if self.menu_items[i].getCommand() in self.menu_pages: self.menu_items[i].setPage(self.menu_pages[self.menu_items[i].getCommand()]) # Update menu based on keyboard direction # If return is 'menu' then still in menu, so don't update anything else # If return is 'quit' then quit the application # Any other return is next instruction def update(self, keyboard): # set status_selected if menu status changed (through mouse click or press) selected_command_type = "" selected_command = "" # check if status is clicked - which means mouse was pressed on a valid entry if (self.status == STATUS_CLICKED): selected_command_type = self.menu_items[self.menu_pos].getMenuType() selected_command = self.menu_items[self.menu_pos].getCommand() self.status = STATUS_MENU # check if we are in menu timer in which case return until expired elif (self.menu_timer.getTimeRemaining() > 0): return 'menu' elif (self.game_controls.isPressed(keyboard,'up') and self.menu_pos>0): if (self.status == STATUS_MENU): self.menu_pos -= 1 self.menu_timer.startCountDown() elif (self.game_controls.isPressed(keyboard,'down') and self.menu_pos<len(self.menu_items)-1): if (self.status == STATUS_MENU): self.menu_pos += 1 self.menu_timer.startCountDown() elif (self.game_controls.isOrPressed(keyboard,['jump','duck'])): if (self.status == STATUS_MENU): selected_command_type = self.menu_items[self.menu_pos].getMenuType() selected_command = self.menu_items[self.menu_pos].getCommand() # If click was on text page then return to main menu elif (self.status == STATUS_PAGE): selected_command_type = 'menu' self.status = STATUS_MENU self.menu_timer.startCountDown() elif (self.game_controls.isPressed(keyboard,'escape')): selected_command_type = 'command' selected_command = 'quit' # If a menu object was clicked / chosen then handle if (selected_command_type == 'command'): # Reset menu to start position self.reset() return selected_command elif (selected_command_type == 'textpage'): self.status = STATUS_PAGE self.menu_timer.startCountDown() return 'menu' elif (selected_command_type == 'subcommand'): return selected_command else: return 'menu' def show(self, screen): # Create a rectangle across the area - provides transparancy screen.blit(self.menu_surface,self.start_pos) # draw directly onto the screen draw surface (transparency doesn't apply) if (self.status == STATUS_MENU): self.showMenu(screen) elif (self.status == STATUS_PAGE): self.showPage(screen) def showMenu(self, screen): for menu_num in range (0,len(self.menu_items)): if (menu_num == self.menu_pos): background_color = (255,255,255) else: background_color = None screen.draw.text(self.menu_items[menu_num].getText(), fontsize=self.menu_font_size, midtop=(self.width/2,self.offset[1]+self.border+(self.menu_spacing*menu_num)+self.top_spacing), color=(0,0,0), background=background_color) # Shows a page of text def showPage(self, screen): page_text = self.menu_items[self.menu_pos].getPage() screen.draw.text(page_text, fontsize=self.menu_font_page, topleft=(self.offset[0]+self.border+self.left_spacing,self.offset[1]+self.border+self.top_spacing), color=(0,0,0)) def mouse_move(self, pos): if (self.status == STATUS_MENU): return_val = self.get_mouse_menu_pos(pos) if return_val != -1: self.menu_pos = return_val def mouse_click(self, pos): if (self.status == STATUS_MENU): return_val = self.get_mouse_menu_pos(pos) if return_val != -1: self.menu_pos = return_val self.status = STATUS_CLICKED # If click from text page then return to menu elif (self.status == STATUS_PAGE): self.status = STATUS_MENU def reset(self): self.menu_pos = 0 self.status = STATUS_MENU # Checks if mouse is over menu and if so returns menu position # Otherwise returns -1 def get_mouse_menu_pos (self, pos): if (pos[0] > self.start_pos[0] and pos[1] > self.start_pos[1] + self.top_spacing and pos[0] < self.start_pos[0] + self.size[0] and pos[1] < self.start_pos[1] + self.size[1]): start_y = self.start_pos[1] + self.top_spacing for this_menu_pos in range(0,len(self.menu_items)): if (pos[1] - start_y >= this_menu_pos * self.menu_spacing and pos[1] - start_y <= (this_menu_pos * self.menu_spacing)+self.menu_spacing): return this_menu_pos # If not returned then not over menu return -1