コード例 #1
0
ファイル: game.py プロジェクト: wxy517/space-app-2019
def drawTransitionPage(continueBtnText):
    stayAtThisPage = True
    continueBtn = button(green, width / 3, height * 2 / 3, 120, 50, continueBtnText)
    quitBtn = button(red, width * 2 / 3, height * 2 / 3, 120, 50, 'Close')

    while stayAtThisPage:
        redrawWindow(continueBtn, quitBtn)
        pygame.display.update()

        for event in pygame.event.get():
            pos = pygame.mouse.get_pos()
            if event.type == pygame.QUIT:
                stayAtThisPage = False
                pygame.quit()
                quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if continueBtn.isOver(pos):
                    print("clicked the Button", continueBtnText)
                    stayAtThisPage = False
                elif quitBtn.isOver(pos):
                    print("user decided to quit the game")
                    stayAtThisPage = False
                    pygame.quit()
                    quit()
            if event.type == pygame.MOUSEMOTION:
                if continueBtn.isOver(pos):
                    continueBtn.color = greenDark
                else:
                    continueBtn.color = green
                if quitBtn.isOver(pos):
                    quitBtn.color = redDark
                else:
                    quitBtn.color = red
コード例 #2
0
ファイル: gui.py プロジェクト: Nikittttt/highfrontier
 def createFirmSubcommandbox(self):
     self.buttonlinks = [
         "firm_process_info", "base_and_firm_market_window",
         "firm_trade_partners_info"
     ]
     self.buttonnicenames = ["production", "market", "trade partners"]
     i = 0
     b = button.button("production",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["production"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickFirmProduction)
     i = i + 1
     b = button.button("market",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["market"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickFirmMarket)
     i = i + 1
     b = button.button("trade partners",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["trade partners"] = b
     signaller.connect(b, "signal__clicked",
                       self.slot__clickFirmTradePartners)
     return
コード例 #3
0
def draw_window(yellow, red, yellow_bullets, red_bullets, yellow_health,
                red_health, text, green_col, red_col):
    WIN.blit(SPACE, (0, 0))
    pygame.draw.rect(WIN, BLACK, BORDER)
    red_health_text = HEALTH_FONT.render("Health: " + str(red_health), 1,
                                         WHITE)
    yellow_health_text = HEALTH_FONT.render("Health: " + str(yellow_health), 1,
                                            WHITE)
    WIN.blit(red_health_text, (WIDTH - red_health_text.get_width() - 10, 10))
    WIN.blit(yellow_health_text, (10, 10))
    WIN.blit(YS, (yellow.x, yellow.y))
    WIN.blit(RS, (red.x, red.y))
    for bullet in yellow_bullets:
        pygame.draw.rect(WIN, YELLOW, bullet)
    for bullet in red_bullets:
        pygame.draw.rect(WIN, RED, bullet)
    if text != "":
        # per-pixel alpha
        s = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        s.fill((0, 0, 0, 150))
        WIN.blit(s, (0, 0))
        winner_text = WINNER_FONT.render(text, 1, WHITE)
        WIN.blit(winner_text, ((WIDTH - winner_text.get_width()) // 2,
                               (HEIGHT - winner_text.get_height()) // 2))
        BTN = button(green_col, (WIDTH - 100) // 2,
                     (HEIGHT + winner_text.get_height()) // 2, 100, 50)
        BTN.draw(WIN)
        BTN.add_text("Restart", WHITE, 30)
        BTN2 = button(red_col, (WIDTH - 100) // 2,
                      (HEIGHT + winner_text.get_height()) // 2 + 100, 100, 50)
        BTN2.draw(WIN)
        BTN2.add_text("Quit", WHITE, 30)
    pygame.display.update()
コード例 #4
0
ファイル: intro.py プロジェクト: Nikittttt/highfrontier
 def ask_company_name(self,give_warning=False):
     pygame.draw.rect(self.window, (212,212,212), self.gui_rect)
     title = global_variables.standard_font.render("Name of company:",True,(0,0,0))
     self.window.blit(title, (self.gui_rect[0] + 10, self.gui_rect[1] + 10))
     self.text_receiver = entry.entry(self.window, 
                          (self.gui_rect[0] + 10, self.gui_rect[1] + 45), 
                          self.gui_rect[2] - 20, 
                          global_variables.max_letters_in_company_names)
     self.buttons = {}
     self.buttons["ok"] = button.button(
         "ok", 
         self.window, 
         topleft = (self.gui_rect[0] + self.gui_rect[2] - 100,self.gui_rect[1] + self.gui_rect[3] - 40), 
         fixed_size = None)
     signaller.connect(self.buttons["ok"],"signal__clicked",self.ask_company_capital)
     self.buttons["cancel"] = button.button(
         "cancel", 
         self.window, 
         topleft = (self.gui_rect[0] + self.gui_rect[2] - 65,self.gui_rect[1] + self.gui_rect[3] - 40), 
         fixed_size = None)
     signaller.connect(self.buttons["cancel"],"signal__clicked",self.create_intro_gui);
     if give_warning:
         warning_label = global_variables.standard_font_small.render("No double space, no blanks",True,(0,0,0))
         self.window.blit(warning_label, (self.gui_rect[0] + 10, self.gui_rect[1] + 90))
         pygame.display.flip()
コード例 #5
0
ファイル: game.py プロジェクト: pavan-aeturi/2048
def EndorContinueGame(HighestScore, Mtx, window):
    sleep(1.0)
    window.fill(WHITE)
    if Mtx.winner:
        template = button(FONT_WCOLOR, 200, 200, 200, 200, "You won", 50)
        template.draw(window)
    else:
        template = button(FONT_WCOLOR, 200, 200, 200, 200, "You Loose", 50)
        template.draw(window)

    Try_Again = button(BLUE, 100, 500, 150, 50, "Try Again", FONT_WCOLOR)
    Exit = button(BLUE, 350, 500, 150, 50, "Exit", FONT_WCOLOR)
    Try_Again.draw(window)
    Exit.draw(window)
    HighestScore.Number = max(HighestScore.Number, Mtx.score)
    while True:
        try:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                        if Try_Again.isOver(pygame.mouse.get_pos()):
                            return True
                        elif Exit.isOver(pygame.mouse.get_pos()):
                            return False
        except:
            return False
コード例 #6
0
    def __init__(self):
        self.led1 = None
        self.pwm1 = None
        try:
            self.led1 = led(248)
        except ValueError:
            self.pwm1 = Pwm(0, True, 0)

        self.led2 = None
        self.pwm2 = None
        try:
            self.led2 = led(249)
        except ValueError:
            #self.pwm2 = Pwm(1, True, 0)
            pass

        # Red is always on, green and blue don't work
        # But the Tadpole does work for red and green using the same values
        # I believe my Calamari is bad
        self.led3 = rgb(82, 83, 208)

        self.s1 = button(216, True)
        self.s2 = button(227, True)
        self.s3 = button(226, True)

        # Need to test ssg, not working either...
        self.sseg = Seg7()

        # Requires Calamari kernel driver
        self.adc = calamari_adc()
コード例 #7
0
ファイル: tongxin.py プロジェクト: WeileiZeng/python-tutorial
def main():
	win=GraphWin("win",800,400)
	win.setCoords(0.0,0.0,40.0,20.0)
	a=Point(5,5)
	color=['red','blue','yellow','green','orange']
	
	question1="hello!\nI am one of tongxin\'s friends,\nNice to meet you Miss Wang!\nand I want to talk something about him with you,\nwell,you just need to answer the \nfollowing question by 'yes' or 'no'"
	tt=Text(Point(15.0,10.0),question1)
	tt.draw(win)
	time.sleep(2)


	question2="i think that tongxin is a very nice person,\nat all the time he is missing you ,he told me.\n Do you think he gave you enough warmth,enough love and enough happiness?"
	tt.setText(question2)

	#tt1=Text(Point(5.0,12.0),question2)
	
	#tt1.draw(win)
	tt2=Text(Point(5.0,10.0),"yes or no?")
	tt2.draw(win)
	en1=Entry(Point(5.0,8.0),10)
	en1.draw(win)
	yes=button.button(win,Point(4.0,4.0),2.0,1.0,'yes')
	no=button.button(win,Point(8.5,4.0),2.0,1.0,'no')
	Text(Point(6.0,4.0),"or").draw(win)
	Text(Point(10.0,4.0),"?").draw(win)
	pp=win.getMouse()
	if yes.judge(pp):
		Text(Point(5.0,2.0),"I think so,too").draw(win)
		win.getMouse()
	if no.judge(pp):
                pass
        image1= Image(Point(20.0,10.0),"")
        
	win.close()
コード例 #8
0
 def __init__(self, screen, path):
     self.screen = screen
     self.bg = pygame.image.load(path)
     self.bg = pygame.transform.scale(
         self.bg, (self.screen.get_width(), self.screen.get_height()))
     self.return_but = button("res/button_blue.png")
     self.return_but.add_button((49, 48), (339, 95, 388, 143), '',
                                (255, 255, 255))
     self.return_but.add_button((49, 45), (290, 95, 340, 140), '',
                                (255, 255, 255))
     self.return_but.set_picture(
         'res/icons.png', (4 * 51 - 5, 51 + 5, 5 * 51 - 5, 2 * 51 + 5),
         (40, 40))
     self.return_but.draw_button(
         self.screen, 0,
         (self.screen.get_width() - 100, self.screen.get_height() - 100))
     self.ans_1_but = button("res/button_blue.png")
     self.ans_2_but = button("res/button_blue.png")
     self.ans_3_but = button("res/button_blue.png")
     self.ans_4_but = button("res/button_blue.png")
     self.ans_1_but.add_button((190, 49), (0, 0, 190, 49), '',
                               (255, 255, 255))
     self.ans_1_but.add_button((190, 45), (0, 50, 190, 95), '',
                               (255, 255, 255))
     self.ans_2_but.add_button((190, 49), (0, 0, 190, 49), '',
                               (255, 255, 255))
     self.ans_2_but.add_button((190, 45), (0, 50, 190, 95), '',
                               (255, 255, 255))
     self.ans_3_but.add_button((190, 49), (0, 0, 190, 49), '',
                               (255, 255, 255))
     self.ans_3_but.add_button((190, 45), (0, 50, 190, 95), '',
                               (255, 255, 255))
     self.ans_4_but.add_button((190, 49), (0, 0, 190, 49), '',
                               (255, 255, 255))
     self.ans_4_but.add_button((190, 45), (0, 50, 190, 95), '',
                               (255, 255, 255))
     x = self.screen.get_width() // 2
     y = self.screen.get_height() // 2 + 180
     self.ans_1_but.draw_button(self.screen, 0, (x - 100, y - 30))
     self.ans_2_but.draw_button(self.screen, 0, (x + 100, y - 30))
     self.ans_3_but.draw_button(self.screen, 0, (x - 100, y + 30))
     self.ans_4_but.draw_button(self.screen, 0, (x + 100, y + 30))
     self.cur_exp = ""
     self.cur_diff = 0
     self.cur_score = -1
     self.cur_time = 10
     self.del_time = self.cur_time
     self.cur_ticks = pygame.time.get_ticks()
     self.cur_right = -1
     self.variants = []
     self.but = 0
     self.is_right = False
     self.fin_scr = message_box(self.screen)
     self.is_over = False
     self.is_first = True
     self.is_f_f = True
     self.out = -1
     self.new_level(True)
コード例 #9
0
 def init_buttons(self):
     for i in range(6):
         self.buttons.append(button("res/button_blue.png"))
         self.buttons[i].add_button((49,48),(339,95,388,143),str(i+1),(255,255,255))
         self.buttons[i].add_button((49,45),(290,95,340,140),str(i+1),(255,255,255))
     self.return_button=button("res/button_blue.png")
     self.return_button.add_button((49,48),(339,95,388,143),'',(255,255,255))
     self.return_button.add_button((49,45),(290,95,340,140),'',(255,255,255))
     self.return_button.set_picture('res/icons.png',(4*51-5,51+5,5*51-5,2*51+5),(40,40))
コード例 #10
0
def main2():  #create questons one by one
    win = GraphWin("qinaqian test", 400, 700)
    win.setCoords(0, 0, 20.0, 40.0)
    start = button.button(win, Point(5.0, 2.0), 3.0, 1.6, "start")
    eexit = button.button(win, Point(15.0, 2.0), 2.7, 1.6, 'exit')
    Image(Point(15.0, 2.0),
          'c://Python26/program/qianqian_test/tuichu.gif').draw(win)
    kaishi = Image(Point(5.0, 2.0),
                   'c://Python26/program/qianqian_test/kaishi.gif')
    kaishi.draw(win)
    question = Text(Point(7.0, 10.0), "")
    answer = Text(Point(15.0, 10.0), "")
    question.draw(win)
    answer.draw(win)
    pp = win.getMouse()
    while not start.judge(pp):
        pp = win.getMouse()

    Image(Point(5.0, 2.0),
          'c://Python26/program/qianqian_test/jiaojuan.gif').draw(win)
    answer_list = []
    entry_list = []
    duicuo = []
    for i in range(20):
        duicuo.append([])
        duicuo[i].append(
            Image(Point(15.0, 37.5 - i * 1.75),
                  'c://Python26/program/qianqian_test/dui.gif'))
        duicuo[i].append(
            Image(Point(16.5, 37.5 - i * 1.75),
                  'c://Python26/program/qianqian_test/cuo.gif'))
        q_a = create_multiplication()
        question_text, answer_text = q_a[0], q_a[1]  #
        Text(Point(5.0, 37.5 - i * 1.75), question_text).draw(win)  #
        entry = Entry(Point(9.0, 37.5 - i * 1.75), 3)
        entry.draw(win)
        entry_list.append(entry)  #
        answer = Text(Point(11.0, 37.5 - i * 1.75), answer_text)
        answer_list.append(answer)  #
    pp = win.getMouse()
    while not eexit.judge(pp):

        if start.judge(pp):
            for i in range(20):
                answer_list[i].draw(win)

                if len(entry_list[i].getText()) > 0 and int(
                        entry_list[i].getText()) == answer_list[i].getText():
                    duicuo[i][0].draw(win)
                else:
                    duicuo[i][1].draw(win)
            break

        pp = win.getMouse()
    pp = win.getMouse()
    win.close()
コード例 #11
0
	def __init__(self, width, height, window, screen_type):

		self.width = width
		self.height = height
		self.window = window

		self.running = True
		self.traits_ready = False
		self.text_boxes = []
		self.buttons = []
		self.buttons_dic = dict()
		self.screen_type = screen_type

		#Adding Text Boxes
		self.text_boxes += [text_box(1000, 100, 100, 20, title="Minimum Neighbours (%)", border=1, is_float=True)]
		self.text_boxes += [text_box(1000, 150, 100, 20, title="Maximum Neighbours (%)", border=1, is_float=True)]
		self.text_boxes += [text_box(1000, 200, 100, 20, title="Empty Spots (%)", border=1, is_float=True)]
		self.text_boxes += [text_box(1000, 250, 100, 20, title="Width", border=1, is_int=True)]
		self.text_boxes += [text_box(1000, 300, 100, 20, title="Height", border=1, is_int=True)]
		if self.screen_type == "Neighbourhoods":
			self.text_boxes += [text_box(1000, 350, 100, 20, title="Number of Neighbourhoods", border=1, is_int=True)]

		self.inputs = dict()
		self.inputs["Traits"] = 0

		#Adding Buttons
		self.start_button = button(925, 400, 100, 40, text="Run", hor_space=50, ver_space=2)
		self.buttons += [button(850, 100, 20, 20, text="2", border=2, text_size=10, hor_space=15, ver_space=4)]
		self.buttons_dic["2"] = False
		self.buttons += [button(875, 100, 20, 20, text="3", border=2, text_size=10, hor_space=15, ver_space=4)]
		self.buttons_dic["3"] = False
		self.buttons += [button(900, 100, 20, 20, text="4", border=2, text_size=10, hor_space=16, ver_space=4)]
		self.buttons_dic["4"] = False
		self.buttons += [button(925, 100, 20, 20, text="5", border=2, text_size=10, hor_space=15, ver_space=4)]
		self.buttons_dic["5"] = False

		#Message settings
		self.intro_font = pygame.font.SysFont("times new roman", 40, bold=True)
		self.intro_text_colour = (0,51,102)
		self.intro_message = "Set the parameters"
		self.intro_pos = vec(self.width//10, self.height//5)

		#Traits text settings
		self.trait_font = pygame.font.SysFont("times new roman", 12, bold=True)
		self.trait_text_colour = (0,51,102)
		self.trait_message = "Number of Traits"
		self.trait_pos = vec(850, 80)

		#Error message settings
		self.error_font = pygame.font.SysFont("times new roman", 8, bold=True)
		self.error_text_colour = (0,0,0)
		self.error_messages = dict()
コード例 #12
0
ファイル: gui.py プロジェクト: Nikittttt/highfrontier
 def createBaseSubcommandbox(self):
     self.buttonlinks = [
         "base_population_info", "base_list_of_companies",
         "base_list_of_firms", "base_and_firm_market_window",
         "base_build_menu"
     ]
     self.buttonnicenames = [
         "population", "companies", "firms", "market", "build"
     ]
     i = 0
     b = button.button("population",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["population"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickBasePopulation)
     i = i + 1
     b = button.button("companies",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["companies"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickBaseCompanies)
     i = i + 1
     b = button.button("firms",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["firms"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickBaseFirms)
     i = i + 1
     b = button.button("market",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["market"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickBaseMarket)
     i = i + 1
     b = button.button("build",
                       self.subcommand_surface,
                       fixed_size=(self.subcommand_surface.get_width() - 20,
                                   35),
                       topleft=(10, i * 40 + 10))
     self.subcommand_buttons["build"] = b
     signaller.connect(b, "signal__clicked", self.slot__clickBaseBuild)
     return
コード例 #13
0
 def merchant_pick_name(self, resource, give_length_warning=False):
     """
     Function to get the name of the merchant
     give_length_warning         If true, this will specify the max text size as part of the title.
     """
     self.menu_position = "pick name"
     self.selections["resource"] = resource
     #check that this does not already exist
     exists = False
     for firm_instance in self.solar_system_object_link.current_player.owned_firms.values(
     ):
         if isinstance(firm_instance, company.merchant):
             if firm_instance.from_location == self.selections[
                     "from_location"]:
                 if firm_instance.to_location == self.selections[
                         "to_location"]:
                     if firm_instance.resource == resource:
                         exists = True
     if exists:
         print_dict = {
             "text":
             "A merchant from " +
             str(self.selections["from_location"].name) + " to " +
             str(self.selections["to_location"].name) + " trading " +
             str(resource) + " does already exist",
             "type":
             "general gameplay info"
         }
         self.solar_system_object_link.messages.append(print_dict)
     else:
         pygame.draw.rect(self.action_surface, (212, 212, 212), self.rect)
         pygame.draw.rect(self.action_surface, (0, 0, 0), self.rect, 2)
         pygame.draw.line(self.action_surface, (255, 255, 255),
                          (self.rect[0], self.rect[1]),
                          (self.rect[0] + self.rect[2], self.rect[1]))
         pygame.draw.line(self.action_surface, (255, 255, 255),
                          (self.rect[0], self.rect[1]),
                          (self.rect[0], self.rect[1] + self.rect[3]))
         text = global_variables.standard_font.render(
             "Choose name for merchant:", True, (0, 0, 0))
         self.action_surface.blit(text,
                                  (self.rect[0] + 10, self.rect[1] + 10))
         if give_length_warning:
             warning = global_variables.standard_font.render(
                 "Name must be unique", True, (0, 0, 0))
             self.action_surface.blit(
                 warning, (self.rect[0] + 10, self.rect[1] + 50))
         self.text_receiver = entry.entry(
             self.action_surface,
             topleft=(self.rect[0] + 10, self.rect[1] + 90),
             width=self.rect[3] - 20,
             max_letters=global_variables.max_letters_in_company_names)
         self.text_receiver.active = True
         self.ok_button = button.button("ok",
                                        self.action_surface,
                                        fixed_size=(100, 35),
                                        topleft=(self.rect[0] + 10,
                                                 self.rect[1] + 150))
         signaller.connect(self.ok_button, "signal__clicked",
                           self.merchant_build)
コード例 #14
0
    def create(self):
        """
        The creation function.  
        """
        pygame.draw.rect(self.action_surface, (212, 212, 212), self.rect)
        pygame.draw.rect(self.action_surface, (0, 0, 0), self.rect, 2)
        pygame.draw.line(self.action_surface, (255, 255, 255),
                         (self.rect[0], self.rect[1]),
                         (self.rect[0] + self.rect[2], self.rect[1]))
        pygame.draw.line(self.action_surface, (255, 255, 255),
                         (self.rect[0], self.rect[1]),
                         (self.rect[0], self.rect[1] + self.rect[3]))

        self.button_labels = [
            "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus",
            "neptune"
        ]

        self.buttons = {}
        for i, button_label in enumerate(self.button_labels):
            b = button.button(button_label,
                              self.action_surface,
                              topleft=(self.rect[0] + 5,
                                       self.rect[1] + 5 + i * 30),
                              fixed_size=(self.rect[2] - 10, 25))
            self.buttons[button_label] = b
            signaller.connect(b, "signal__clicked",
                              lambda: self.planet_jump(b.label()))
コード例 #15
0
    def select_save_name(self, function_parameter=[]):
        """
        Prompts the player to input the name of the savegame file
        """
        
        pygame.draw.rect(self.action_surface, (150,150,150), self.rect)
        description = global_variables.standard_font.render("Enter savegame name:",True,(0,0,0))
        self.action_surface.blit(description, (10 + self.rect[0], 10 + self.rect[1]))
        
        self.button_list_now = ["Empty space","Name box","Ok"]
        self.button_instances_now = {}
        self.button_instances_now["Name box"] = entry.entry(self.action_surface, 
                             topleft = (10 + self.rect[0], 10 + 40 + self.rect[1]), 
                             width = self.rect[2] - 20, 
                             max_letters = global_variables.max_letters_in_company_names)

        self.text_receiver = self.button_instances_now["Name box"]
        self.button_instances_now["Name box"].active = True 
        
        self.button_instances_now["Ok"] = button.button(
                                    "Ok",
                                    self.action_surface,
                                    self.effectuate_save,
                                    function_parameter = None,
                                    fixed_size = (self.rect[2] - 20, 35),
                                    topleft = (10 + self.rect[0], 80 + 10 + self.rect[1])
                                    )
        pygame.display.flip() 
コード例 #16
0
    def loadSettingMenu(self):

        playerColor = 0

        clock = pygame.time.Clock()

        fenetre = pygame.display.set_mode((self.WIDTH, self.HEIGHT))

        back = pygame.image.load("background.jpg").convert()
        back2 = pygame.transform.scale(back,
                                       (int(Game.WIDTH), int(Game.HEIGHT)))
        back3 = sprite(0, 0, back2)

        menuSprites = list([back3], "sprites")

        Game.toDisplay.append(menuSprites)

        strColors = ["GREEN", "BLUE", "PURPLE", "RED", "YELLOW"]
        rgbColors = [Game.GREEN, Game.BLUE, Game.PURPLE, Game.RED, Game.YELLOW]

        buttons = list([], "buttons")

        for i in range(0, 5):
            b = button(Game.WIDTH / 6 * (i + 1) - Game.WIDTH_BUTTON / 2,
                       Game.HEIGHT / 4, Game.WIDTH_BUTTON, Game.HEIGHT_BUTTON,
                       rgbColors[i], strColors[i], 14)
            buttons.l.append(b)

        Game.toDisplay.append(buttons)

        menuLabel = list([], "labels")

        text = "Select a player!"

        lab = label((Game.WIDTH - len(text) * 26) / 2, Game.HEIGHT / 5 - 26,
                    text, 52)

        menuLabel.l.append(lab)

        Game.toDisplay.append(menuLabel)

        loop = True

        while loop:

            self.updateDisplay(Game.toDisplay, fenetre)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    loop = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                    for li in Game.toDisplay:
                        if li.name == "buttons":
                            for b in li.l:
                                if b.intersect(event.pos):
                                    playerColor = b.settings[4]
                                    loop = False
        return playerColor
コード例 #17
0
def main():

    #creacion de objetos para el programa
    bg = background.background(settings.pantalla,'00.jpg')

    #configuramos boton principal
    boton = button.button(settings.pantalla,posicion=(40,450))
    boton.agregar_img('00.png')
    boton.agregar_img('01.png')
    boton.agregar_img('02.png')
    boton.actual(0)
    
    mouse = cursor.cursor()
    bgmusic = bgm.bgm("001.mp3")
    running = True
    directorio = os.getcwd()

    #acciones de uso unico
    bgmusic.play()

    #bucle principal
    while running:
        #variables que se comprueban cada bucle
            

        #lista que contiene todos los eventos que se ejecutaron
        for evento in pygame.event.get():
            if evento.type == pygame.MOUSEBUTTONUP:
                if evento.button == 1:
                    if boton.rectangulo.left < mouse.posicion[0] < boton.rectangulo.right and boton.rectangulo.top < mouse.posicion[1] < boton.rectangulo.bottom:
                        s1.main()
                        running = False
                        
                        
            if evento.type == pygame.QUIT:
                running = False


        #opciones de posicion del mouse
        if mouse.posicion[0] > boton.rectangulo.right or \
           mouse.posicion[0] < boton.rectangulo.left or \
           mouse.posicion[1] > boton.rectangulo.bottom or \
           mouse.posicion[1] < boton.rectangulo.top:
            boton.actual(0)
        else:
            if mouse.estado[0]:
                boton.actual(2)
            if not(mouse.estado[0]):
                boton.actual(1)

        #Actualizamos posicion de las cosas
        bg.update()
        boton.update()
        mouse.update()
        if not(running): bgmusic.stop()
        
        #actualizamos la pantalla
        pygame.display.flip()
        settings.reloj.tick(60)                     #60 frames por segundo
コード例 #18
0
 def __init__(self, screen, image_path):
     pygame.sprite.Sprite.__init__(self)
     self.screen = screen
     self.bg = pygame.image.load(image_path)
     self.bg = pygame.transform.scale(
         self.bg, (self.screen.get_width(), self.screen.get_height()))
     self.inf_but = button("res/buttons.png")
     self.inf_but.add_button((190, 49), (190, 45, 380, 95), "Informatics")
     self.inf_but.add_button((190, 45), (0, 50, 190, 95), "Informatics")
     self.math_but = button("res/buttons.png")
     self.math_but.add_button((190, 49), (190, 45, 380, 95), "Mathematics")
     self.math_but.add_button((190, 45), (0, 50, 190, 95), "Mathematics")
     self.memo_but = button("res/buttons.png")
     self.memo_but.add_button((190, 49), (190, 45, 380, 95), "Memo")
     self.memo_but.add_button((190, 45), (0, 50, 190, 95), "Memo")
     self.font = pygame.font.SysFont('Corbel', 100)
     self.title = "Learning"
コード例 #19
0
ファイル: intro.py プロジェクト: Nikittttt/highfrontier
 def ask_company_capital(self,give_warning=False):
     if "country_window" in self.buttons and self.is_country:
         company_name = self.buttons["country_window"].selected
     elif self.text_receiver is not None and not self.is_country:
         company_name = self.text_receiver.text
     else:
         raise Exception("Could not figure out whether country or private company was selected")
     all_ok = True
     if not (0 < len(company_name) <= global_variables.max_letters_in_company_names):
         all_ok = False
     if company_name.find("  ") != -1: #somewhere it is used that there are two double spaces, so we can't allow that in a companyname
         all_ok = False
     if company_name in self.countries and not self.is_country:
         all_ok = False
     if all_ok:
         pygame.draw.rect(self.window, (212,212,212), self.gui_rect)
         title = global_variables.standard_font.render("Starting capital:",True,(0,0,0))
         self.window.blit(title, (self.gui_rect[0] + 10, self.gui_rect[1] + 10))
         self.text_receiver = entry.entry(self.window, 
                              (self.gui_rect[0] + 10, self.gui_rect[1] + 45), 
                              self.gui_rect[2] - 20, 
                              global_variables.max_letters_in_company_names,
                              starting_text = "10000000")
         self.buttons = {}
         self.buttons["ok"] = button.button(
             "ok", 
             self.window, 
             topleft = (self.gui_rect[0] + self.gui_rect[2] - 100,self.gui_rect[1] + self.gui_rect[3] - 40), 
             fixed_size = None)
         signaller.connect(self.buttons["ok"],"signal__clicked",self.start_new_game)
         self.buttons["cancel"] = button.button(
             "cancel", 
             self.window, 
             topleft = (self.gui_rect[0] + self.gui_rect[2] - 65,self.gui_rect[1] + self.gui_rect[3] - 40), 
             fixed_size = None)
         signaller.connect(self.buttons["cancel"],"signal__clicked",self.create_intro_gui);
         self.company_name = company_name
         if give_warning:
             warning_label = global_variables.standard_font_small.render("Starting capital must be an",True,(0,0,0))
             self.window.blit(warning_label, (self.gui_rect[0] + 10, self.gui_rect[1] + 90))
             warning_label2 = global_variables.standard_font_small.render("integer above zero",True,(0,0,0))
             self.window.blit(warning_label2, (self.gui_rect[0] + 10, self.gui_rect[1] + 100))
             pygame.display.flip()
     else:
         self.ask_company_name(give_warning=True)
コード例 #20
0
 def draw_subfunction_button(self,button_name,slot,size,pos):
     b = button.button(
         button_name,
         self.action_surface,
         fixed_size=size,
         topleft=pos
         )
     signaller.connect(b,"signal__clicked",slot)
     return b
コード例 #21
0
ファイル: memo.py プロジェクト: michaelknz/educational_game
    def __init__(self, screen):
        self.BOARDWIDTH = 6  # количество столбцов в игре
        self.BOARDHEIGHT = 6  # количество строк в игре

        self.screen = screen

        self.WIDTH = screen.get_width()
        self.HEIGHT = screen.get_height()

        self.SPEEDDEMONSTRATION = 1
        self.BOXSIZE = 40  # размер карточек
        self.GAPSIZE = 10  # отступы между карточками

        self.XMARGIN = int((self.WIDTH - (self.BOARDWIDTH *
                                          (self.BOXSIZE + self.GAPSIZE))) / 2)
        self.YMARGIN = int((self.HEIGHT - (self.BOARDHEIGHT *
                                           (self.BOXSIZE + self.GAPSIZE))) / 2)

        # радуга палитра
        self.RED = (255, 0, 0)
        self.ORANGE = (255, 128, 0)
        self.YELLOW = (255, 255, 0)
        self.GREEN = (0, 255, 0)
        self.CYAN = (0, 255, 255)
        self.BLUE = (0, 0, 255)
        self.PURPLE = (255, 0, 255)
        self.GRAY = (100, 100, 100)
        self.WHITE = (255, 255, 255)
        self.BLACK = (0, 0, 0)

        # возможные фигуры
        self.CIRCLE = 'circle'
        self.SQUARE = 'square'
        self.DIAMOND = 'diamond'
        self.LINES = 'lines'
        self.OVAL = 'oval'

        # цвета и формы
        self.ALLCOLORS = (self.RED, self.GREEN, self.BLUE, self.YELLOW,
                          self.ORANGE, self.PURPLE, self.CYAN)
        self.ALLSHAPES = (self.CIRCLE, self.SQUARE, self.DIAMOND, self.LINES,
                          self.OVAL)

        self.mainBoard = self.getRandomizedBoard()
        self.revealedBoxes = self.generateRevealedBoxesData(False)
        self.firstSelection = None

        self.is_start = True
        self.return_button = button("res/button_blue.png")
        self.return_button.add_button((49, 48), (339, 95, 388, 143), '',
                                      (255, 255, 255))
        self.return_button.add_button((49, 45), (290, 95, 340, 140), '',
                                      (255, 255, 255))
        self.return_button.set_picture(
            'res/icons.png', (4 * 51 - 5, 51 + 5, 5 * 51 - 5, 2 * 51 + 5),
            (40, 40))
        self.return_button.draw_button(self.screen, 0, (1500, 700))
コード例 #22
0
	def __init__(self, width, height, window):

		self.width = width
		self.height = height
		self.window = window

		self.running = True

		#Adding Buttons
		self.buttons = []
		self.buttons += [button(800, 400, 250, 40, text="Regular Model", hor_space=75, ver_space=2)]
		self.buttons += [button(150, 400, 250, 40, text="Neighbourhoods", hor_space=50, ver_space=2)]


		self.intro_font = pygame.font.SysFont("times new roman", 40, bold=True)
		self.intro_text_colour = (0,51,102)
		self.intro_message = "Welcome to Schelling Model's Simulation!"
		self.intro_pos = vec((self.width-len(self.intro_message)*18)/2, self.height//5)
コード例 #23
0
 def generate_tbox(self):
     '''
     Generating the textbox to display the value.
     '''
     x = int(self.x - (self.radius / sqrt(2)))
     y = int(self.y - (self.radius / sqrt(2)))
     w = int(sqrt(2) * self.radius)
     fnt = pygame.font.SysFont('Times New Roman', 25)
     self.tbox = button.button(self.text, x, y, w, w, self.colour, col.WHITE, fnt)
コード例 #24
0
 def draw_submenu_button(self,button_name,parameter,size,pos):
     b = button.button(
         button_name,
         self.action_surface,
         fixed_size=size,
         topleft=pos
         )
     signaller.connect(b,"signal__clicked",lambda: self.go_to_submenu(parameter))
     return b
コード例 #25
0
ファイル: testButton.py プロジェクト: lloydas/mdp_gui
 def createWidgets(self):
     values = {
         "text": "say_hi",
         "fg": "red",
         "relief": SUNKEN,
         "disabledforeground": "blue"
     }
     position = {"side": "left"}
     self.hi = button(parent=self, values=values, position=position)
コード例 #26
0
 def execute(label, technology):
     """
     This function is activated on scrollbar value change on the size selection box, and updates the input_
     output_dict
     """
     update_rect = pygame.Rect(self.rect[0] + 50, self.rect[1] + 170,
                               self.rect[2] - 100, self.rect[3] - 250)
     pygame.draw.rect(self.action_surface, (212, 212, 212), update_rect)
     size_info = global_variables.standard_font_small.render(
         "size: " + str(self.slider.position), True, (0, 0, 0))
     self.action_surface.blit(size_info,
                              (self.rect[0] + 130, self.rect[1] + 170))
     lineno = 0
     for put in ["input", "output"]:
         lineno = lineno + 1
         direction_info = global_variables.standard_font_small.render(
             put + ":", True, (0, 0, 0))
         self.action_surface.blit(
             direction_info,
             (self.rect[0] + 130, self.rect[1] + 170 + lineno * 20))
         #                print technology.keys()
         for resource in technology["input_output_dict"][put].keys():
             lineno = lineno + 1
             if resource in self.solar_system_object_link.mineral_resources + [
                     "food"
             ] and put == "output":
                 mining_opportunity = self.solar_system_object_link.current_planet.current_base.get_mining_opportunities(
                     self.solar_system_object_link.current_planet,
                     resource)
                 unmodified_output = technology["input_output_dict"][
                     "output"][resource]
                 value = (mining_opportunity / 10) * unmodified_output
                 value = int(value * self.slider.position)
                 value_info = global_variables.standard_font_small.render(
                     resource + ": " + str(value) +
                     " (location modifier: " +
                     str(round(mining_opportunity, 2)) + ")", True,
                     (0, 0, 0))
             else:
                 value = technology["input_output_dict"][put][resource]
                 value = value * self.slider.position
                 value_info = global_variables.standard_font_small.render(
                     resource + ": " + str(value), True, (0, 0, 0))
             self.action_surface.blit(
                 value_info,
                 (self.rect[0] + 150, self.rect[1] + 170 + lineno * 20))
     self.ok_button = button.button(
         "ok",
         self.action_surface,
         fixed_size=(100, 35),
         topleft=(self.rect[0] + self.rect[2] - 110,
                  self.rect[1] + self.rect[3] - 40))
     signaller.connect(self.ok_button, "signal__clicked",
                       lambda: self.commodity_build_firm(existing_firm))
     pygame.display.flip()
コード例 #27
0
ファイル: show.py プロジェクト: lloydas/mdp_gui
def createCanvas():
    newWindow = Toplevel()
    newWindow.geometry("500x500")

    newCanvas = canvas(newWindow, values_json["canvas"][0],
                       values_json["canvas"][1])
    entry1 = entry(newWindow, values_json["entry1"][0], newCanvas)
    entry1.render(values_json["entry1"][1])
    buttonCanvas = button(newWindow, entry1.getTextVal,
                          values_json["buttonCanvas"][0],
                          values_json["buttonCanvas"][1])
コード例 #28
0
ファイル: intro.py プロジェクト: Nikittttt/highfrontier
    def ask_country_name(self):
        self.gui_rect = pygame.Rect(global_variables.window_size[0] / 2 - 150,global_variables.window_size[1] / 3 - 50, 300,300)
        pygame.draw.rect(self.window, (212,212,212), self.gui_rect)

        country_window = fast_list.fast_list(self.window, self.countries, rect = pygame.Rect(self.gui_rect[0], self.gui_rect[1], self.gui_rect[2], self.gui_rect[3] - 50))
        self.buttons = {}
        self.buttons["country_window"] = country_window
        self.buttons["ok"] = button.button(
            "ok", 
            self.window, 
            topleft = (self.gui_rect[0] + self.gui_rect[2] - 100,self.gui_rect[1] + self.gui_rect[3] - 40), 
            fixed_size = None)
        signaller.connect(self.buttons["ok"],"signal__clicked",self.ask_company_capital)
        self.buttons["cancel"] = button.button(
            "cancel", 
            self.window, 
            topleft = (self.gui_rect[0] + self.gui_rect[2] - 65,
                       self.gui_rect[1] + self.gui_rect[3] - 40), 
            fixed_size = None)
        signaller.connect(self.buttons["cancel"],"signal__clicked",self.create_intro_gui)
コード例 #29
0
ファイル: main.py プロジェクト: knyete/mqtt_lights
def load_button(config, devices):
    import button
    for i in config:
        item = config[i]
        if "type" in item and item["type"] == "button":
            state_topic = item["state_topic"]
            pin = item["pin"]
            invert = not item["high_on"]
            device = button.button(pin=pin, topic=state_topic, inverted=invert)
            devices.append(device)
    return devices
コード例 #30
0
def rungame():
    p.init()
    ai_Settings=Settings()
    screen=p.display.set_mode((ai_Settings.screen_width,ai_Settings.screen_heigth))
    ship=Ship(screen,ai_Settings)
    p.display.set_caption("Alien Invasion")
    play_button=button(ai_Settings,screen,"play")
    lose_button=button(ai_Settings,screen,"Gamal AbdelNaser")
    bullets=Group()
    aliens=Group()
    state=Game_Sate(ai_Settings)
    sb=scoreboard(screen,state,ai_Settings)
    gf.fleet_of_aliens(ai_Settings,screen,aliens,ship)
    while True:
        gf.check_event(state,play_button,ship,aliens,ai_Settings,screen,bullets,lose_button,sb)
        gf.update_screen(ai_Settings,screen,ship,bullets,aliens,state,play_button,lose_button,sb)
        if state.game_active:
            ship.update()
            bullets.update()
            gf.update_aliens(aliens,ai_Settings,ship,screen,bullets,state,sb)
            gf.update_bullets(bullets,aliens,ai_Settings,screen,ship,sb,state)
コード例 #31
0
ファイル: dialogbox.py プロジェクト: jordsti/pydbg
    def __generate_buttons(self):

        if self.buttons == self.Ok:
            btn_ok = button(self.button_width, self.button_height)
            btn_ok.caption = "Ok"
            btn_ok.add_receivers(self.__ok)
            btn_ok.x = (self.width - self.button_width) / 2
            btn_ok.y = (self.height - self.button_height) - self.button_offset
            self.__buttons.append(btn_ok)

        elif self.buttons == self.OkCancel:
            btn_ok = button(self.button_width, self.button_height)
            btn_ok.caption = "Ok"
            btn_ok.add_receivers(self.__ok)
            btn_ok.x = ((self.width - self.button_width*2) / 2) - self.button_offset
            btn_ok.y = (self.height - self.button_height) - self.button_offset
            self.__buttons.append(btn_ok)

            btn_cancel = button(self.button_width, self.button_height)
            btn_cancel.caption = "Cancel"
            btn_cancel.add_receivers(self.__cancel)
            btn_cancel.x = btn_ok.x + btn_ok.width + self.button_offset
            btn_cancel.y = btn_ok.y
            self.__buttons.append(btn_cancel)
コード例 #32
0
ファイル: palette.py プロジェクト: blackmius/circuitD
    def __init__(self, name, elements, palette):
        self.name = name

        self.palette = palette

        self.open = False
        
        self.w = 190
        self.h = 26

        self.x = 0 - self.palette.offset
        self.y = 0

        self.image = Surface((self.w, self.h))

        fill_gradient(self.image, (60, 60, 60), (15, 15, 13))

        self.fontsize = 18

        self.font = font.Font('../data/fonts/gost.ttf', self.fontsize)

        self.image.blit(self.font.render(self.name, 0, (255, 255, 255)), (4, self.h/2-self.font.size(self.name)[1]/2))

        self.surfaceH = self.h
        
        self.surface = Surface((self.w, self.surfaceH))
        
        self.elements =  []

        self.num = len(self.palette.tabs)

        self.circuitSize = 50        
        self.circuitIntend = 25

        for i in elements:
            self.addElement(i)

        self.buttonImgs = [image.load('../data/imgs/arrowbutton2.png'), transform.flip(image.load('../data/imgs/arrowbutton2.png'), False, True)]
        self.button = button(160, self.h/2 - 7, self.image, self.buttonImgs, imgnum = 1 if self.open else 0, whereuponvars = [self.x, self.y + 36, self.w, self.h], backlight = (255, 255, 255, 30))
        
        self.elementImg = Surface((50, 50))
        self.elementImg.fill((255, 255, 255), (2, 2, 46, 46))

        self.font = font.Font('../data/fonts/gost.ttf', self.fontsize)

        self.mousepressed = False
コード例 #33
0
ファイル: palette.py プロジェクト: blackmius/circuitD
    def resize(self):
        self.width = 200

        self.height = self.window.height - 72

        self.surface = Surface((self.width, self.height)).convert_alpha()

        self.arrowsBg = Surface((self.arrowsWidth+2, self.height))

        self.arrows = button(self.width+1, self.height/2 - self.arrowsHeight/2, self.window.screen, [self.arrowsImg1, self.arrowsImg2], imgnum = 0 if self.offset == 0 - self.width else 1, backlight = (255, 255, 255, 30))

        self.circuitSurface = Surface((self.width - 15, self.height)).convert_alpha()
        self.circuitSurface.fill((0, 0, 0, 0))

        self.sliderHeight = self.height

        self.slider = slider(self.window.screen, self.sliderX, self.sliderY, self.sliderWidth, self.sliderHeight, self.sliderMaxoffset)

        self.arrows.change_coords(x = self.offset + self.width + 1)
        self.slider.change_coords(x = self.offset + self.width - percent(self.width - self.width/4, 10))
コード例 #34
0
ファイル: old.run.py プロジェクト: miyvrey2/ipmedt5
import time
from rta import rta
from sum import sum
from button import button
from scene import scene


sum = sum()
button = button()
rta = rta()
scene = scene()

score = 0

while True:
	if scene.pressStart(rta, button) == True:
		break

for x in range(0, 3):
	
	# Clear the board
	rta.codeBig("JYM01")
	time.sleep(1)
	
	clickIn = 0
	answer = ""
	answerbit = ""	

	current = x
	som = sum.createSum()
コード例 #35
0
ファイル: TestFile.py プロジェクト: djphan/302-MegaPidgeots
from __future__ import print_function
from calibrationWizard import CalibrationWizard
import os
import SceneManager
import ClientHandler
#from multiprocessing import Process
from button import button
from polyModel import polyModel
import time

buttonz = button("Blue.OSGB","Button")
コード例 #36
0
ファイル: palette.py プロジェクト: blackmius/circuitD
    def __init__(self, window):
        self.window = window
        
        self.width = 200
        self.height = self.window.height - 72
    
        self.offset = 0
        self.offsetTo = self.offset

        self.moveSpeed = 10

        self.surface = Surface((self.width, self.height)).convert_alpha()

        self.arrowsWidth = 10
        self.arrowsHeight = 124
    
        self.arrowsBg = Surface((self.arrowsWidth+2, self.height))

        self.arrowsImg2 = transform.scale(image.load('../data/imgs/arrowbutton.png'), (self.arrowsWidth, self.arrowsHeight))
        self.arrowsImg1 = transform.flip(self.arrowsImg2, True, False)

        self.arrows = button(self.width+1, self.height/2 - self.arrowsHeight/2, window.screen, [self.arrowsImg1, self.arrowsImg2], imgnum = 0 if self.offset == 0 - self.width else 1, backlight = (255, 255, 255, 30))

        self.sliderWidth = 15
        self.sliderHeight = self.height
        self.sliderX = self.offset + self.width - self.sliderWidth
        self.sliderY = 36
        self.sliderMaxoffset = 0

        self.slider = slider(window.screen, self.sliderX, self.sliderY, self.sliderWidth, self.sliderHeight, self.sliderMaxoffset)

        self.lastslideroffset = 0

        self.offsetY = 0

        self.mousepressed = False

        self.pannelWidth = 640
        self.pannelHeight = 36
        
        self.offsetreturn = self.offset
        self.pastoffsetreturn = self.offset

        self.tabs = []
        
        for i in ['Inputs', 'Outputs', 'Prim elements', 'Elements']:
            self.tabs.append(tab(i, [], self))

        self.tabs[0].addElement('Constant 1')
        self.tabs[0].addElement('Constant 0')
        self.tabs[0].addElement('Switch')
        
        self.tabs[1].addElement('Bulb')
        
        self.tabs[2].addElement('Not')
        self.tabs[2].addElement('And')
        self.tabs[2].addElement('Or')


        self.tabupdated = True

        self.element = None

        self.elementImg = None
コード例 #37
0
DISPLAYSURF = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('NetNave Alarm Clock')


#Set Frames per second
FPS = 30 
fpsClock = pygame.time.Clock()

#AlarmSet
alarmWidth = 400
alarmHeight = 300
alarmTop = 50
alarmLeft = 200


snoozeAlarm = button(370,35,(alarmLeft + 15), (alarmTop + 5) ,pygame.image.load('snoozeImg.png'),DISPLAYSURF)
disarmAlarm = button(370,35, (alarmLeft + 15), (alarmTop + alarmHeight) - 35 ,pygame.image.load('disarmImg.png'),DISPLAYSURF)

#Load images
dawnImg = pygame.image.load('NYCDawn.png')
dayImg = pygame.image.load('NYCDay.png')
eveImg = pygame.image.load('NYCEve.png')
nightImg = pygame.image.load('NYCNight.png')
#Load fonts
clockFont = pygame.font.Font("Roboto-Black.ttf", 80)
alarmFont = pygame.font.Font("Roboto-Black.ttf", 40)

#Create test alarm(always current time plus 1 minute)
testAlarm = datetime.datetime.now()
testAlarm = testAlarm + datetime.timedelta(minutes = 1)
コード例 #38
0
ファイル: chess.py プロジェクト: gamda/chess
# ^ to display color of who's turn it is
turnTxt = pygame.image.load("img\\turnTxt.png")
turnTxt.set_colorkey((255, 255, 255))


### BUTTONS
btnNames = ["btnMusicOn", "btnMusicOff", "btnNewGame", "btnSaveGame", "btnUndo", "btnQuit"]
disabledForNetwork = ["btnNewGame", "btnSaveGame", "btnUndo"]
path, suffix = "img/", ".png"
active, disabled = "Active", "Disabled"
xstart, ystart = WINDOW_HEIGHT + 15, 330
buttons = {}
btnRects = {}
firstPass = True  # to have both music buttons on the same pos
for name in btnNames:
    buttons[name] = button(name, path + name + suffix, path + name + active + suffix, path + name + disabled + suffix)
    if not firstPass:
        # only one music square
        btnRects[name] = buttons[name].get_rect((xstart, ystart))
        # only add after the first pass, means first 2 have same pos
        ystart = ystart + 45
    firstPass = False


### Promotion
# special rect to hold the 4 possibilities for pawn promotion
#   it will be placed starting around (c,3)
promoRect = pygame.Rect(MARGIN + 2 * SQR_WIDTH - 10, MARGIN + 3 * SQR_WIDTH - 10, 4 * SQR_WIDTH + 20, SQR_HEIGHT + 20)
promoRow = 5
promoSqrs = [(chessLocals.c, promoRow), (chessLocals.d, promoRow), (chessLocals.e, promoRow), (chessLocals.f, promoRow)]
promoPcs = [chessLocals.QUEEN, chessLocals.BISHOP, chessLocals.KNIGHT, chessLocals.ROOK]
コード例 #39
0
ファイル: menu.py プロジェクト: rcockbur/Python-Game---Dawn
 def addButton(self, x, y, width, height, text):
     self.buttonDict[(x, y, width, height)] = (button.button(width, height, text))
コード例 #40
0
ファイル: Alarm.py プロジェクト: alexswo/OhlarmClock
import linecache
import musicPlayer
import button
import subprocess 
import sys
from rotary_class import RotaryEncoder
import menu_class
import sevenSegmentFunc

isPlayingMusic = False
#subprocess.call("/home/pi/OhlarmClock/rmb.py",shell=True)
#subprocess.call("/home/pi/OhlarmClock/rmb2.py",shell=True)

media = musicPlayer.musicPlayer()
menu = menu_class.menu_class()
button = button.button()
sevenSegment = sevenSegmentFunc.sevenSegmentFunc()

#Defining GPIO Pins for each switch related to the Rotary Encoder
BUTTON_SWITCH = 19
LEFT_SWITCH = 16
RIGHT_SWITCH = 12
volumeknob = RotaryEncoder(LEFT_SWITCH,RIGHT_SWITCH,BUTTON_SWITCH,menu.navigateMenu,media)

#This subprocess call will make the 3.5mm  audio jack the primary target
#for outputting audio from.
#subprocess.call("/home/pi/Projects/audioJack.sh", shell=True)

#These two commands are for getting the data that are listed on the data.cfg 
alarmTime1 = linecache.getline("data.cfg", 2).rstrip('\n')
alarmTime2 = linecache.getline("data.cfg", 3).rstrip('\n')
コード例 #41
0
ファイル: pyGates.py プロジェクト: zacatac/BIOE147
def main():
    def drawScreen():   #updates all the gates (and this also sockets and cables), then draws them to the screen.
        pygame.draw.line(screen, black,(250,0),(250,screensize[1]),2)
        for Gate in gates:
            Gate.update()
        for creator in creators:
            creator.draw()
        for button in buttons:
            button.draw()
    pygame.init()
    screensize = (1200,700)
    screen = pygame.display.set_mode(screensize)
    
    # The FPS the simulation will run at.
    FPS = 30
    sleeptime = 1/float(FPS) #default sleep time


    creatorTypes = ["and","or","xor","nand","nor","xnor","not","switch","bulb"]

    gates = []  #in a sense, this is LIFO when it comes to drawing: the last element will be drawn on top.
    cables = []
    creators = [gateCreator() for x in range(len(creatorTypes))]
    
    for index, creator in enumerate(creators):
        creator.setType(creatorTypes[index])
        creator.setCords(75,index*50)#creator.rect.height)
        creator.setScreen(screen)
    
    compiler = button()
    compiler.setType("compile")
    compiler.setCords(10,len(creatorTypes)*50) # under the creators
    compiler.setScreen(screen)
    buttons = [compiler]

    running = True

    while running: #each iteration of this is one frame, unless gates are clicked (framerate will remain the same however)
        time.sleep(sleeptime)   #wait a little on each frame
        events = pygame.event.get()
        screen.fill(white)
        drawScreen()
        pygame.display.flip()
        for g in gates: #check if any gates should be deleted
            if g.rect.center[0]<100:
                g.SHUTDOWNEVERYTHING()
                gates.remove(g)
                    
        for event in events:                #handle events
            if event.type == 2 and event.key == 27:     #escape key pressed? -> quit
                running = False
            
            if event.type == pygame.MOUSEBUTTONDOWN:    #mouse pressed?
                mouse = pygame.mouse.get_pos()
                mousePressed = True
                for gC in creators:                     #check if creators have been pressed  -  if so, create gate.
                    if gC.pressed(mouse):
                        if gC.type == "bulb":
                            Gate = bulb()
                            cOffset = (gC.rect.topleft[0] - mouse[0], gC.rect.topleft[1]-mouse[1]) 
                            Gate.create(gC.type,(mouse[0]+cOffset[0],mouse[1]+cOffset[1]),screen)
                            gates.append(Gate)
                        elif gC.type == "switch":
                            Gate = switch()     #HAHA! It's not actually a gate!
                            cOffset = (gC.rect.topleft[0] - mouse[0], gC.rect.topleft[1]-mouse[1]) #mouse offset - we want to be able to drag the gate from wherever we press it
                            Gate.create(gC.type,(mouse[0]+cOffset[0],mouse[1]+cOffset[1]),screen)
                            gates.append(Gate)
                        else:
                            Gate = gate()
                            cOffset = (gC.rect.topleft[0] - mouse[0], gC.rect.topleft[1]-mouse[1]) #mouse offset - we want to be able to drag the gate from wherever we press it
                            Gate.create(gC.type,(mouse[0]+cOffset[0],mouse[1]+cOffset[1]),screen)
                            gates.append(Gate)
                    
                        offset = (Gate.rect.topleft[0] - mouse[0], Gate.rect.topleft[1]-mouse[1])
                        
                        while pygame.MOUSEBUTTONDOWN not in [ev.type for ev in pygame.event.get()]:
                            mouse = pygame.mouse.get_pos()
                            screen.fill(white)
                            Gate.setCords(mouse[0]+offset[0],mouse[1]+offset[1])
                            drawScreen()
                            pygame.display.flip()
                for b in buttons:
                    if b.pressed(mouse):
                        print "%s clicked" %b
                        if b.type == 'compile':
                            pc(gates)
                #### FOR THE LOVE OF ALL THAT IS HOLY DO NOT TOUCH THIS NEXT PART #####
                for Gate in gates:                      #check if gate was clicked
                    ev = pygame.event.get()
                    mouse = pygame.mouse.get_pos()
                    p = Gate.pressed(mouse)
                    if p:
                        if p == "main":         #gate was clicked "on body", not sockets so we dont need to worry about cable stuff here.
                            offset = (Gate.rect.topleft[0] - mouse[0], Gate.rect.topleft[1]-mouse[1])   #dragging offset again
                            while pygame.MOUSEBUTTONUP not in [ev.type for ev in ev]:
                                time.sleep(sleeptime)
                                mouse = pygame.mouse.get_pos()
                                Gate.setCords(mouse[0]+offset[0],mouse[1]+offset[1])
                                screen.fill(white)
                                drawScreen()
                                ev = pygame.event.get()
                                pygame.display.flip()
                            
                        elif p[:2] == "in":         # oh boy, someone clicked an input socket, now what do we do
                            
                            ### Disconnect logic - only inputs can be disconnected
                            if Gate.inSockets[int(p[2:])].connected:    #great, the socket already had a connection on it. lets change that..
                                print "disconnecting"
                                Cable = Gate.inSockets[int(p[2:])].attachedCables[0]
                                Cable.disconnect("in")
                                mousePressed = False
                                gatePressed = False
                                while not mousePressed:     #loop for dragging the loose cable around. also yes, I should probably have called them wires
                                        time.sleep(sleeptime)
                                        mouse = pygame.mouse.get_pos()
                                        screen.fill(white)
                                        drawScreen()
                                        Cable.drawCable(Cable.startSocket.rect.center,mouse)
                                        if pygame.MOUSEBUTTONDOWN in [ev.type for ev in pygame.event.get()]:
                                            print "mousedown"
                                            for g in gates:
                                                press = g.pressed(mouse)    #a socket was clicked, lets attach the cable here
                                                if press:
                                                    print "#############"
                                                    mousePressed = True
                                                    if press[:2]=="in":     #only worry about input sockets
                                                        print "connecting to ", g
                                                        inSock = g.inSockets[int(press[2:])]    #saving the socket for connecting to later
                                                        gatePressed = True
                                                        break
                                            if not gatePressed: #none of the gates were clicked, but the mouse was -> delete the cable.
                                                print "no gate pressed, deleting cable"
                                                mousePressed = True
                                                break
                                                    
                                        pygame.display.flip()
                                        if gatePressed: # this part could have probably gone where we check if a gate was pressed
                                            print "gate pressed after disconnect, should be reconnecting"
                                            if inSock.connect(Cable):
                                                Cable.setEndSocket(inSock)
                                                print "connected",Cable.endSocket," to ", Cable.startSocket, " with ", Cable
                                            break
                                        if mousePressed: # here we delete the cable
                                            Cable.startSocket.attachedCables.remove(Cable)
                                            Cable.endSocket.attachedCables = []
                                            Cable.startSocket = None
                                            Cable.endSocket = None
                                            break
                
                            #### connect logic for input -> outpout
                            else:   #whew, long if statement there
                                print "cable from in"
                                Cable = cable()
                                Cable.setScreen(screen)
                                Cable.setEndSocket(Gate.inSockets[int(p[2:])])
                                if Gate.inSockets[int(p[2:])].connect(Cable):       # this whole thing pretty much runs analog to the disconnect logic, just in reverse
                                    mousePressed = False
                                    gatePressed = False
                                    while not mousePressed:#(pygame.MOUSEBUTTONDOWN not in [ev.type for ev in pygame.event.get()]):
                                        time.sleep(sleeptime)
                                        mouse = pygame.mouse.get_pos()
                                        screen.fill(white)
                                        drawScreen()
                                        Cable.drawCable(mouse,Cable.endSocket.rect.center)
                                        if pygame.MOUSEBUTTONDOWN in [ev.type for ev in pygame.event.get()]:
                                            print "mousedown"
                                            for g in gates:
                                                if g.pressed(mouse)=="out":     #only connect if an output socket was clicked
                                                    print "connecting to output"
                                                    outSock = g.outSocket
                                                    gatePressed = True
                                                    break
                                                mousePressed = True
                                            if not gatePressed:
                                                print "mouse pressed, gates iterated, none pressed, disconnecting cable."
                                                Gate.inSockets[int(p[2:])].disconnect(Cable)
                                                
                                        pygame.display.flip()
                                        if gatePressed:
                                            if outSock.connect(Cable):
                                                Gate.inSockets[int(p[2:])].connect(Cable)
                                                Cable.setStartSocket(outSock)
                                                print "connected",Cable.startSocket," to ", Cable.endSocket, " with ", Cable
                                            else:
                                                Gate.inSockets[int(p[2:])].disconnect(Cable)
                                            break
                        ### connect logic for output -> input
                        else:
                            print "cable from out"
                            Cable = cable()
                            Cable.setScreen(screen)
                            Cable.setStartSocket(Gate.outSocket)
                            if Gate.outSocket.connect(Cable):
                                mousePressed = False
                                gatePressed = False
                                while not mousePressed:#(pygame.MOUSEBUTTONDOWN not in [ev.type for ev in pygame.event.get()]):
                                    time.sleep(sleeptime)
                                    mouse = pygame.mouse.get_pos()
                                    screen.fill(white)
                                    drawScreen()
                                    Cable.drawCable(mouse,Cable.startSocket.rect.center)
                                    if pygame.MOUSEBUTTONDOWN in [ev.type for ev in pygame.event.get()]: #little different here: we need to specify which input socket to connect to
                                        print "mousedown"
                                        for g in gates:
                                            press = g.pressed(mouse)    #this returns "in0" and "in1" depending on which socket was clicked
                                            print press
                                            if press =="in0":#(("in0" in [g.pressed(mouse) for g in gates])):
                                                print "connecting to input0"
                                                inSock = g.inSockets[0]
                                                gatePressed = True
                                                break
                                            elif press =="in1":#("in1" in [g.pressed(mouse) for g in gates]):
                                                print "connecting to input1"
                                                inSock = g.inSockets[1]
                                                gatePressed = True
                                                break
                                            mousePressed = True
                                        if not gatePressed:
                                            print "not connecting."
                                            Gate.outSocket.disconnect(Cable)
                                            break
                                    
                                    pygame.display.flip()
                                    if gatePressed:
                                        if inSock.connect(Cable):
                                            Cable.setEndSocket(inSock)
                                            print "connected",Cable.endSocket," to ", Cable.startSocket, " with ", Cable
                                        break
                        break
                ########################################
    pygame.quit()
コード例 #42
0
ファイル: main.py プロジェクト: littlegustv/pycharm-projects
        elev1.floor = int(elev1.y / 50) - 1
    for p in elev1.passengers:
        p.destFloor = elev1.floor
#        elev1.passengers.remove(p)
#        floors[elev1.floor].append(p)
#        waitTime[p.faction] += p.waiting
#        p.waiting = 0.0
#        p.floor = elev1.floor
#        waitqueue.append(p)


def start_game():
    global gamestate
    gamestate = "Game"

menuButton = button.button(window.width / 2 - 30, window.height/2 - 126, "PLAY", start_game)

alarmButton = button.button(296,500,"ALARM",elevator_alarm)
objects.append(alarmButton)

def person_spawn():
    if random.randint(0,100) < 1:
        name = names[random.randint(0,len(names)-1)]
        name = name[:len(name) - 1]
        fc = random.randint(0,6)
        if fc <= 1:
            faction = "Opener"
        elif fc <= 3:
            faction = "Closer"
        else:
            faction = "Neutral"