コード例 #1
0
        def on_play(button):
            for b in self.menu_buttons:
                self.objects.remove(b)

            try:
                complexity = int(ask(self.surface, game=self))
            except ValueError:
                complexity = -1

            while not 0 <= complexity <= 10:
                try:
                    complexity = int(
                        ask(self.surface,
                            game=self,
                            error='Write number in range [0; 10]'))
                except ValueError:
                    complexity = -1
            k_comp = complexity * 0.1 + 1
            self.ball.speed = self.ball.speed[0], k_comp * c.ball_speed
            c.ball_speed = self.ball.speed[1]

            self.paddle.speed = (2 - k_comp) * c.paddle_speed

            self.is_game_running = True
            self.start_level = True
コード例 #2
0
ファイル: grafico.py プロジェクト: mgbarotto/GraficarArboles
 def graficar(self, arb):
     assert hasattr(arb, 'raiz'), "El tipo arbol debe tener un atributo llamado \'raiz\'"
     pygame.init()
     scrolling=False
     self.screen= pygame.display.set_mode(self.screensize,pygame.RESIZABLE)
     pygame.display.set_caption("Grafico")
     self.dibujarArbol(arb)
     listo=False
     while not listo:
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 listo=True
             elif event.type==pygame.VIDEORESIZE:
                 self.screensize=event.dict['size']
                 screen=pygame.display.set_mode(self.screensize,pygame.RESIZABLE)
                 self.dibujarArbol(arb)
             elif event.type == pygame.MOUSEBUTTONDOWN and event.button==1:
                 scrolling=True
             elif event.type == pygame.MOUSEBUTTONUP and event.button==1:
                 scrolling=False
                 self.dibujarArbol(arb)
             elif event.type == pygame.MOUSEMOTION and scrolling:
                 self.offset[0]+=event.rel[0]
                 self.offset[1]+=event.rel[1]
             elif event.type == pygame.KEYDOWN:
                 
                     if event.key==pygame.K_ESCAPE:
                         listo=True
                         
                     elif event.key==pygame.K_h:
                         self.ayuda=not self.ayuda
                         
                     elif event.key==pygame.K_d:
                         n=inputbox.ask(self.screen, 'Eliminar numero')
                         if n:
                             n=int(n)
                             arb.borrar(n)
                         
                     elif event.key==pygame.K_LEFT:
                         if self.separacion<10:
                             self.separacion+=1
                         
                     elif event.key==pygame.K_RIGHT:
                         if self.separacion>1:
                             self.separacion-=1
                     elif event.key==pygame.K_SPACE:
                         self.offset=[0,0]
                     elif event.key==pygame.K_a:
                         n=inputbox.ask(self.screen, 'Insertar numero')
                         if n:
                             n=int(n)
                             arb.insertar(n)
                     elif event.key==pygame.K_r:
                         n=inputbox.ask(self.screen, 'Cant. de numeros a ingresar')
                         if n:
                             n=int(n)
                             azar(arb,n)
                     self.dibujarArbol(arb)                   
     pygame.display.quit()
     pygame.quit()
コード例 #3
0
    def dataentryscreen(self):

        intro = True
        self.game_display.fill(menu_background)
        pygame.display.update()

        self.textwriting.welcome()
        self.textwriting.entryinstructions()

        self.exp_tools.inp_id = (inputbox.ask(self.game_display, 'Your ID'))
        self.exp_tools.inp_gender = (inputbox.ask(self.game_display, 'Gender'))
        self.exp_tools.inp_age = (inputbox.ask(self.game_display, 'Age'))

        pygame.display.update()
        self.clock.tick(self.menu_tick)

        while intro:

            for event in pygame.event.get():

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        intro = False

                    if event.key == pygame.K_RETURN:
                        intro = False
コード例 #4
0
ファイル: plansym.py プロジェクト: pawelzell/plansym
    def wczytaj_mase(self, i, n):
        screen = self.dane.screen
        bialy = (255, 255, 255)
        czarny = (0, 0, 0)
        screen.fill(czarny)
        self.rysowanie.rysuj_naglowek("PlanSym Load data: New planet " + str(i) + " / " + str(n))
        self.rysowanie.rysuj_planety()

        self.rysowanie.rysuj_panel_dolny("Set mass of planet")
        font = pygame.font.SysFont("Calibri", 60)
        inputbox.display_box_disabled(screen, (450, screen.get_height() - 120, 70, 60), "")
        text = font.render("*10^", True, czarny)
        screen.blit(text, [325, screen.get_height() - 120])
        pygame.display.flip()
        m_text = inputbox.ask(screen, (20, screen.get_height() - 120, 300, 60), "m = ", self.dane)
        m = float(m_text)

        self.rysowanie.rysuj_panel_dolny("Set mass of planet")
        inputbox.display_box_disabled(screen, (20, screen.get_height() - 120, 300, 60), "m = " + m_text)
        screen.blit(text, [325, screen.get_height() - 120])
        pygame.display.flip()
        w_text = inputbox.ask(screen, (450, screen.get_height() - 120, 70, 60), "", self.dane)
        w = int(w_text)
        c = 1
        for i in range(1, w + 1):
            c *= 10
        return m * c
コード例 #5
0
    def UserPass(self):

        userp = True
        #noStartGame = True

        while userp:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:

                    #s.close()
                    pygame.quit()
                    quit()

            self.gameDisplay.blit(self.background, (0, 0))

            ##SERVER LOGIN##
            self.username = inputbox.ask(self.gameDisplay, "UserName")
            password = inputbox.ask(self.gameDisplay, "Password")

            self.s.sendto("User:?:?".encode(), self.server)
            self.tLock.acquire()
            self.tLock.release()
            time.sleep(0.2)
            #self.shutdown = True
            #rt.join()
            #self.s.close()

            self.waitingRoom()
            """
            password = hashlib.md5(password.encode()).hexdigest()
            print("PASSWORD BEFORE SENDING: ",password," TYPE: ",type(password))
            s.sendto("Login:{}:{}".format(username,password).encode(),server)
            while noStartGame == True:
                data, addr = s.recvfrom(1024)
                data = data.decode()
                data = data.split(":")
                if data[0] == "Gameloop":
                    s.sendto("User:?:?".encode(),server)
                    data, addr = s.recvfrom(1024)
                    data = data.decode()
                    data = data.split(":")
                    if data[0] == "User1":
                        print("USER!!!")
                        user1 = True
                        waitingRoom()
                    if data[0] == "User2":
                        user2 = True
                        waitingRoom()
                
                if data[0] == "Invalidpass":
                    InvalidPass()
                
                
                    
            ##SERVER LOGIN##
            """

            pygame.display.update()
            self.clock.tick(15)
コード例 #6
0
ファイル: helpers.py プロジェクト: gurshabad/scrabby
def getDetails(SECONDHALF, SCREEN, wordListTrie, playerRack):
	FONT = pygame.font.SysFont('Andale Mono', 22)

	playerRack.showRack()

	shuffle = inputbox.ask(SCREEN, SECONDHALF, "SHUFFLE? (YES/NO)")
	if(len(shuffle) != 0): shuffle = shuffle.upper()[0]
	if(shuffle == 'Y' or shuffle == 'N'):
		if(shuffle == 'Y'):
			shuffle = True

			shuffleLetters = inputbox.ask(SCREEN, SECONDHALF, "LETTERS:")
			if(verifyShuffle(shuffleLetters, playerRack)):
				shuffleLetters = ''.join([ "*" if letter == ' ' else letter for letter in shuffleLetters ])
				return ("Shuffle", shuffleLetters.lower())

			else:
				print "Shuffle-Letters: INCORRECT"
				SECONDHALF.blit(FONT.render("INCORRECT LETTERS! TRY AGAIN!", 1, (255,0,0)), ((SECONDHALF.get_width() / 2) - 200, (SECONDHALF.get_height() / 2) + 170))
				SCREEN.blit(SECONDHALF, (500,0))
				pygame.display.flip()
				time.sleep(3)
				return False
		
		else:
			shuffle = False

			wordPlayed = inputbox.ask(SCREEN, SECONDHALF, "WORD?")
			if(wordListTrie.query(wordPlayed.lower())): #Check if legit word
				print "Word? " + wordPlayed
				
				positionPlayed = inputbox.ask(SCREEN, SECONDHALF, "POSITION? (ROW COL)")
				sanitizedPos = sanitizePosition(positionPlayed)
				if(sanitizedPos != False): #Check if legit position
					print "Position? " + positionPlayed
					print "After Sanitization: "+str(sanitizedPos)

					playHorizontal = inputbox.ask(SCREEN, SECONDHALF, "ACROSS? (YES/NO)")
					playHorizontal = (playHorizontal).upper()
					if(playHorizontal != "YES" and playHorizontal != "NO" and playHorizontal != "Y" and playHorizontal != "N"):
						print "Across? WEIRD INPUT"
						SECONDHALF.blit(FONT.render("WEIRD INPUT! TRY AGAIN!", 1, (255,0,0)), ((SECONDHALF.get_width() / 2) - 200, (SECONDHALF.get_height() / 2) + 170))
						SCREEN.blit(SECONDHALF, (500,0))
						pygame.display.flip()
						time.sleep(3)
						return False
			
					else:
						playHorizontal = playHorizontal[0]
						if playHorizontal == 'Y': print "Horizontal? Y"; playHorizontal = True
						else: print "Horizontal? N"; playHorizontal = False
						return ("Move", wordPlayed.lower(), sanitizedPos, playHorizontal)
				else:
					print "Position? " + positionPlayed + " - Invalid Position!"
					SECONDHALF.blit(FONT.render("Invalid Position! TRY AGAIN!", 1, (255,0,0)), ((SECONDHALF.get_width() / 2) - 200, (SECONDHALF.get_height() / 2) + 170))
					SCREEN.blit(SECONDHALF, (500,0))
					pygame.display.flip()
					time.sleep(3)
					return False
コード例 #7
0
ファイル: main.py プロジェクト: sk364/N_by_N_Tic_Tac_Toe
def run_game(mode):
	global player, first_play, n

	if mode==1:
		while player not in [0,1]:
			x = inputbox.ask(screen,"Press 1 for circle, 0 for cross")
                	if len(x) == 1 and x in ['1','0']:
                        	player = int (x)

		while first_play not in [0,1]:
			x = inputbox.ask(screen,"Press 0 for cross to play first, 1 for circle")
	                if len(x) == 1 and x in ['1','0']:
        	                first_play = int (x)
	
	if mode!=3:
		while n<=0 or n>8:
			x = inputbox.ask(screen, "Enter N")
			if len(x)==1 and x in [str(i) for i in xrange(1,8)]:
				n = int (x)

	board = init_board()
	draw_board(board,SIZE,n)

	if first_play == opp[player] and mode!=2:
		cpu_turn(board,opp[player], mode)

	game_loop = True
	while game_loop:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()

			if event.type == pygame.MOUSEBUTTONDOWN and mode!=2:
				x,y = pygame.mouse.get_pos()
				p = get_square(x,y)
				if board[p[0]][p[1]] == -1:
					board[p[0]][p[1]] = player
			
					draw_board(board,SIZE,n)

					end = check_game_end(board, player, mode)

					if end==2:
						end = cpu_turn(board,opp[player], mode)
						if end != 2:
							first_play = not first_play
							run_game(3)
					else:
						first_play = not first_play
						run_game(3)			

		if mode==2:
			end = cpu_turn(board,player, mode)
			if end==2:
				pass
			pygame.time.wait(100)
			player = opp[player]
コード例 #8
0
def startGame3(DISPLAYSURF):

    fpsClock = pygame.time.Clock()
    SCREEN_WIDTH = 600
    #DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH,400), 0, 32)
    pygame.display.set_caption('Animation')

    #btn = Button('Input the values')

    clock = pygame.time.Clock()
    background = pygame.image.load('Images/game1.jpg')

    run = True

    while run:
        DISPLAYSURF.blit(background, (0, 0))
        mouse = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()
            #elif event.type == pygame.MOUSEBUTTONDOWN:
            #	if btn.obj.collidepoint(mouse):
            countInputs = 1
            m1 = inputbox.ask(DISPLAYSURF, "Mass of object1, m1", countInputs)
            m1_ = float(m1)
            countInputs = countInputs + 5
            u1 = inputbox.ask(DISPLAYSURF, "InitialVelocity of 1,u1",
                              countInputs)
            u1_ = float(u1)
            countInputs = countInputs + 5
            m2 = inputbox.ask(DISPLAYSURF, "Mass of object2, m2", countInputs)
            m2_ = float(m2)
            countInputs = countInputs + 5
            u2 = inputbox.ask(DISPLAYSURF, "InitialVelocity of 2,u2",
                              countInputs)
            u2_ = float(u2)
            if (m1_ <= 0 or m2_ <= 0):
                errorScreen.errorScreen(DISPLAYSURF, "Invalid Mass entered")
            v1 = (((m1_ - m2_) * u1_) + (2 * m2_ * u2_)) / (m1_ + m2_)
            v1_ = round(v1, 2)
            v2 = ((2 * m1_ * u1_) - ((m1_ - m2_) * u2_)) / (m1_ + m2_)
            v2_ = round(v2, 2)
            background = pygame.image.load('Images/game3/background.png')
            DISPLAYSURF.blit(background, (0, 0))
            font = pygame.font.Font(None, 20)
            text = font.render(
                "Final Velocity of object A =" + str(v1_) +
                "metre/sec and Final Velocity of object B =" + str(v2_) +
                "metre/sec", 1, (10, 10, 10))
            animation3(DISPLAYSURF, 'right', text, u1_, u2_, v1_, v2_)
            run = False
        #btn.draw(DISPLAYSURF, mouse, (185,80,200,20), (225,83))
        pygame.display.update()
        clock.tick(60)
コード例 #9
0
ファイル: names.py プロジェクト: creends/Palets-Game
def ask_names_local():
    screen = pygame.display.get_surface()
    names = [None, None]

    screen.fill(0xffffff)

    names[0] = inputbox.ask(screen, "Joueur 1", 6)
    if names[0] == "":
        return names
    names[1] = inputbox.ask(screen, "Joueur 2", 6)
            
    return names
コード例 #10
0
def startGame2(DISPLAY_SURF):
    print("INSIDE GAME2.py")
    btn_start = pygame.image.load('Images/buttons/start.png')

    clock = pygame.time.Clock()
    background = pygame.image.load('Images/game2/1.png')
    run = True
    while run:
        DISPLAY_SURF.blit(background, SCREEN_TOPLEFT)
        mouse = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if rect_start.collidepoint(mouse):
                    countInputs = 1

                    mass = inputbox.ask(DISPLAY_SURF, "Mass, M", countInputs)
                    mass = float(mass)
                    if mass <= 0:
                        errorScreen.errorScreen(DISPLAY_SURF,
                                                "Mass must be Positve")
                    countInputs = countInputs + 5
                    initial_velocity = inputbox.ask(DISPLAY_SURF,
                                                    "Coeff. of Friction, u",
                                                    countInputs)
                    initial_velocity = float(initial_velocity)
                    if initial_velocity > 1:
                        errorScreen.errorScreen(DISPLAY_SURF,
                                                "Invalid coeff. of friction")
                    if initial_velocity < 0:
                        errorScreen.errorScreen(DISPLAY_SURF,
                                                "Invalid coeff. of friction")
                    countInputs = countInputs + 5
                    force = inputbox.ask(DISPLAY_SURF, "Force, F", countInputs)
                    force = float(force)
                    final_velocity = initial_velocity * force
                    weight = mass * 9.8

                    if (weight > final_velocity):
                        font = pygame.font.Font(None, 36)
                        text = font.render("The block will fall down.", 1,
                                           (10, 10, 10))
                        animation2(DISPLAY_SURF, 'down', text)
                    else:
                        res = pygame.image.load('Images/game2/5.png')
                        DISPLAY_SURF.blit(res, SCREEN_TOPLEFT)
                        endScreen(DISPLAY_SURF, ":)")

        rect_start = DISPLAY_SURF.blit(btn_start, (220, 303))

        pygame.display.update()
        clock.tick(60)
コード例 #11
0
ファイル: game3.py プロジェクト: gopal10sep/SimPhy-1
def startGame3(DISPLAYSURF):
			
	
	fpsClock = pygame.time.Clock()
	SCREEN_WIDTH = 600
	#DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH,400), 0, 32)
	pygame.display.set_caption('Animation')
	

	#btn = Button('Input the values')
	
	clock = pygame.time.Clock()
	background=pygame.image.load('Images/game1.jpg')

	run = True
	
	while run:
		DISPLAYSURF.blit(background,(0,0))
		mouse = pygame.mouse.get_pos()
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
				pygame.quit()
				sys.exit()
			#elif event.type == pygame.MOUSEBUTTONDOWN:
			#	if btn.obj.collidepoint(mouse):
			countInputs=1;
			m1 = inputbox.ask(DISPLAYSURF, "Mass of object1, m1",countInputs)
			m1_ = float (m1)
			countInputs=countInputs+5;
			u1 = inputbox.ask(DISPLAYSURF, "InitialVelocity of 1,u1",countInputs)
			u1_ = float (u1)
			countInputs=countInputs+5;
			m2 = inputbox.ask(DISPLAYSURF, "Mass of object2, m2",countInputs)
			m2_ = float (m2)
			countInputs=countInputs+5;
			u2 = inputbox.ask(DISPLAYSURF, "InitialVelocity of 2,u2",countInputs)
			u2_ = float (u2)
			if(m1_<=0 or m2_<=0):
				errorScreen.errorScreen(DISPLAYSURF,"Invalid Mass entered")
			v1 = (((m1_ - m2_)*u1_) + (2*m2_*u2_))/(m1_+m2_)
			v1_ = round (v1,2)
			v2 = ((2*m1_*u1_) - (( m1_ - m2_)* u2_))/(m1_+m2_)
			v2_ = round (v2,2)
			background = pygame.image.load('Images/game3/background.png')
			DISPLAYSURF.blit(background,(0,0))
			font = pygame.font.Font(None, 20)
			text = font.render("Final Velocity of object A ="+str(v1_)+"metre/sec and Final Velocity of object B ="+str(v2_)+"metre/sec", 1, (10, 10, 10))
			animation3(DISPLAYSURF,'right',text,u1_,u2_,v1_,v2_)
			run = False				
		#btn.draw(DISPLAYSURF, mouse, (185,80,200,20), (225,83))
		pygame.display.update()
		clock.tick(60)
コード例 #12
0
def HighScore(file, score):
    highscore_name, highscore = readInHighScore("scores.txt")
    if score > highscore:
        name = inputbox.ask(canvas, "NEW HIGH SCORE! Enter your name")
    elif score == highscore:
        name = inputbox.ask(canvas, "YOU TIED THE HIGH SCORE! Enter your name")
    elif score < highscore:
        name = inputbox.ask(canvas, "Enter your name")
    if name == None or len(name) == 0:
        return

    recordScore("scores.txt", name, score)
    return
コード例 #13
0
def UserPass():
    global user1
    global user2
    global username
    global cur
    global con
    global server
    userp = True
    noStartGame = True

    while userp:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:

                s.close()
                pygame.quit()
                quit()

        gameDisplay.blit(background, (0, 0))

        ##SERVER LOGIN##
        username = inputbox.ask(gameDisplay, "UserName")
        password = inputbox.ask(gameDisplay, "Password")
        password = hashlib.md5(password.encode()).hexdigest()
        print("PASSWORD BEFORE SENDING: ", password, " TYPE: ", type(password))
        s.sendto("Login:{}:{}".format(username, password).encode(), server)
        while noStartGame == True:
            data, addr = s.recvfrom(1024)
            data = data.decode()
            data = data.split(":")
            if data[0] == "Gameloop":
                s.sendto("User:?:?".encode(), server)
                data, addr = s.recvfrom(1024)
                data = data.decode()
                data = data.split(":")
                if data[0] == "User1":
                    print("USER!!!")
                    user1 = True
                    waitingRoom()
                if data[0] == "User2":
                    user2 = True
                    waitingRoom()

            if data[0] == "Invalidpass":
                InvalidPass()

        ##SERVER LOGIN##

        pygame.display.update()
        clock.tick(15)
コード例 #14
0
ファイル: gui.py プロジェクト: staticbg/Game_of_Chess
def menu_window():
    dimension = [1000, 600]
    screen = pygame.display.set_mode(dimension)
    screen.fill(brown)
    pygame.display.set_caption("Enter players names")
    player_1 = inputbox.ask(screen, "Player 1 name")
    player_2 = inputbox.ask(screen, "Player 2 name")
    print(player_1, player_2)
    global board
    board = MultiPlayer(player_1, player_2)
    global initialized
    initialized = True
    draw_board()
    pygame.display.flip()
コード例 #15
0
ファイル: game2.py プロジェクト: gopal10sep/SimPhy-1
def startGame2(DISPLAY_SURF):
	print ("INSIDE GAME2.py")
	btn_start = pygame.image.load('Images/buttons/start.png')

	clock = pygame.time.Clock()
	background=pygame.image.load('Images/game2/1.png')
	run = True
	while run:
		DISPLAY_SURF.blit(background,SCREEN_TOPLEFT)
		mouse = pygame.mouse.get_pos()
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
			elif event.type == pygame.MOUSEBUTTONDOWN:
				if rect_start.collidepoint(mouse):
					countInputs = 1;
											
					mass = inputbox.ask(DISPLAY_SURF, "Mass, M",countInputs)
					mass = float (mass)
					if mass <= 0 :
						errorScreen.errorScreen(DISPLAY_SURF,"Mass must be Positve")
					countInputs = countInputs + 5;
					initial_velocity = inputbox.ask(DISPLAY_SURF, "Coeff. of Friction, u",countInputs)
					initial_velocity = float (initial_velocity)
					if initial_velocity > 1 :
						errorScreen.errorScreen(DISPLAY_SURF,"Invalid coeff. of friction")
					if initial_velocity < 0 :
						errorScreen.errorScreen(DISPLAY_SURF,"Invalid coeff. of friction")
					countInputs = countInputs + 5;
					force = inputbox.ask(DISPLAY_SURF, "Force, F",countInputs)
					force = float (force)
					final_velocity = initial_velocity * force
					weight = mass * 9.8
						
					if ( weight > final_velocity):
						font = pygame.font.Font(None, 36)
						text = font.render("The block will fall down.", 1, (10, 10, 10))
						animation2(DISPLAY_SURF,'down',text)
					else:
						res = pygame.image.load('Images/game2/5.png')
						DISPLAY_SURF.blit(res,SCREEN_TOPLEFT)
						endScreen(DISPLAY_SURF,":)")
					
		rect_start = DISPLAY_SURF.blit(btn_start ,(220,303))

		

		pygame.display.update()
		clock.tick(60)
コード例 #16
0
ファイル: Graphismes.py プロジェクト: GeoffroyG/TDLOG
def displayLosingMenu(DISPLAYSURF, FPSCLOCK, timer):
    """When the game is over, displays a message to the player. """
    lost = True
    DISPLAYSURF.fill((0,0,0))
    mouseClicked = False

    while lost:
        text = font_title.render("YOU LOST : CLICK TO START AGAIN", 1, RED)
        textposTitle = text.get_rect(centerx = WINDOWWIDTH / 2,
                                     centery = WINDOWHEIGHT / 2)
        DISPLAYSURF.blit(text, textposTitle)
        for event in pygame.event.get(): # event handling loop
            if event.type == MOUSEBUTTONUP:
                mousex, mousey = event.pos
                mouseClicked = True
            elif event.type == QUIT or (event.type == KEYUP \
                                        and event.key == K_ESCAPE):
                pygame.quit()
                os.sys.exit()
        pygame.display.update()
        FPSCLOCK.tick(FPS)

        if mouseClicked:
            DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
            answer = inputbox.ask(DISPLAYSURF, "Your name")
            time_min, time_sec = convert_time(timer//FPS)
            date = get_date_str()
            write_leaderboard(LEADERBOARDFILE, answer, time_min, time_sec, date)
            lost = False
コード例 #17
0
ファイル: pong.py プロジェクト: CodeClubLux/BBQjam
def main():
	screen = pygame.display.set_mode((WIDTH, HEIGHT))
	pygame.display.set_caption("Pygame Tests :)")

	backgroundImageOrig = loadImage('images/bg.png')
	backgroundImage = pygame.transform.scale(backgroundImageOrig, (WIDTH, HEIGHT))
	answer = inputbox.ask(screen, "Your name")
	ball = Ball()
	gamePaddle = Paddle(30)

	clock = pygame.time.Clock()

	while True:
		time = clock.tick(60)
		keys = pygame.key.get_pressed()
		for events in pygame.event.get():
			if events.type == QUIT:
				sys.exit(0)

		ball.refresh(time, gamePaddle)
		gamePaddle.move(time, keys)
		screen.blit(backgroundImage, (0,0))
		screen.blit(ball.image, ball.rect)
		screen.blit(gamePaddle.image, gamePaddle.rect)
		pygame.display.flip()
	return 0
コード例 #18
0
    def new(self):
        #start a new game
        self.score = 0
        self.die = 0
        self.screen_level = 300
        self.TW = width / 2
        self.all_sprites = pygame.sprite.Group()
        self.floors = pygame.sprite.Group()
        self.zombies = pygame.sprite.Group()
        self.big_guy = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()

        self.mob_time = 0
        self.bs = floor(base[0], base[1])
        self.all_sprites.add(self.bs)
        self.floors.add(self.bs)
        for flr in floor_list:
            self.f = floor(flr[0], flr[1])
            self.all_sprites.add(self.f)
            self.floors.add(self.f)
        self.player = Player(self)
        self.all_sprites.add(self.player)
        self.name = inputbox.ask(self.screen, " Name")

        self.run()
コード例 #19
0
def run_cpu_vs_cpu():
	SIZE = 400

	depth = 1
	
        n = int (inputbox.ask(screen, "Enter N"))

        board = init_board(n)

        draw_board(board,SIZE,n)

	player = 1

	while True:
                for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                                pygame.quit()
                                sys.exit()


                        cpu_turn(board,player,n,depth,SIZE)

			pygame.time.wait(100)
	
			player = opp[player]
コード例 #20
0
ファイル: Graphismes.py プロジェクト: GeoffroyG/TDLOG
def displayLosingMenu(DISPLAYSURF, FPSCLOCK, timer):
    """When the game is over, displays a message to the player. """
    lost = True
    DISPLAYSURF.fill((0, 0, 0))
    mouseClicked = False

    while lost:
        text = font_title.render("YOU LOST : CLICK TO START AGAIN", 1, RED)
        textposTitle = text.get_rect(centerx=WINDOWWIDTH / 2,
                                     centery=WINDOWHEIGHT / 2)
        DISPLAYSURF.blit(text, textposTitle)
        for event in pygame.event.get():  # event handling loop
            if event.type == MOUSEBUTTONUP:
                mousex, mousey = event.pos
                mouseClicked = True
            elif event.type == QUIT or (event.type == KEYUP \
                                        and event.key == K_ESCAPE):
                pygame.quit()
                os.sys.exit()
        pygame.display.update()
        FPSCLOCK.tick(FPS)

        if mouseClicked:
            DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
            answer = inputbox.ask(DISPLAYSURF, "Your name")
            time_min, time_sec = convert_time(timer // FPS)
            date = get_date_str()
            write_leaderboard(LEADERBOARDFILE, answer, time_min, time_sec,
                              date)
            lost = False
コード例 #21
0
def play():
                
                global screen,hover
                font = pygame.font.SysFont('Arial',74)
                title = font.render("Play Game", True, RED)
                screen.blit(title,(45,160))
                screen.blit(hover,(15,100))
                pygame.draw.circle(screen, GREEN, (125,510), 122, 30)
                
                for event in pygame.event.get(): # User did something
                   
                    if event.type == pygame.MOUSEBUTTONDOWN or event.type==pygame.MOUSEBUTTONUP:
                        
                        print "You pressed play game"
                        answer = inputbox.ask(screen, "Your name")
                        
                        pygame.mixer.music.stop()
                        pratik(answer)
                        
                    else:
                        break
                    
                    

                secs=0
                milli=clock.tick()
                sec=milli/1000.
                secs+=sec
                d=speed*sec*0.5
コード例 #22
0
ファイル: saveName.py プロジェクト: safaahusin/weWillBack
    def __init__(self):
        #music.stop()
        #thread.start_new_thread(music.playSong,('Call of Duty 4 Modern Warfare OST - Game Over.mp3',))
        title_arabic = u'\uFEB3\uFEE8\uFECC\uFEEE\uFEA9'.encode('utf8')
        pygame.display.set_caption(title_arabic)
        bg = pygame.image.load('haba.jpg')

        while True:
            pygame.display.update()
            self.screen.blit(bg, (0, 0))
            self.screen.blit(
                self.Text.render("Enter Your Name ... ", True, (0, 0, 0)),
                (200, 300))
            self.screen.blit(
                self.Text.render("Welcome ^___^ ", True, (0, 0, 128)),
                (150, 150))
            inp = str(inputbox.ask(self.screen, ''))
            if (not (inp == "")):
                f = file_module.MyFile()
                f.writeName(inp)
                option.Scale_Test.level
                fun.puzzle(option.Scale_Test.level, inp)
                #intro_level.intro_level(option.Scale_Test.level,inp)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
コード例 #23
0
def writeStatus(dif, rec, time):  # 写入数据(只有赢了才会
    screen = pygame.display.set_mode((320, 240))
    name = inputbox.ask(screen, 'Type your name here')
    exf = open('status.csv', 'a', newline='')
    writer = csv.writer(exf)
    writer.writerow([name, dif, rec, time])
    exf.close()
コード例 #24
0
ファイル: Plane_GamePage.py プロジェクト: vitogitgit/pygame
def cover_leaderboard(userScore, screen):
    score_list, name_list = [], []
    with open('Leaderboard.txt', 'r') as f:
        txt_lines = f.readlines()
        for line in txt_lines:
            line = line.split('-%-')
            score_list.append(int(line[1][:-1]))
            name_list.append(line[0])
    updateList = False
    for i in score_list:
        if userScore > i: updateList = True
    if not updateList:
        return
    userName = inputbox.ask(screen, 'Your name')
    userName = userName[:7].title()
    if '' == userName: userName = '******'
    score_list.pop()
    name_list.pop()
    score_list.append(userScore)
    score_list.sort(reverse=True)
    for i, eachScore in enumerate(score_list):
        if eachScore == userScore: userIndex = i
    name_list.insert(userIndex, userName)
    with open('Leaderboard.txt', 'w') as f:
        for i in range(5):
            f.write(name_list[i] + '-%-' + str(score_list[i]) + '\n')
コード例 #25
0
ファイル: city.py プロジェクト: Skycker/round-city-round
def unless_player_press_smth():
    """Ф-я "ставит игру на паузу" до нажатия кнопки игроком. Обрабатывает эти нажатия"""
    while True:
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                # Полноэкранный режим или оконный?
                if event.key == K_f:
                    pygame.display.set_mode((W_WIDTH, W_HEIGH), pygame.FULLSCREEN)
                    screen.blit(start_background, (0, 0))
            if event.type == MOUSEMOTION:
                for btn in buttons:
                    if btn.rect.collidepoint(pygame.mouse.get_pos()):
                        btn.changeState(1)
                    else:
                        btn.changeState(0)
            elif event.type == MOUSEBUTTONDOWN:
                if new_game:
                    if btn_start_game.rect.collidepoint(pygame.mouse.get_pos()):
                        global player_name
                        player_name = inputbox.ask(screen, "Your name?")
                        return
                if btn_exit.rect.collidepoint(pygame.mouse.get_pos()):
                    pygame.quit()
                    sys.exit()
                if not new_game:
                    if btn_finish_game.rect.collidepoint(pygame.mouse.get_pos()):
                        return 
                
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        for btn in buttons:
            btn.rander(screen)
            set_text(screen, btn.text, 20, (btn.x+27, btn.y+7), 1, btn.text_color )
        pygame.display.flip()
コード例 #26
0
ファイル: 2048_.py プロジェクト: arpitj938/2048_
def showStartScreen():
    #the start screen
    titleFont = pygame.font.Font('freesansbold.ttf', 100)
    titleSurf1 = titleFont.render('2048', True, WHITE, ORANGE)
    global n
    global boxsize
    message = 'Enter level(n*n) from 2 to n'
    while (n < 2):
        n = int(inputbox.ask(screen, message))
        if (n < 2):
            message = "Enter value more than 2"
            print "n<2"
    boxsize = min(WINDOWWIDTH, WINDOWHEIGHT) // n
    drawPressKeyMsg()

    while True:
        screen.fill(BGCOLOR)
        display_rect = pygame.transform.rotate(titleSurf1, 0)
        rectangle = display_rect.get_rect()
        rectangle.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
        screen.blit(display_rect, rectangle)

        drawPressKeyMsg()

        if checkForKeyPress():
            pygame.event.get()
            return
        pygame.display.update()
        FPSCLOCK.tick(FPS)
コード例 #27
0
ファイル: game.py プロジェクト: Joesv/python-platformer
def main():
    pygame.init()
    screen = pygame.display.set_mode((screenWidth, screenHeight))
    pygame.display.set_caption("Platformer")


    answer = inputbox.ask(screen, "Your name")
    print("Player answered: "+answer)


    player = Player()
    levelList = []
    levelList.append(Level01(player))
    currentLevelNo = 0
    currentLevel = levelList[currentLevelNo]

    activeSpriteList = pygame.sprite.Group()
    player.level = currentLevel
    player.rect.x = 340
    player.rect.y = screenHeight - player.rect.height
    activeSpriteList.add(player)
    done = False

    clock = pygame.time .Clock()
    while not done:
        for event in pygame.event.get():
            if event.type == QUIT:
                done = True
            if event.type == KEYDOWN:
                if event.key == K_LEFT:
                    print("left key ")
                    player.left = True
                    player.stop = False
                    player.move()
                if event.key == K_RIGHT:
                    print("right key")
                    player.right = True
                    player.stop = False
                    player.move()
                if event.key == K_UP:
                    player.jump()
            if event.type == KEYUP:
                if event.key == K_RIGHT and player.dx < 0:
                    player.stop = True
                    player.move()
                if event.key == K_LEFT and player.dx > 0:
                    player.stop = True
                    player.move()
        activeSpriteList.update()
        currentLevel.update()
        if player.rect.right > screenWidth:
            player.rect.right = screenWidth
        if player.rect.left < 0:
            player.rect.left = 0
        currentLevel.draw(screen)
        activeSpriteList.draw(screen)

        clock.tick(60)
        pygame.display.flip()
    pygame.quit()
コード例 #28
0
ファイル: inputbox_menu.py プロジェクト: RovisLab/GridSim
    def ask_boxes(self):
        current_box = 0

        while self.exit is False:
            self.display_boxes()
            answear = inputbox.ask(self.screen,
                                   self.question_list[current_box],
                                   self.inputs[current_box],
                                   position=self.positions[current_box],
                                   nr_rows=self.nr_rows,
                                   current_box=current_box)

            if type(answear) is tuple:
                if type(answear[1]) is bool:
                    if answear[1] is True:
                        self.inputs[current_box] = answear[0]
                        inputbox.return_to_menu()
                    elif answear[1] is False:
                        self.inputs[current_box] = answear[0]
                        break
                else:
                    self.inputs[current_box] = answear[0]
                    current_box = answear[1]
            elif type(answear) is str:
                self.inputs[current_box] = answear

        return self.inputs
コード例 #29
0
 def vncRequestPassword(self):
     if self.factory.password is not None:
         self.sendPassword(self.factory.password)
     else:
         #XXX hack, this is blocking twisted!!!!!!!
         screen = pygame.display.set_mode((220,40))
         screen.fill((255,100,0)) #redish bg
         self.sendPassword(inputbox.ask(screen, "Password", password=1))
コード例 #30
0
ファイル: vncviewer.py プロジェクト: Jupiterrr/ok-lily
 def vncRequestPassword(self):
     if self.factory.password is not None:
         self.sendPassword(self.factory.password)
     else:
         #XXX hack, this is blocking twisted!!!!!!!
         screen = pygame.display.set_mode((220,40))
         screen.fill((255,100,0)) #redish bg
         self.sendPassword(inputbox.ask(screen, "Password", password=1))
コード例 #31
0
ファイル: core.py プロジェクト: JohnathonNow/PyConquest
 def handleKeyUp(self, k):
     if k == 'space':  #move cortez
         if self.grid.selected and self.grid.selected[0].known:
             self.moveCortez(self.xt, self.yt)
     elif k == 'c':  #send troops
         if self.grid.selected:
             c = inputbox.ask(self.screen, 'How many men?')
             self.sendMen(self.xt, self.yt, c)
コード例 #32
0
def main():

    inmain = True

    i = 0;
    clock = pygame.time.Clock()
    Display.blit(newLogo, (0,10))   

    Display.blit(newLogo, (800,10))
    Display.blit(newCQ, (250,-50))

    while inmain:
        for event in pygame.event.get():
            button("Stats",0,200,display_w/2, 50, cqorange, cqblue, "Stats")
            button("Question",display_w/2,200,display_w/2, 50, cqblue, cqblue, "Question")
            while i < 7:
                inp = inputbox.ask(Display, 'Question',-100, -50)
                i = 1
                inp = inputbox.ask(Display, 'A)',-100, -10)
                i = 2
                inp = inputbox.ask(Display, 'B)',-100, 20)
                i = 3
                inp = inputbox.ask(Display, 'C)',-100, 50)
                i = 4
                inp = inputbox.ask(Display, 'D)',-100, 80)
                i = 5
                inp = inputbox.ask(Display, 'Exp Reward',-100, 110)
                i = 6
                inp = inputbox.ask(Display, 'Money Reward',-100, 140)
                i = 7
            button("Send",display_w/4,600,display_w/2, 50, cqorange, cqblue, "Send")
            pygame.display.flip()
            
    pygame.display.update()
    clock.tick(20)
コード例 #33
0
ファイル: main.py プロジェクト: sk364/N_by_N_Tic_Tac_Toe
def main():
	screen.fill((0,0,0))
	ch = -1
	while ch not in [1,2]:
		x = inputbox.ask(screen,"Press 1 for CPU v/s You and 2 for CPU v/s CPU")
		if len(x) == 1 and x[0] in ['1','2']:
			ch = int (x[0])

	run_game(ch)
コード例 #34
0
def main():
	screen.fill((0,0,0))
	ch = int (inputbox.ask(screen,"press 1 for cpu vs human and 2 for vs cpu"))

	if ch==1:
		run_human_vs_cpu()

	if ch==2:
		run_cpu_vs_cpu()
コード例 #35
0
ファイル: asteroids.py プロジェクト: majormoses/asteroids
	def game_logic(self, keys, newkeys, surface):
		self.ship.game_logic(keys, newkeys,self.bullet, self.nuke)
		self.bullet.game_logic(keys, newkeys)
		self.nuke.game_logic(keys, newkeys)
		for rock in self.rocks:
			if rock.active == True:
				rock.game_logic(keys, newkeys)

				if self.bullet.collision(rock) and self.bullet.active:
					self.astroid_explosion_sfx.play()
					self.rock_dead.append(rock)
					rock.active = False
					self.asteroid_count -= 1
					self.score = self.score + 100

				if self.nuke.collision(rock) and self.nuke.active:
					self.astroid_explosion_sfx.play()
					self.rock_dead.append(rock)
					rock.active = False
					self.score = self.score + 100
					self.asteroid_count -= 1

				if self.ship.collision(rock) and self.ship.active == True:
					self.ship_explosion_sfx.play()
					self.rock_dead.append(rock)
					self.score = self.score -100

					if self.ship.shield_health >0:
						self.ship.shield_health -= 25
					rock.active = False
					self.asteroid_count -= 1
					self.ship.count -= 1

					if self.ship.count == 0:
						self.ship.active = False

		for star in self.stars:
			star.game_logic()

		if self.game_over() == config.GAME_WIN:
			pygame.mixer.quit()
			self.level += 1

			if self.level >= 5:
				self.nuke_count = 2
			self.reset(self.ship.position, self.ship.rotation, self.ship.pull)

		if (self.game_over() != config.GAME_PLAYING):
			self.name = inputbox.ask(surface, "Three Letter Initial")
			self.name = self.name[0:3]
			name_score = self.name, self.score
			self.high_score.append(str(name_score))
			print self.high_score
			self.high_score.sort(key=lambda s: eval(s)[1], reverse=True)

			if len(self.high_score) > self.high_count:
				self.high_score.pop()
コード例 #36
0
def getinput(scrn, character, lock):
    puzzle, string = generate(lock) #Generate a puzzle
    answer = inputbox.ask(scrn, string) #Will get a string with answer
    cleared = puzzle.checkAnswer(character, answer)
    print cleared
    if cleared == True: #Determines if true or not
        return True #If true, win and door does what wants
    else:
        getinput(scrn, character, lock) #Else, repeat
コード例 #37
0
ファイル: names.py プロジェクト: creends/Palets-Game
def ask_name_reseau():
    screen = pygame.display.get_surface()
    name = None

    screen.fill(0xffffff)

    name = inputbox.ask(screen, "Nom", 6)

    return name
コード例 #38
0
    def UserPass(self):

        userp = True
        noStartGame = True

        while userp:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:

                    #s.close()
                    pygame.quit()
                    quit()

            self.gameDisplay.blit(self.background, (0, 0))

            ##SERVER LOGIN##

            self.name = inputbox.ask(self.gameDisplay, "UserName")
            password = inputbox.ask(self.gameDisplay, "Password")

            #self.s.sendto("User:?:?".encode(),self.server)
            #self.s.sendto("NumberOfPlayers:?:?".encode(),self.server)

            self.tLock.acquire()
            self.tLock.release()
            time.sleep(0.2)
            #self.shutdown = True
            #rt.join()
            #self.s.close()

            password = hashlib.md5(password.encode()).hexdigest()
            #print("PASSWORD BEFORE SENDING: ",password," TYPE: ",type(password))
            self.s.sendto("Login:{}:{}".format(self.name, password).encode(),
                          self.server)
            while noStartGame == True:
                if self.gametime == True:
                    self.waitingRoom()
                if self.invalidtime == True:
                    self.InvalidPass()

            ##SERVER LOGIN##

            pygame.display.update()
            self.clock.tick(15)
コード例 #39
0
 def target_search(self, event):
     SIZE = min(self.surface.get_size())
     path = 'images/target_search.png'
     icon_position = ((4*self.size[0]/10)-50, 35)
     button = Button(self.surface, icon_position, (SIZE, SIZE), path,str('target_search'))
     button.event_handler(self.position, icon_position, event)
     if button.pressed:
         action = str('target_search')
         self.ex.Primative(action)
         answer = inputbox.ask(self.screen, "Number of Drones")
コード例 #40
0
ファイル: core.py プロジェクト: JohnathonNow/PyConquest
 def talk(self):
     tile = self.grid.getTile(self.cortez_x, self.cortez_y)
     if tile.type == grid.CITY:
         city = self.cityData[tile.city]
         if self.DonaMaria == 1:
             if city["Trust"] == 0:
                 inputbox.message_box(self.screen, city["Initial"])
                 if self.troops["nahua"] > 0:
                     self.troops["nahua"] -= city["IA"]
                     if self.troops["nahua"] < 0:
                         self.troops["spanish"] += self.troops["nahua"]
                         self.troops["nahua"] = 0
                 else:
                     self.troops["spanish"] -= city["IA"]
                 self.week += 15 / 7
                 c = "~"
                 while c[0] not in "yn":
                     c = inputbox.ask(
                         self.screen,
                         'Ally with ' + tile.city + '? (yes or no)')
                     if c[0] in "y":
                         self.troops["nahua"] = self.troops['nahua'] + city[
                             "Troops"]
                         city["Troops"] = 0
                         city["Trust"] = 1
                         self.label_string[
                             7] = tile.city + " agrees to an alliance with you."
                     else:
                         city["Trust"] = -1
                         inputbox.message_box(self.screen, city["Reject"])
                         if self.troops["nahua"] > 0:
                             self.troops["nahua"] -= city["RA"]
                             if self.troops["nahua"] < 0:
                                 self.troops["spanish"] += self.troops[
                                     "nahua"]
                                 self.troops["nahua"] = 0
                         else:
                             self.troops["spanish"] -= city["RA"]
                         if city["RK"]:
                             city["Troops"] = 0
                             city["Population"] = 0
                 #city["Trust"] = 1
             elif city["Trust"] > 0:
                 if "Intel" in city.keys():
                     inputbox.message_box(self.screen, city["Intel"])
             elif city["Trust"] < 0:
                 self.fight()
         else:
             inputbox.message_box(
                 self.screen,
                 "You cannot effectively communicate with cites because you do not know the language. Perhaps a translator would help..."
             )
     else:
         #set the notification
         self.label_string[7] = "Talking to yourself will get you nowhere."
コード例 #41
0
ファイル: inventory.py プロジェクト: 602p/spacegame
    def process_events(self, events):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.finish()
                if self.selected_item:
                    if event.key == pygame.K_x:
                        self.selected_item.dequip()
                        self.first_start()
                    if event.key == pygame.K_d:
                        if self.selected_item.equipped == -1:
                            self.root.state_manager.states[
                                "game"].entities.append(
                                    ship.create_ship(
                                        self.root, "cargo_pod_generic",
                                        self.selected_item.parent.rigidbody.x,
                                        self.selected_item.parent.rigidbody.y,
                                        1, 1))
                            self.root.state_manager.states["game"].entities[
                                -1].pick_up(self.selected_item)
                            del self.selected_item.parent.inventory[
                                self.selected_item.parent.inventory.index(
                                    self.selected_item)]
                            self.first_start()
                        else:
                            ui_states.interdict_ok(
                                self.root,
                                title="Error",
                                text=
                                "Cannot drop equipped item!%nDequip with X first",
                                button="OK")

                    if event.key == pygame.K_u:
                        self.selected_item.fire()
                    if event.key == pygame.K_e:
                        self.root.state_manager.start_interdicting(
                            "hardpoint_select", {
                                "inv_id": self.sm_id,
                                "item": self.selected_item
                            })
                    if event.key == pygame.K_s:
                        self.selected_item.parent.try_stack(self.selected_item)
                        self.first_start()
                    if event.key == pygame.K_a:
                        self.selected_item.parent.try_split(
                            self.selected_item,
                            int(
                                inputbox.ask(self.root.screen.screen,
                                             "Number to take >> ")))
                        self.first_start()

            if event.type == pygame.MOUSEBUTTONDOWN:
                for _, _, rect, item in self.cache_items:
                    if rect.collidepoint(pygame.mouse.get_pos()):
                        self.selected_item = item
コード例 #42
0
ファイル: VNCSCCV143.py プロジェクト: goccikcan/VNCSCCV
	def main2():
	    #o = Options()
	    #try:
	    #	o.parseOptions()
	    #except usage.UsageError, errortext:
	    #    print "%s: %s" % (sys.argv[0], errortext)
	     #   print "%s: Try --help for usage details." % (sys.argv[0])
	      #  raise SystemExit, 1

	    depth = int("32")

	    logFile = sys.stdout
	    #if o.opts['outfile']:
	     #   logFile = o.opts['outfile']
	    log.startLogging(logFile)
	    
	    pygame.init()
	    remoteframebuffer = PyGameApp()
	    
	    #~ from twisted.python import threadable
	    #~ threadable.init()
	    #~ reactor.callInThread(eventcollector)

	    host = (i)
	    passwordvnc=("100")
	    pvnc=("100")
	    p=("100")

	    display = int("0")
	    if host is None:
	        screen = pygame.display.set_mode((220,40))
	        screen.fill((0,100,255)) #blue bg
	        host = inputbox.ask(screen, "Host")
	        if host == '':
	            raise SystemExit
	        if ':' in host:
	            host, display = host.split(':')
	            if host == '':  host = 'localhost'
	            display = int(display)

	    # connect to this host and port, and reconnect if we get disconnected
	    reactor.connectTCP(
	        host,                                   #remote hostname
	        display + 5900,                         #TCP port number
	        VNCFactory(
	                remoteframebuffer,              #the application/display
	                depth,                          #color depth
	                passwordvnc,                 #if a fast connection is used
#	                passwordvnc,
#	                time.sleep(7)
#	                pyautogui.typewrite("100", interval=0.25)
#					pyautogui.press('enter')             #password or none
	                #int(o.opts['shared']),          #shared session flag
	        )
	    )
コード例 #43
0
ファイル: main.py プロジェクト: yadavali1/Asteroid_Evader
def name_selection():
    pygame.time.delay(50)
    display_screen(name_screen,0,0)
    buttons('', 0, 0, 40, 38, blue, white,14, main_menu)
    gameDisplay.blit(back_icon,(10,10))

    buttons('', 760, 0, 40, 38, blue, white,14, settings)
    gameDisplay.blit(settings_icon,(772,10))
    global username
    username = inputbox.ask(gameDisplay, '')
    pygame.display.update()
コード例 #44
0
ファイル: main.py プロジェクト: simon1573/Roadrunner
def game_over():
    global is_game_over
    global name
    global highscore_background
    global leaderboard
    is_game_over = True
    screen.blit(highscore_background, (0, 0))
    name = inputbox.ask(screen, "Name")
    leaderboard = Leaderboard(name, SCORE)
    leaderboard.load_previous_scores()
    leaderboard.save_score()
コード例 #45
0
ファイル: main.py プロジェクト: maryams64/Roadrunner
def game_over():
    global is_game_over
    global name
    global highscore_background
    global leaderboard
    is_game_over = True
    screen.blit(highscore_background, (0, 0))
    name = inputbox.ask(screen, "Name")
    leaderboard = Leaderboard(name, SCORE)
    leaderboard.load_previous_scores()
    leaderboard.save_score()
コード例 #46
0
def run_human_vs_cpu():
	SIZE = 400

	depth = 1

	player = int (inputbox.ask(screen, "0 for cross, 1 for circle"))
	n = int (inputbox.ask(screen, "Enter N"))
	first_play = int (inputbox.ask(screen, "play 0 or 1 first ?"))

	board = init_board(n)

	draw_board(board,SIZE,n)

	if first_play == opp[player]:
		cpu_turn(board,opp[player],n,depth,SIZE)

	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()

			if event.type == pygame.MOUSEBUTTONDOWN:
				x,y = pygame.mouse.get_pos()
				p = get_square(x,y,SIZE/n)
				if board[p[0]][p[1]] == -1:
					board[p[0]][p[1]] = player
			
					draw_board(board,SIZE,n)

					if board_full(board, n):
						display_message("Draw!")
					        main()
					if win(board,opp[player],n):
						display_message("You Lose")
						main()
					if win(board,player,n):
						display_message("You Win")
						main()

					cpu_turn(board,opp[player],n,depth,SIZE)
コード例 #47
0
ファイル: label_objects.py プロジェクト: hexhex/mlplugin
def mainLoop(scr, px, label_list):
    names = []
    polygons = []
    pointlist = []

    polygons.append([pointlist,get_color(),0])

    mouse_position = [pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]]
    n=0
    end=False
    while n!=1:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                pointlist.append(event.pos)
            if event.type == pygame.MOUSEBUTTONUP and event.button == 3:
                displayImage(scr, px, polygons, names, False)
                name = inputbox.ask(scr, 'Label')
                while name not in label_list:
                    name = inputbox.ask(scr, 'Label')
                names.append(name)
                displayImage(scr, px, polygons, names, True)
                pointlist = []
                polygons.append([pointlist,get_color(),0])
            if event.type == pygame.KEYDOWN:
                if event.key == 8:
                    if len(polygons) > 1:
                        polygons.pop()
                        polygons.pop()
                        names.pop()        
                        pointlist = []
                        polygons.append([pointlist,get_color(),0])
                        displayImage(scr, px, polygons, names, True)
                if event.key == 27:
                    n = 1
                    end = True
                if event.key == 110:
                    n = 1
        if [pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]] != mouse_position:
            displayImage(scr, px, polygons, names, True)
            mouse_position = [pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]]
    return (polygons, names, end)
コード例 #48
0
ファイル: core.py プロジェクト: JohnathonNow/PyConquest
 def handleClick(self, xxt, yyt):
     self.grid.clearSelection()
     if self.grid.select(xxt, yyt):
         self.xt = xxt
         self.yt = yyt
         print((xxt, yyt))
         #inputbox.coordinates(screen, xxt, yyt)
         if self.mode == 'move' and self.grid.selected[0].known:
             self.moveCortez(self.xt, self.yt)
         elif self.mode == 'dispatch':
             c = inputbox.ask(self.screen, 'How many men?')
             self.sendMen(self.xt, self.yt, c)
コード例 #49
0
 def formation(self, event):
     SIZE = min(self.surface.get_size())
     path = 'images/formation.png'
     icon_position = ((3*self.size[0]/10) - 50, 35)
     button = Button(self.surface, icon_position, (SIZE, SIZE), path,str('formation'))
     button.event_handler(self.position, icon_position, event)
     if button.pressed:
         answer = inputbox.ask(self.screen, "Number of Drones")
         action = str('formation')
         self.ex.Primative(action)
         #print(pygame.mouse.get_pos())
         button.indication(self.surface, self.position, icon_position)
コード例 #50
0
def main():

    screen2 = pg.display.set_mode((280, 250))
    screen2.fill((255, 255, 255))
    pg.display.set_caption(CAPTION)

    num_guests = int(
        inputbox.ask(screen2, 20, 10, 220, 30, "Quantidade de hospedes"))
    num_channel = int(
        inputbox.ask(screen2, 20, 50, 220, 30, "Quantidade de canais"))
    min_watch_time = int(
        inputbox.ask(screen2, 20, 90, 220, 30, "Tempo minimo assistindo"))
    max_watch_time = int(
        inputbox.ask(screen2, 20, 130, 220, 30, "Tempo maximo assistindo"))
    min_rest_time = int(
        inputbox.ask(screen2, 20, 170, 220, 30, "Tempo minimo descansando"))
    max_rest_time = int(
        inputbox.ask(screen2, 20, 210, 220, 30, "Tempo maximo descansando"))

    pg.display.quit()

    global screen
    screen = pg.display.set_mode(SCREEN_SIZE)
    screen.fill(BACKGROUND_COLOR)
    pg.display.set_caption(CAPTION)

    y = 20
    for i in range(num_guests):
        t = Guest(randint(1, num_channel),
                  randint(min_watch_time, max_watch_time),
                  randint(min_rest_time, max_rest_time), i, 0)
        t.pos_y = y
        t.start()
        y = y + 71
コード例 #51
0
def main():

    screen2 = pg.display.set_mode((280, 250))
    screen2.fill((255, 255, 255))
    pg.display.set_caption(CAPTION)

    num_guests = int(inputbox.ask(screen2, 20, 10, 220, 30, "Quantidade de hospedes"))
    num_channel = int(inputbox.ask(screen2, 20, 50, 220, 30, "Quantidade de canais"))
    min_watch_time = int(inputbox.ask(screen2, 20, 90, 220, 30, "Tempo minimo assistindo"))
    max_watch_time = int(inputbox.ask(screen2, 20, 130, 220, 30, "Tempo maximo assistindo"))
    min_rest_time = int(inputbox.ask(screen2, 20, 170, 220, 30, "Tempo minimo descansando"))
    max_rest_time = int(inputbox.ask(screen2, 20, 210, 220, 30, "Tempo maximo descansando"))

    pg.display.quit()

    global screen
    screen = pg.display.set_mode(SCREEN_SIZE)
    screen.fill(BACKGROUND_COLOR)
    pg.display.set_caption(CAPTION)

    y = 20
    for i in range(num_guests):
        t = Guest(randint(1, num_channel), randint(min_watch_time, max_watch_time), randint(min_rest_time, max_rest_time), i, 0)
        t.pos_y = y
        t.start()
        y = y + 71
コード例 #52
0
ファイル: game2.py プロジェクト: BlazingFire/SimPhy
def startGame2(DISPLAYSURF):
	btn = Button('Start')

	clock = pygame.time.Clock()
	background=pygame.image.load('Images/1.png')
	run = True
	while run:
		DISPLAYSURF.blit(background,(0,0))
		mouse = pygame.mouse.get_pos()
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
			elif event.type == pygame.MOUSEBUTTONDOWN:
				if btn.obj.collidepoint(mouse):
					countInputs=1;
											
					m1 = inputbox.ask(DISPLAYSURF, "Mass, M",countInputs)
					m2 = float (m1)
					countInputs=countInputs+5;
					u1 = inputbox.ask(DISPLAYSURF, "Coefficient of Friction, u",countInputs)
					u2 = float (u1)
					countInputs=countInputs+5;
					f1 = inputbox.ask(DISPLAYSURF, "Force, F",countInputs)
					f2 = float (f1)
					v1 = u2 * f2
					W = m2 * 9.8
						
					if ( W > v1):
						font = pygame.font.Font(None, 36)
						text = font.render("The block will fall down.", 1, (10, 10, 10))
						animation2(DISPLAYSURF,'down',text)
					else:
						res=pygame.image.load('Images/5.png')
   						DISPLAYSURF.blit(res,(0,0))
						errorScreen(DISPLAYSURF,"The block wont show any motion!")
					
		btn.draw(DISPLAYSURF, mouse, (200,300,100,20), (225,303))

		pygame.display.update()
		clock.tick(60)
コード例 #53
0
def main():
    o = Options()
    try:
        o.parseOptions()
    except (usage.UsageError, errortext):
        print ("%s: %s" % (sys.argv[0], errortext))
        print ("%s: Try --help for usage details." % (sys.argv[0]))
        raise (SystemExit, 1)

    depth = int(o.opts['depth'])

    logFile = sys.stdout
    if o.opts['outfile']:
        logFile = o.opts['outfile']
    log.startLogging(logFile)
    
    pygame.init()
    remoteframebuffer = PyGameApp()
    
    #~ from twisted.python import threadable
    #~ threadable.init()
    #~ reactor.callInThread(eventcollector)

    host = o.opts['host']
    display = int(o.opts['display'])
    if host is None:
        screen = pygame.display.set_mode((220,40))
        screen.fill((0,100,255)) #blue bg
        host = inputbox.ask(screen, "Host")
        if host == '':
            raise SystemExit
        if ':' in host:
            host, display = host.split(':')
            if host == '':  host = 'localhost'
            display = int(display)

    # connect to this host and port, and reconnect if we get disconnected
    reactor.connectTCP(
        host,                                   #remote hostname
        display + 5900,                         #TCP port number
        VNCFactory(
                remoteframebuffer,              #the application/display
                depth,                          #color depth
                o.opts['fast'],                 #if a fast connection is used
                o.opts['password'],             #password or none
                int(o.opts['shared']),          #shared session flag
        )
    )

    # run the application
    reactor.callLater(0.1, remoteframebuffer.mainloop)
    reactor.run()
コード例 #54
0
ファイル: smsproject.py プロジェクト: maggiezheng108/sms
def main():
    leaving = False
    play = 0
    correct = 0
    titlescreen()
    inkey = inputbox.get_key()
    if inkey != K_RETURN:
        return
    directions()
    inkey = inputbox.get_key()
    if inkey != K_RETURN:
        return 
    screen.fill(black)
    pygame.display.flip()
    while play < 21:
        clock = pygame.time.Clock()
        clock.tick()
        word = Word()
        gameplay(word)
        answer = inputbox.ask(screen, "")

        clock.tick()
        time = (2000 - clock.get_time())
        
        if clock.get_time() >= 2000 or answer.upper() != words[word.getKey()]:
                screen.fill(grey)
                pygame.display.flip()
                play += 1
                continue
        time = str(2000 - clock.get_time())
        text = font.render(time, 1, white)
        screen.blit(text, (50, 50))
        screen.fill(black)
        pygame.display.flip()
        play += 1
        if answer.upper() == words[word.getKey()]:
                correct += 1
    else:
        print(correct)
        correct = str(correct)
        text = font.render('Score: '+ correct, 1, white)
        screen.blit(text, (300 - (text.get_width() / 2), 300 - (text.get_height() / 2)))
        text2 = font2.render("Press Enter to play again", 1, white)
        screen.blit(text2, (300 - (text2.get_width() / 2), 300 - (text2.get_height() / 2) + 100))
        text3 = font2.render("Press Space to exit", 1, white)
        screen.blit(text3, (300 - (text3.get_width() / 2), 300 - (text3.get_height() / 2) + 150))
        pygame.display.flip()
        inkey = inputbox.get_key();
        if inkey == K_RETURN:
            main()
        elif inkey == K_SPACE:
            pass
コード例 #55
0
ファイル: plansym.py プロジェクト: pawelzell/plansym
    def wczytaj(self):
        obiekty = []
        self.dane.screen.fill((0, 0, 0))
        self.rysowanie.rysuj_naglowek("PlanSym Load data ")
        self.rysowanie.rysuj_panel_dolny("Set number of planets:")
        n_text = inputbox.ask(self.dane.screen, (20, self.dane.screen.get_height() - 120, 220, 60), "n = ", self.dane)
        n = int(n_text)

        for i in xrange(1, n + 1):
            obiekty.append(self.wczytaj_planete(i, n, exit))
            self.dane.obiekty = obiekty
            if self.dane.exit:
                break
コード例 #56
0
    def __init__(self, screen):
	
	self.screen = screen
	self.clients = []
	self.userName = inputbox.ask(screen, "Type your name ")
	
	self.buttonColor = (200,20,20)
	self.buttonSize = (200,50)
	self.buttonPos = (50,50)
	self.myButton = Button(self.buttonPos, self.buttonSize,
				self.buttonColor, self.userName)
	
	self.brokenError = False
コード例 #57
0
ファイル: Setup.py プロジェクト: fryingpan/Assignment2
    def event(self, event):
        #        ##joysticks
        #            ##self.joy = Joystick()
        #        while not self.joy.quit_attempt:
        #            self.interaction_phase(Globals.SCREEN, self.character, self.joy)

        #Allows quitting pygame and changing states
        #added changes for multiple states to allow testing
        for ev in event:
            if ev.type in Joystick.JOYSTICK:  # only care about objective switching
                if ev.type == PG.JOYBUTTONUP:
                    self.joy.buttons[ev.button] = False
                elif ev.type == PG.JOYBUTTONDOWN:
                    self.joy.buttons[ev.button] = True

            if ev.type == PG.KEYDOWN and ev.key == PG.K_ESCAPE:
                #Globals.STATE = 'Menu'
                PM.music.fadeout(1000)
                if Globals.SCORE > 0:
                    Globals.PLAYERNAME = str(inbx.ask(Globals.SCREEN, 'Name'))
                    # Globals.SCORE = self.character.score
                Globals.STATE = 'Menu'
                #Globals.RUNNING = False
            elif ev.type == PG.KEYDOWN and ev.key == PG.K_1:
                level = 1
                self.stage = 1
                self.change_level(level, self.stage)
            elif ev.type == PG.KEYDOWN and ev.key == PG.K_2:
                level = 2
                self.stage = 1
                self.change_level(level, self.stage)
            elif ev.type == PG.KEYDOWN and ev.key == PG.K_3:
                level = 3
                self.stage = 1
                self.change_level(level, self.stage)
            elif ev.type == PG.KEYDOWN and ev.key == PG.K_4:
                level = 4
                self.stage = 1
                self.change_level(level, self.stage)
            elif ev.type == PG.KEYDOWN and ev.key == PG.K_5:
                Cutscene(Globals.SCREEN, 5)
                Globals.STATE = "Menu"
            elif (ev.type == PG.KEYDOWN and ev.key == PG.K_p):
                Globals.SCORE = self.num_enemies
            elif (ev.type == PG.KEYDOWN and ev.key == PG.K_n):
                # see if banner still needs to be shown (self.updated_obj gets True)
                self.updated_obj = self.objective.nextBannerTxt(
                )  #returns if true if there is more text, false if not
                self.objectiveBlit = False
            else:
                self.objectiveBlit = True
コード例 #58
0
def NameScreen():
    pygame.time.delay(50)
    name_select = True
    while name_select:
        screen = DisplayScreen(name_screen)
        screen.show()
        global username
        back = DisplayText('', blue, 14)
        back.buttons(0, 0, 40, 38, blue, white, 14, MenuScreen)
        gameDisplay.blit(back_icon, (10, 10))
        username = inputbox.ask(gameDisplay, '')
        name_select = False
        pygame.display.update()
        fps.tick(60)