Пример #1
0
def main():

    print_instruction()

    board = []
    for i in range(9):
        board.append(-1)

    win = False
    move = 0
    while not win:

        print_board(board)
        print "Turn number" + str(move + 1)
        if move % 2 == 0:
            turn = 'X'
        else:
            turn = 'O'

        user = get_input(turn)
        while board[user] != -1:
            print "Invalid move! Cell already taken. Please try again.\n"
            user = get_input(turn)
        board[user] = 1 if turn == 'X' else 0

        move += 1
        if move > 4:
            winner = check_win(board)
            if winner != -1:
                out = "The winner is"
                out += "X" if winner == 1 else "O"
                out += "=D"
                quit_game(board, out)
            elif move >= 9:
                quit_game(board, "No winner :(")
Пример #2
0
def main():
	
	print_instruction()
	
	board = []
	for i in range(9):
		board.append(-1)
		
	win = False
	move = 0
	while not win:

		print_board(board)
		print "Turn number" + str(move+1)
		if move % 2 == 0:
			turn = 'X'
		else:
			turn = 'O'

		user = get_input(turn)
		while board[user] != -1:
			print "Invalid move! Cell already taken. Please try again.\n"
			user = get_input(turn)
		board[user] = 1 if turn == 'X' else 0

		move += 1
		if move > 4:
			winner = check_win(board)
			if winner != -1:
				out = "The winner is"
				out += "X" if winner == 1 else "O"
				out += "=D"
				quit_game(board,out)
			elif move >= 9:
				quit_game(board, "No winner :(")
Пример #3
0
def set_grep_word(stdscr):
    word = get_input(stdscr, "Grep for: ")
    tab.get_current_tab().grep = word
    tab.get_current_tab().name = word
    # Clear screen is required since the word size (in the tab) could have changed
    globvar.clear_screen = True
    globvar.redraw = True
Пример #4
0
def train():
    with tf.Graph().as_default():
        global_step = tf.Variable(0, trainable=False)
        image, label = input.get_input(LABEL_PATH, LABEL_FORMAT, IMAGE_PATH, IMAGE_FORMAT)
        logits = model.inference(image)
        loss = model.loss(logits, label)
        train_op = model.train(loss, global_step)
        saver = tf.train.Saver(tf.all_variables())
        summary_op = tf.merge_all_summaries()
        init = tf.initialize_all_variables()
        sess = tf.Session(config=tf.ConfigProto(log_device_placement=input.FLAGS.log_device_placement))
        sess.run(init)
        # Start the queue runners.
        tf.train.start_queue_runners(sess=sess)
        summary_writer = tf.train.SummaryWriter(input.FLAGS.train_dir, graph_def=sess.graph_def)
        for step in xrange(input.FLAGS.max_steps):
            start_time = time.time()
            _, loss_value = sess.run([train_op, loss])
            duration = time.time() - start_time
            assert not np.isnan(loss_value), "Model diverged with loss = NaN"
            if step % 1 == 0:
                num_examples_per_step = input.FLAGS.batch_size
                examples_per_sec = num_examples_per_step / duration
                sec_per_batch = float(duration)
                format_str = "%s: step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch)"
                print(format_str % (datetime.now(), step, loss_value, examples_per_sec, sec_per_batch))
            if step % 10 == 0:
                summary_str = sess.run(summary_op)
                summary_writer.add_summary(summary_str, step)
            # Save the model checkpoint periodically.
            if step % 25 == 0:
                checkpoint_path = os.path.join(input.FLAGS.train_dir, "model.ckpt")
                saver.save(sess, checkpoint_path, global_step=step)
Пример #5
0
def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!\n')

    # TO DO: get user input for city (chicago, new york city, washington)
    while True:
        city = inp.get_input('Please input the city name:- (chicago), or (new york city), or (washington):__ ',
                         ['chicago', 'new york city', 'washington'])
        if city in ['chicago', 'new york city', 'washington']:
            break

    # TO DO: get user input for month (all, january, february, ... , june)
    while True:
        month = inp.get_input('\nWhich month? january, february, march, april, may, june, all?__ ',
                          ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september',
                           'october', 'november', 'december', 'all'])
        try:
            month.index(month)
        except:
            continue
        else:
            break

    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    while True:
        day = inp.get_input('\nWhich day? monday, tuesday, wednesday, thursday, friday, saturday, sunday, all?__ ',
                        ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all'])
        try:
            day.index(day)
        except:
            continue
        else:
            break
    print('-' * 40)
    return city, month, day
Пример #6
0
def main():
	
	print_instruction()
	
	board = []
	for i in range(9):
		board.append(-1)
		
	win = False
	move = 0
	while not win:

		print_board(board)
		print "Turn number" + str(move+1)
        	if move % 2 == 0:
            		#this is the user
            		turn = 'X'
            		user = get_input(turn)
            		while board[user] != -1:
                		print "Invalid move! Cell already taken. Please try again.\n"
                		user = get_input(turn)
            		board[user] = 1
        	else:
            		#this will be the computer
            		turn = 'O'
            		comp=generate_o(board)#computer behaviour define
            		board[comp]=0
		move += 1
		if move > 4:
			winner = check_win(board)
			if winner != -1:
				out = "The winner is"
				out += "X" if winner == 1 else "O"
				out += "=D"
				quit_game(board,out)
			elif move >= 9:
				quit_game(board, "No winner :(")
Пример #7
0
def do_fizzbuzz():
    try:
        user_input = get_input()
        end = user_input
        curr = 1
        while curr < end:
            if curr % 3 == 0:
                print("fizz")
            elif curr % 5 == 0:
                print("buzz")
            elif curr % 15 == 0:
                print("fizzbuzz")
            else:
                print(curr)
            curr += 1
    except ValueError:
        return
Пример #8
0
def test():
	with tf.Graph().as_default():
		image, label = input.get_input(LABEL_PATH, LABEL_FORMAT, IMAGE_PATH, IMAGE_FORMAT)
		logits = model.inference(image)
		top_k_op = tf.nn.in_top_k(logits, label, 1)
		
		variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY)
		variables_to_restore = variable_averages.variables_to_restore()
		saver = tf.train.Saver(variables_to_restore)

		# Get summaries for TENSOR BOARD
		summary_op = tf.merge_all_summaries()
		graph_def = tf.get_default_graph().as_graph_def()
		summary_writer = tf.train.SummaryWriter(input.FLAGS.eval_dir, graph_def=graph_def)

		while True:
			evaluate_model(saver, summary_writer, top_k_op, summary_op)
			if input.FLAGS.run_once:
				break
			time.sleep(input.FLAGS.eval_interval_secs)
Пример #9
0
def train():
    with tf.Graph().as_default():
        global_step = tf.Variable(0, trainable=False)
        image, label = input.get_input(LABEL_PATH, LABEL_FORMAT, IMAGE_PATH,
                                       IMAGE_FORMAT)
        logits = model.inference(image)
        loss = model.loss(logits, label)
        train_op = model.train(loss, global_step)
        saver = tf.train.Saver(tf.all_variables())
        summary_op = tf.merge_all_summaries()
        init = tf.initialize_all_variables()
        sess = tf.Session(config=tf.ConfigProto(
            log_device_placement=input.FLAGS.log_device_placement))
        sess.run(init)
        # Start the queue runners.
        tf.train.start_queue_runners(sess=sess)
        summary_writer = tf.train.SummaryWriter(input.FLAGS.train_dir,
                                                graph_def=sess.graph_def)
        for step in xrange(input.FLAGS.max_steps):
            start_time = time.time()
            _, loss_value = sess.run([train_op, loss])
            duration = time.time() - start_time
            assert not np.isnan(loss_value), 'Model diverged with loss = NaN'
            if step % 1 == 0:
                num_examples_per_step = input.FLAGS.batch_size
                examples_per_sec = num_examples_per_step / duration
                sec_per_batch = float(duration)
                format_str = (
                    '%s: step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch)'
                )
                print(format_str % (datetime.now(), step, loss_value,
                                    examples_per_sec, sec_per_batch))
            if step % 10 == 0:
                summary_str = sess.run(summary_op)
                summary_writer.add_summary(summary_str, step)
            # Save the model checkpoint periodically.
            if step % 25 == 0:
                checkpoint_path = os.path.join(input.FLAGS.train_dir,
                                               'model.ckpt')
                saver.save(sess, checkpoint_path, global_step=step)
Пример #10
0
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
               '|    |    |    |    |    |    |    |    |    |    |',
               '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +']

SHIP_LIST = [('Destroyer', 2, 'd2'),
             ('Cruiser', 3, 'c3'),
             ('Submarine', 3, 's3'),
             ('Battleship', 4, 'b4'),
             ('Aircraft Carrier', 5, 'a5')]


if __name__ == '__main__':
    board = BLANK_BOARD
    taken = set()

    for ship_tuple in SHIP_LIST:
        board, taken = get_input(board, ship_tuple, taken)
Пример #11
0
def highlight(stdscr):
    globvar.redraw = True
    word = get_input(stdscr, "Highlight word: ")
    if not word:
        return
    tab.get_current_tab().highlight.append(word)
Пример #12
0
def goto_backward(stdscr):
    globvar.redraw = True
    word = get_input(stdscr, "Go to: ")
    if not word:
        return
    tab.get_current_tab().goto = (word, BACK)
Пример #13
0
def main():
	input_string = input.get_input()
	vowels = count_vowels(input_string, True)
	vowel_summary(vowels)
Пример #14
0
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +',
    '|    |    |    |    |    |    |    |    |    |    |',
    '+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +'
]

SHIP_LIST = [('Destroyer', 2, 'd2'), ('Cruiser', 3, 'c3'),
             ('Submarine', 3, 's3'), ('Battleship', 4, 'b4'),
             ('Aircraft Carrier', 5, 'a5')]

if __name__ == '__main__':
    board = BLANK_BOARD
    taken = set()

    for ship_tuple in SHIP_LIST:
        board, taken = get_input(board, ship_tuple, taken)
Пример #15
0
def load_profile(stdscr):
    """ Save profile to file"""

    word = get_input(stdscr, "Loading: Profile name:")
    # Get resulting contents
    load_profile_from_file(word)
Пример #16
0
def save_profile(stdscr):
    """ Save profile to file"""

    word = get_input(stdscr, "Saving: Profile name:")
    # Get resulting contents
    save_profile_to_file(word.strip())
Пример #17
0
def build(regime: str, epochs: int, batch_size: int, wd: float,
          learning_rate: float, buffer_size: int) -> list:

    summaries = []

    with tf.name_scope('inputs'):

        batch, dataset_len = get_input(regime, epochs, batch_size, buffer_size)

        cues, responses, lens, target = batch

        global_step = _locate_variable('global_step', [],
                                       tf.constant_initializer(0), False, None)

    with tf.variable_scope('embeddings_matrices', reuse=False):

        cues_embeddings = _locate_variable(
            'cues_embeddings',
            shape=[CUES_MAP_SIZE, 100],
            initializer=tf.random_normal_initializer(),
            trainable=True,
            wd=wd)

        responses_embeddings = _locate_variable(
            'responses_embeddings',
            shape=[RESPONSES_MAP_SIZE, 100],
            initializer=tf.random_normal_initializer(),
            trainable=True,
            wd=wd)

    with tf.name_scope('lookup'):

        cues_embedded = tf.nn.embedding_lookup(cues_embeddings, cues)

        summaries.append(tf.summary.histogram('cues_embeddings',
                                              cues_embedded))

        responses_embedded_raw = tf.nn.embedding_lookup(
            responses_embeddings, responses)

        mask = _return_mask(lens)

        responses_embedded_masked = tf.multiply(mask, responses_embedded_raw)

        responses_embedded = tf.reduce_sum(
            responses_embedded_masked, axis=1) / tf.cast(
                tf.expand_dims(lens, axis=1), dtype=tf.float32)

        summaries.append(
            tf.summary.histogram('response_embeddings', responses_embedded))

    with tf.name_scope('dense_body'):

        dense_input = tf.concat((cues_embedded, responses_embedded), axis=1)

        summaries.append(tf.summary.histogram('dense_input', dense_input))

        with tf.variable_scope('first_dense', reuse=False):

            w1 = _locate_variable(
                'w', [200, 1024],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

            b1 = _locate_variable('b', [
                1024,
            ], tf.random_normal_initializer(), True, wd)

        z1 = tf.nn.elu(tf.matmul(dense_input, w1) + b1)

        with tf.variable_scope('second_dense', reuse=False):

            w2 = _locate_variable(
                'w', [1024, 512],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

            b2 = _locate_variable('b', [
                512,
            ], tf.random_normal_initializer(), True, wd)

        z2 = tf.nn.elu(tf.matmul(z1, w2) + b2)

        with tf.variable_scope('third_dense', reuse=False):

            w3 = _locate_variable(
                'w', [512, 256],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

            b3 = _locate_variable('b', [
                256,
            ], tf.random_normal_initializer(), True, wd)

        z3 = tf.nn.elu(tf.matmul(z2, w3) + b3)

        with tf.variable_scope('forth_dense', reuse=False):

            w4 = _locate_variable(
                'w', [256, 128],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

            b4 = _locate_variable('b', [
                128,
            ], tf.random_normal_initializer(), True, wd)

        z4 = tf.nn.elu(tf.matmul(z3, w4) + b4)

        with tf.variable_scope('fivth_dense', reuse=False):

            w5 = _locate_variable(
                'w', [128, 64],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

            b5 = _locate_variable('b', [
                64,
            ], tf.random_normal_initializer(), True, wd)

        z5 = tf.nn.elu(tf.matmul(z4, w5) + b5)

        with tf.variable_scope('sixth_dense', reuse=False):

            w6 = _locate_variable(
                'w', [64, 32],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

            b6 = _locate_variable('b', [
                32,
            ], tf.random_normal_initializer(), True, wd)

        z6 = tf.nn.elu(tf.matmul(z5, w6) + b6)

        with tf.variable_scope('final_dense', reuse=False):

            w_final = _locate_variable(
                'w', [32, 1], tf.contrib.layers.variance_scaling_initializer(),
                True, wd)

            b_final = _locate_variable('b', [
                1,
            ], tf.random_normal_initializer(), True, wd)

        with tf.variable_scope('skip_connection', reuse=False):

            w_sc = _locate_variable(
                'w', [200, 1],
                tf.contrib.layers.variance_scaling_initializer(), True, wd)

        z_sc = tf.matmul(dense_input, w_sc)

        logits = tf.nn.sigmoid(
            tf.squeeze(tf.matmul(z6, w_final) + b_final + z_sc),
            name='sig_logits')

        summaries.append(tf.summary.histogram('logits', logits))

    with tf.name_scope('mae'):

        mae, metric_update_op = tf.metrics.mean_absolute_error(
            labels=target, predictions=logits)

        running_variables = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES,
                                              scope='mae/mean_absolute_error')

        running_variables_init = tf.variables_initializer(
            var_list=running_variables)

        mae_summary = tf.summary.scalar('mae', mae)

    with tf.name_scope('loss'):

        loss = _return_loss(target, logits)

        summaries.append(tf.summary.scalar('loss', loss))

    with tf.name_scope('optimization'):

        with tf.variable_scope('optimizer', reuse=False):

            optimizer = tf.train.AdamOptimizer(learning_rate)

        grads_vars = optimizer.compute_gradients(loss)

        train_step = optimizer.apply_gradients(grads_vars,
                                               global_step=global_step)

    with tf.name_scope('gradients'):

        for grad, var in grads_vars:

            if grad is not None:

                summaries.append(
                    tf.summary.histogram('gradient_at_{}'.format(var.op.name),
                                         grad))

    with tf.name_scope('variables'):

        for var in tf.trainable_variables():

            summaries.append(
                tf.summary.histogram('var_at_{}'.format(var.op.name), var))

    merge_op = tf.summary.merge(summaries)

    dense_activations = tf.get_collection(tf.GraphKeys.SUMMARIES,
                                          scope='dense_body')

    input_summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope='lookup')

    test_summaries_op = tf.summary.merge(dense_activations + input_summaries)

    mae_merge_op = tf.summary.merge([mae_summary])

    with tf.name_scope('saving'):

        saver = tf.train.Saver()


    return global_step, train_step, merge_op, test_summaries_op, \
        saver, dataset_len, mae_merge_op, running_variables_init, \
            metric_update_op
Пример #18
0
        mario.move(input , board)

    if input == 'q' :
        os.system('clear')
        sys.exit()
    time.sleep(0.2)
'''
a='r'

quit_val = 1
timer = time.time()
timer1 = time.time()
while a=='r':
    if config.level == 2 :
        break
    p_input = (input.get_input())

    if p_input == 'q':
        quit_val = 0
        break

    # cur_round = datetime.datetime.now()
    
    """ if (cur_round - prev_round) >= datetime.timedelta(seconds=1):
        # bd.update_frame()
        # prev_round = cur_round"""

    mario.move(p_input , board)
    board.render((mario._y - 25))
    #board.printer(0,20,0,190)
    print(mario.get_coods())
Пример #19
0
def main():
	input_string = input.get_input()
	reversed_string = reverse_string(input_string)
	print reversed_string
	print "This string a Palindrome?: %s"%(isPalindrome(reversed_string))
Пример #20
0
def main():
        input.get_input()
        NumnodeS = cirdraw.draw()
        prepare.cube_ready(NumnodeS)
        caculater.caclulater(NumnodeS)
Пример #21
0
def main():
	#file = read_file(file_path)
	computer_v2 = get_input()
Пример #22
0
    if eat_coins(screen, player):
        play(coin)
        count += 1
        coin_count -= 1

    if killPlayer(screen, player):
        player = restart(screen, player)
        health -= 1
        if health == 0:
            break

    player.draw(screen, dir)
    mission_comp = checkMissions(mission_comp)
    make_scene(screen)
    try:
        keypress = input.get_input()
        if keypress == 'd':
            iter_count += 1
            dir = 0
            move = checkMove(screen, player)
            if move != 2 and move != 1:
                screen.move_right()
        elif keypress == 'a':
            dir = 1
            move = checkMove(screen, player)
            if move != 3 and move != 1:
                screen.move_left()
        elif keypress == 'w':
            play(jump)
            player.jump(screen)
            make_scene(screen)
Пример #23
0
h2_150 = np.array(Ne150)[1, :]
G_150 = np.add(h1_150, h2_150)
'''
def cal_diff(x, y):
    assert isinstance(x, int)
    a = table_1.iloc[:, x]
    b = h1
    diff = 0
    for i in range(0, len(b)-1):
        if a.loc[i] == b[i]:
            diff = diff
        else:
            diff += 1
    return diff
'''
s, h, r, s_ID = input.get_input()
s_ID = np.array(s_ID)
answer1 = h[:, 2]
answer2 = h[:, 3]
answer_G = np.add(answer1, answer2)


def locus_diff(my_id, his_id):
    different = []
    for i in range(len(my_id)):
        if int(my_id[i]) != his_id[i]:
            different.append(i)
    np.array(different)
    return different

Пример #24
0
            GLOBAL.enemy_list[j].next()

        if level == 2:
            to_del = []
            for j in GLOBAL.bullet_list:
                oldx = GLOBAL.bullet_list[j].x
                GLOBAL.bullet_list[j].next()
                # GLOBAL.bullet_list[j].collision()

                if oldx == GLOBAL.bullet_list[j].x:
                    to_del.append(j)

            for j in to_del:
                del GLOBAL.bullet_list[j]

        a = input.get_input()
        GLOBAL.board.header["points"] = GLOBAL.points
        GLOBAL.board.header["health"] = player.health
        b = int(player.x / config.boardWidth * 100)
        if level == 1:
            GLOBAL.board.header[
                "progress"] = '\n[' + "\033[31m#\033[39m" * b + "-" * (100 -
                                                                       b) + ']'
        if level == 2:
            GLOBAL.board.header["boss health"] = GLOBAL.boss.health

        if player.x >= config.boardWidth - (
                config.dispWidth) / 2 and level != 2:
            fin_score = GLOBAL.points
            os.system("tput reset")
            print("final score: " + str(fin_score))
Пример #25
0
        return lst

    def randomize(self, lst):
        off = numpy.random.random() - 0.5
        for i in range(0, len(lst)):
            lst[i] += (numpy.random.random()-0.5)*0.009 + off*0.02

    def deconvolute(self, convoluted):
        matrix = self._a().I
        return numpy.asarray(matrix * numpy.array(convoluted, ndmin=2).transpose()).transpose()[0]




if __name__ == "__main__":
    original = get_input()
    sigma = 0.02
    disc = Discretizer(sigma, original)
    convoluted = disc.convolute_with_integral()
    convoluted2 = disc.convolute_with_matrix()

    plt.figure()
    plt.plot(original, "r")
    plt.plot(convoluted, "b")

    plt.figure()
    plt.plot(convoluted, "b")
    plt.plot(disc.deconvolute(convoluted2), "r")
    plt.figure()
    plt.plot(original, "r")
    plt.plot(convoluted2, "b")
Пример #26
0
def main():
	input_string = input.get_input()
	pl_string = pig_latin_phrase(input_string)
	print pl_string
Пример #27
0
import prepare
from input import get_input
from AI.SemanticAnalysis import SemanticAnalysis
from config import Config

config = Config()

ai = SemanticAnalysis(config)
sentence = get_input(config.INPUT)
while sentence:
    print("客户: " + sentence)
    ai.get_response(sentence)
    if ai.is_end():
        break
    sentence = get_input(config.INPUT)
Пример #28
0
'''
This is the entry point for the program, everything will happen through here
'''

import fetch
import input
import plot
import simplify

data = 0
while data == 0:
    #Get the input from the user
    symbol = input.get_input()

    #Fetch the data from Google Finance
    if symbol:
        data = fetch.get_data(symbol)

#Simplify the data from Google
simplified_Data = simplify.simplify_data(data)

#Plot the graph of the stock price over time
plot.plot_graph(simplified_Data)
Пример #29
0
def init():	
	star_spawner = logic.star_spawner()

	#Game loop
	while 1:
		var.window.setscreencolors('white','black',clear=True)
		input.get_input()
		
		for d in var.debris:
			if not var.pause or d.owner==var.player:
				d.tick()
			
			d.draw()

		for b in var.bullets:
			if not var.pause and var.state=='game': b.tick()
			b.draw()
		
		for s in var.ships:
			if not var.pause and var.state=='game': s.tick()
			s.draw()
		
		if var.state=='game' and not var.player in var.ships and not var.lives:
			var.pause = True
			
			_count = 0
			for d in var.debris:
				if d.owner==var.player: _count+=1
			
			if not _count:
				sound.pause_song()
				var.window.putchars('YOU ARE DEAD',fgcolor=(255,255,255),x=9,y=15)
		elif var.state=='game' and not var.player in var.ships and var.lives and not var.cleaning:
			var.cleaning = True
			
			sound.pause_song()
			
			for d in var.debris:
				if d.owner==var.player: continue
				
				d.move_speed_max = d.move_speed_max/2
				d.move_speed = 0
			
			for s in var.ships:
				s.move_speed_max = 1#s.move_speed_max/2
				s.move_speed = 0
				s.direction = 'south'
				s.y_limit = var.win_size[1]+1
		elif var.state=='menu':
			_r = random.randint(-100,0)
			var.window.putchars('ASCII SHOOTER',fgcolor=(255+_r,255+_r,255+_r),x=9,y=13-(len(var.main_menu)/2))
			for entry in var.main_menu:
				_i = var.main_menu.index(entry)
				if _i == var.menu_select:
					var.window.putchars('> '+entry['text'],fgcolor=(255,255,255),x=12,y=15-(len(var.main_menu)/2)+_i)
				else:
					var.window.putchars(entry['text'],fgcolor=(255,255,255),x=12,y=15-(len(var.main_menu)/2)+_i)
		
		if var.cleaning:
			var.window.putchars('LIFE -1',fgcolor=(255,255,255),x=12,y=15)
			
			if not len(var.ships):
				var.player = ship.fighter(x=15,y=25,player=True)
				var.player.move_speed_max = 3
				
				var.lives-=1
				sound.unpause_song()
				
				var.cleaning = False
		elif var.pause and var.player in var.ships:
			var.window.putchars('PAUSED',fgcolor=(255,255,255),x=12,y=15)
		
		var.window.putchars('Score %s' % (var.score),fgcolor=(255,255,255),x=0,y=0)
		var.window.putchars('Lives %s' % (var.lives),fgcolor=(255,255,255),x=23,y=0)
			
		if not var.pause and not var.cleaning and var.state=='game': var.ship_spawner.tick()
		if not var.pause: star_spawner.tick()

		var.window.update()
		var.clock.tick(var.fps)