コード例 #1
0
ファイル: play_core.py プロジェクト: ninn55/tic_tac_toe
def play_1():
    init_board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    for i in range(9):
        if i == 0:
            os.system('clear')
            board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            print("Let's play Tic_Tac_Toe")
            print("press number to play")
            draw(init_board)
            draw(board)
        temp = user_input(board) - 1
        os.system('clear')
        print("Let's play Tic_Tac_Toe")
        print("press number to play")
        draw(init_board)
        if i % 2 == 0:
            board = update_board(board, temp, 'X')
            draw(board)
            if check_board(board):
                break
        else:
            board = update_board(board, temp, 'O')
            draw(board)
            if check_board(board):
                break
    return 0
コード例 #2
0
def game(wins=0, lost=0):
    input1 = word_generator()
    output = {}
    output[0] = len(input1) * "*"
    fail = 0
    win = wins
    lose = lost
    special = ",!@$%^&*(){}: #.'"
    for sign in special:
        output = check_letter(input1, sign, output[0])
    print('\n' * 50)
    print(f"""
    Welcome to Hangman!
    Try to guess this!
    {output[0]}""")
    while input1 != output[0] and fail != 12:
        letter = str(input("Put your letter here (or final word): "))
        print('\n' * 50)
        if letter == input1:
            break
        elif len(letter) == 1:
            output = check_letter(input1, letter, output[0])
            if output[1] == False:
                fail += 1
        else:
            fail += 1
            print("You do something wrong!")
        print(output[0])
        draw(fail)
    if fail == 12:
        lose += 1
        print(f'The word is :{input1}')
    else:
        print("CONGRATULATIONS YOU WIN!")
        print(f'The word is :{input1}')
        win += 1
    print(f"YOUR WINS: {win}.")
    print(f"YOUR LOSSES: {lose}.")
    check = True
    while check == True:
        rpl = input("You want to play Again? Y/N: ")
        if rpl.upper() == "Y":
            game(win, lose)
            check = False
        elif rpl.upper() == "N":
            print("Thank you! Good bye!")
            check = False
        else:
            print("You do something wrong!")
コード例 #3
0
def main(num_rows, num_aisles, refresh_rate, num_iterations, move_speed,
         boarding_procedure,
         num_zones):  #, boarding_procedures, num_zones = None):

    pygame.init()
    windowSurface = pygame.display.set_mode((1200, 770), 0, 32)
    pygame.display.set_caption('Airport')
    drawing = draw(windowSurface, num_rows, num_aisles)
    seats = drawing.seats()

    passengersz = passengers(windowSurface, move_speed, boarding_procedure,
                             num_zones, seats['seat_locations'],
                             seats['left_aisle'], seats['right_aisle'],
                             seats['row1Y'], seats['seat_width'],
                             seats['left_plane'], seats['brdg_wide'],
                             seats['brdg_to_plane'])

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

        windowSurface.fill((255, 255, 255))

        drawing.plane()
        drawing.seats()
        drawing.jet_bridge()

        passengersz.board(num_iterations)

        pygame.display.update()

        time.sleep(refresh_rate)
コード例 #4
0
ファイル: typing.py プロジェクト: NoahBlack012/speedtyping
 def __init__(self):
     pygame.init()
     pygame.font.init()
     self.settings = settings()
     self.player = player()
     self.draw = draw()
     self.keys = keys()
     self.screen = pygame.display.set_mode(
         (self.settings.WIDTH, self.settings.HEIGHT))
     pygame.display.set_caption(self.settings.CAPTION)
     self.clock = pygame.time.Clock()
     self.time_font = pygame.font.Font('freesansbold.ttf', 60)
     self.text_font = pygame.font.Font('freesansbold.ttf', 20)
     self.end_font = pygame.font.Font('freesansbold.ttf', 30)
     self.start_font = pygame.font.Font('freesansbold.ttf', 100)
     with open("texts/text.txt") as f:
         contents = f.readlines()
     for n, line in enumerate(contents):
         if line.startswith("line"):
             contents[n] = "\n" + line.rstrip()
         else:
             contents[n] = line.rstrip()
     self.contents = ' '.join(contents)
     self.text_width, self.text_height = self.time_font.size(self.contents)
     self.lines = int(math.ceil(self.text_width / self.settings.WIDTH / 2))
     self.groups = int(len(self.contents) / self.lines)
     self.line_contents = textwrap.wrap(self.contents, self.groups)
     for n, line in enumerate(self.line_contents):
         if n < len(self.line_contents):
             self.line_contents[n] = self.line_contents[n] + " "
コード例 #5
0
class GameLoop:
    runFlag = False
    
    #Start the game loop
    def run(self, delta):
        runFlag = True
        
        startUp()
        
        #convert time to seconds
        nextTime = time.time() + 60
        maxTimeDiff = 0.5
        skippedFrames = 1
        maxSkippedFrames = 5
        
        while(runFlag):
            currTime = time.time() / 1000000000.0
            if((currTime - nextTime) > maxTimeDiff):
                nextTime = currTime
            if(currTime >= nextTime):
                #new time for update
                nextTime += delta
                update()
                
                if((currTime < nextTime) | (skippedFrames > maxSkippedFrames)):
                    draw()
                    skippedFrames = 1
                else:
                    skippedFrames + 1
            else:
                #determine sleep time
                sleepTime = 1000.0 * (nextTime - currTime)
                if(sleepTime > 0):
                    #sleep until next update
                    try:
                        time.sleep(sleepTime)
                    except InterruptedError:
                        #do nothing
    
        #inside of run
        shutdown()
        
        
    def stop(self):
        runFlag = False
        
    startUp()
    shutdown()
    update()
    draw()
                        
                    
    
    
コード例 #6
0
while run:
    x = pick()
    chance = 7
    y = len(x)
    m = []
    usedChar = ""

    while y > 0:
        m.append("_")
        y = y - 1

    reset = True

    while reset:
        os.system('cls')
        draw(chance)
        print("\n\n")

        if chance == 0:
            print('You have lost')
            print('The answer is:\n', x)
            again = input("do you want to play again? y/n: ")
            reset = False
            if again == 'n':
                run = False

        elif '_' in m:

            print("\nYou have", chance, "chances\n")
            print("  ".join(m), "\n\n\n")
            print("Used Letters:", usedChar)
コード例 #7
0
ファイル: parse_logs.py プロジェクト: nikhilag13/AdaptiveCAP
def parse():
  tree = Tree()
  project_home = dirname(sys.path[0])
  # while project_home.split('/')[-1] != 'AdaptiveCAP':
  #   project_home = dirname(project_home)
  # print ('project_home', project_home)

  log_path = os.path.join(project_home, _LOG_FILE)
  print ('log_path', log_path)

  with open(log_path, 'r') as fp:
    lines = fp.readlines()
    print "heyhehheehheheyeyeyeyeyeyyeyeyyyyyyyyy"
  print "file is accessed"
  interested = False
  hello_sent_from = -1  # new parent
  hello_sent_to = -1  # node which will move

  for line in lines:
    # TODO: start at timestamp/ automatically run afterclustering

    if not line:
      continue

    last_part = line.split('-')[-1].strip()
    if last_part == 'Starting Server':
      node_id = line.split('-')[-2].split(':')[-1].strip()

      if node_id in SPANNING_INFO:
        parent = SPANNING_INFO[node_id]['parentId']
      else:
        parent = None
      if parent:
        parent = int(parent)
      node_id = int(node_id)
      tree.add_node(node=node_id, parent=parent)

      sleep(_DELAY)
      draw(tree.data)

      if _PARSE_LOGS_DEBUG:
        print 'Starting Server'
        print ('node_id', node_id)
        print ('parent', parent)
        pp.pprint(tree.data)
        print "\n"

    elif last_part == 'Got Prune':
      node_id = line.split('-')[-2].split(':')[-1].strip()
      tree.prune(node_id)
      sleep(_DELAY)
      draw(tree.data)
      if _PARSE_LOGS_DEBUG:
        print 'Got Prune'
        pp.pprint(tree.data)
        print "\n"

    elif last_part == 'Got Response: interested: 1':
      interested = True
      hello_sent_from = line.split('-')[-2].split(':')[-1].strip()

    elif interested:
      interested = False
      hello_sent_to = line.split(':')[-1].strip()
      new_parent = int(hello_sent_from)
      to_move = int(hello_sent_to)
      tree.prune(node=to_move, new_parent=new_parent)
      sleep(_DELAY)
      draw(tree.data)
      if _PARSE_LOGS_DEBUG:
        print 'Got Response: interested: 1'
        print "moving Node {to_move} to Node {new_parent}".format(
          to_move=to_move, new_parent=new_parent)
        pp.pprint(tree.data)
        print '\n'
コード例 #8
0
ファイル: 05.py プロジェクト: michigann/grafy_zestaw_5
	print(i)
	
	
counter = 0
#print(g.vertices)
for i in g.matrix:
	print(i)
	for j in i:
		if j>0:
			counter+=1
print(counter)

maxFlow = MaxFlow(g)
print(maxFlow.max_flow())

for i in maxFlow.flowMatrix:
	print(i)

bipartite = Bipartite() 
bipartiteMaxFlow = MaxFlow(bipartite)
print(bipartiteMaxFlow.max_flow())
bipartite.show()
print('''
''')
bipartiteMaxFlow.show()


raw_input('Enter to draw a graph...')
draw(g, maxFlow)
#draw(bipartite, bipartiteMaxFlow)
コード例 #9
0
def mainloop():
        f = open('logs.txt', 'w')
        f.write("Logs" + '\n')
        f.close()
        clock = pygame.time.Clock()
        #[world, scene, boat, brain, score]
        population = []
        for i in range(n_persons):
                population.append(generate())
        educatable = generate(mode = "educatable")
        user = generate(mode = "user")
        step_counter = 0
        fps = 0
        training_data = []
        for _ in range(60000):
                step_counter += 1
                wins = 0
                for i in range(n_persons):
                        for t in range(inf):
                                if not draw_all:
                                        fps = inf - 1
                                if fps <= 30:
                                        draw(population[i]["scene"])
                                else:
                                        fps = inf - 1
                                status, moves = run(population[i]["boat"], population[i]["world"], clock, population[i]["brain"], fps)
                                for event in pygame.event.get():
                                        if event.type == pygame.QUIT:
                                                pygame.quit()
                                                quit()
                                        if event.type == pygame.KEYUP:
                                                if event.key == 276:
                                                        status = "skip"
                                        if event.type == pygame.MOUSEBUTTONDOWN:
                                                if event.button == 4:
                                                        fps += 10
                                                elif event.button == 5:
                                                        fps-=10
                                                        fps = min(max(0, fps), 30)
                                clock.tick(1 + fps)
                                if(t == game_time or status):
                                        population[i]["score"] = 1/(population[i]['boat'].get_aim() + 1/inf)
                                        if status == "break" or status == "skip":
                                                population[i]["score"] *= 0.1
                                        if status == "win":
                                                for i in moves:
                                                        training_data.append(i)
                                                wins += 1
                                        break
                if user_play:
                        for t in range(inf):
                                if draw_user:
                                        draw(user["scene"])
                                cls()
                                print("Step {}: (MAX_FPS = {}), win rate = {}".format(step_counter, fps + 1, wins))# / n_persons))
                                print("Your Turn.")
                                status, moves = run(user['boat'], user['world'], clock, None, fps, mode = "human")
                                for event in pygame.event.get():
                                        if event.type == pygame.QUIT:
                                                pygame.quit()
                                                quit()
                                if(t == game_time or status):
                                                user["score"] = 1/(user['boat'].get_aim() + 1/inf)
                                                if status == "break" or status == "skip":
                                                        user["score"] *= 0.1
                                                        print("You Break!")
                                                if status == "win":
                                                        for i in moves:
                                                                training_data.append(i)
                                                        print("You Win!")
                                                print("Finish")
                                                break
                if education_play:
                        for t in range(inf):
                                if not draw:
                                        fps = inf - 1
                                if fps <= 30:
                                        draw(educatable["scene"])
                                else:
                                        fps = inf - 1
                                status, moves = run(educatable["boat"], educatable["world"], clock, educatable["brain"], fps, mode = 'educatable')
                                for event in pygame.event.get():
                                        if event.type == pygame.QUIT:
                                                pygame.quit()
                                                quit()
                                        if event.type == pygame.KEYUP:
                                                if event.key == 276:
                                                        status = "skip"
                                        if event.type == pygame.MOUSEBUTTONDOWN:
                                                if event.button == 4:
                                                        fps += 10
                                                elif event.button == 5:
                                                        fps-=10
                                                        fps = min(max(0, fps), 30)
                                clock.tick(1 + fps)
                                if(t == game_time or status):
                                        educatable["score"] = 1/(educatable['boat'].get_aim() + 1/inf)
                                        if status == "break" or status == "skip":
                                                educatable["score"] *= 0.1
                                        if status == "win":
                                                for i in moves:
                                                        training_data.append(i)
                                                wins += 1
                                        break
                        if len(training_data):
                                X = np.array([i[0] for i in training_data]).reshape(-1,len(training_data[0][0]),1)
                                y = [i[1] for i in training_data]
                                np.random.shuffle(training_data)
                                educatable['brain'][0].fit({'input': X}, {'targets': y}, n_epoch=500, show_metric=True, run_id='boat', snapshot_epoch=False, snapshot_step = inf)
                                cls()
                print("Step {}: (MAX_FPS = {}), win rate = {}".format(step_counter, fps + 1, wins))# / n_persons))
                f = open('logs.txt', 'a')
                f.write("Step {}: (MAX_FPS = {}), win rate = {}".format(step_counter, fps + 1, wins))# / n_persons) + '\n')
                f.close()
                populate(population)
                for i in range(n_persons):
                        population[i] = {**generate(person = True), **dict.fromkeys(["brain"], population[i]["brain"])}
                user = generate(mode = "user")
                educatable = {**generate(mode = "user"), **dict.fromkeys(["brain"], educatable["brain"])}