Esempio n. 1
0
#匯入pygame模組
import pygame
#設定顏色
WHITE = color(255, 255, 255)
BLACK = color(0, 0, 0)
RED = color(255, 0, 0)
GREEN = color(0, 255, 0)
BLUE = color(0, 0, 255)
#pygame初始化
pygame.init()
#設定螢幕
pygame.display(640, 70)
#設定視窗標題
screen.blit.set_caption("HIHI")
#設定更新時鐘
clock = pygame.time.Clock()
#設定迴圈開關
done = False
#設定球x原先座標
ball_x = 10
ball_y = 10
#主迴圈
while not done:
    #偵測關閉事件
    for event in pygame.event.get()
        done = true
    #偵測鍵盤事件
    keys = pygame.key.get_pressed()
    #判斷鍵盤是否為左右按鈕,若是則移動球位置
    if keys[pygame.K_RIGHT]:
        ball_x += 30
Esempio n. 2
0
import pygame
import sys
from pygame.locals import *

pygame.init()

SetDisplay = pygame.display()
Esempio n. 3
0
def log(msg):
  print time.asctime(), msg

surface = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE)
info = pygame.display.Info()
screen_width = info.current_w
screen_height = info.current_h

while True:
  try:
    maybeExit(False)
    items = update()
    for item in items:
      download(item)
      display()
      maybeExit()
  except urllib2.HTTPError, ex:
    log(ex)
    time.sleep(1)
  except urllib2.URLError, ex:
    log(ex)
    time.sleep(1)
  except socket.error, ex:
    log(ex)
    time.sleep(1)
  except pygame.error, ex:
    log(ex)
  except httplib.HTTPException:
    log(ex)
Esempio n. 4
0
steer = 90
speed = 0
left_limit = 60
right_limit = 120
GREEN = (0, 255, 0)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_UP:
                print("up")
                steer, speed = pygame.mouse.get_pos()
                pygame.display('s = ' + str(steer))
                #rr.forward()
                #rr.set_led1(True)
                #rr.set_led2(True)
            elif event.key == K_DOWN:
                print('down')
                pygame.draw.line(screen, GREEN, [0, 0], [
                    50,
                    30,
                ], 5)
                pygame.display.flip()
                #rr.set_led1(True)
                #rr.set_led2(True)
                #rr.reverse()
            elif event.key == K_RIGHT:
                print('right')
Esempio n. 5
0
 def __init__(self):
     pygame.init()
     self.screen = pygame.display(set_mode((260, 260)))
     pygame.display.set_caption(TITLE)
     self.clock = pygame.time.Clock()
Esempio n. 6
0
import random as rd
import pygame as pg
import time, sys, os

display = pg.display()
display.title("Platformer")

while True:

    for event in pg.events:
        if event == pg.events.EXIT:
            break

    pg.display.update()

sys.exit()
Esempio n. 7
0
import pygame
from pygame.locals import*
img = pygame.image.load('Family.jpg')

screen = pygame.display.set_mode((640, 480))
pygame.display()

white = (255, 64, 64)
w = 640
h = 480
screen = pygame.display.set_mode((w, h))
screen.fill((white))
running = 0

while (running<1):
    screen.fill((white))
    screen.blit(img,(0,0))
    pygame.display.flip()
    running = running + 1

Esempio n. 8
0
def log(msg):
    print time.asctime(), msg


surface = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE)
info = pygame.display.Info()
screen_width = info.current_w
screen_height = info.current_h

while True:
    try:
        maybeExit(False)
        items = update()
        for item in items:
            download(item)
            display()
            maybeExit()
    except urllib2.HTTPError, ex:
        log(ex)
        time.sleep(1)
    except urllib2.URLError, ex:
        log(ex)
        time.sleep(1)
    except socket.error, ex:
        log(ex)
        time.sleep(1)
    except pygame.error, ex:
        log(ex)
    except httplib.HTTPException:
        log(ex)
                mapselectleftButton.click(event.pos)
            if event.type == pygame.MOUSEBUTTONUP:
                if mapselectleftButton.release(event.pos):         
                    cleanscreen.prev()
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                mapselectrightButton.click(event.pos)
            if event.type == pygame.MOUSEBUTTONUP:
                if mapselectrightButton.release(event.pos):         
                    cleanscreen.next()
                    
            if event.type == pygame.MOUSEBUTTONDOWN:
                optionsButton.click(event.pos)
            if event.type == pygame.MOUSEBUTTONUP:
                if optionsButton.release(event.pos):
                        pygame.display("Images/Screens/temporaryOptionsScreen.png")
                    
                            
                    



        all.update(width, height)

        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(60)
        
    Pointer("Cursors/RedCursor.png")
    pygame.mouse.set_visible(True)
Esempio n. 10
0
def run(display_option, speed, params):
    pygame.init()
    agent = DQNAgent(params)
    weights_filepath = params['weights_path']
    if params['load_weights']:
        agent.model.load_weights(weights_filepath)
        print("weights loaded")

    counter_games = 0
    score_plot = []
    counter_plot = []
    record = 0
    while counter_games < params['episodes']:
        logger.info("===========================")
        logger.info(f"{info_string}")

        time_start = time.time()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        # Initialize classes
        game = Game(440, 440)
        player1 = game.player
        food1 = game.food
        # Perform first move
        initialize_game(player1, game, food1, agent, params['batch_size'])

        if display_option == True:
            display(player1, food1, game, record)

        time_start_game_update = time.time()
        while not game.crash:
            time_start_game_update_pygame = time.time()
            if not params['train']:
                agent.epsilon = 0
            else:
                # agent.epsilon is set to give randomness to actions
                if agent.epsilon <= params['min_epsilon']:
                    agent.epsilon = params['min_epsilon']
                else:
                    agent.epsilon = 1 - (counter_games *
                                         params['epsilon_decay_linear'])

            # get old state
            state_old, vision = agent.get_state(game, player1, food1)

            # perform random actions based on agent.epsilon, or choose the action
            if randint(0, 1) < agent.epsilon:
                final_move = to_categorical(randint(0, 2), num_classes=3)
            else:
                # predict action based on the old state
                prediction = agent.model.predict(
                    state_old.reshape((1, params['num_input_features'])))
                final_move = to_categorical(np.argmax(prediction[0]),
                                            num_classes=3)

            # perform new move and get new state
            player1.do_move(final_move, player1.x, player1.y, game, food1,
                            agent)
            state_new, vision = agent.get_state(game, player1, food1)

            # set reward for the new state
            reward = agent.set_reward(player1, game.crash)
            time_end_game_update_pygame = time.time()

            time_start_game_update_train = time.time()

            if params['train']:
                # train short memory base on the new action and state
                agent.train_short_memory(state_old, final_move, reward,
                                         state_new, game.crash)
                # store the new data into a long term memory
                agent.remember(state_old, final_move, reward, state_new,
                               game.crash)

            time_end_game_update_train = time.time()

            time_start_game_update_record = time.time()
            record = get_record(game.score, record)
            time_end_game_update_record = time.time()

            logger.debug("Pygame update step: " +
                         str((time_end_game_update_pygame -
                              time_start_game_update_pygame)))
            logger.debug("Train short term update step: " +
                         str((time_end_game_update_train -
                              time_start_game_update_train)))
            logger.debug("Record score  step: " +
                         str((time_end_game_update_record -
                              time_start_game_update_record)))

            if display_option == True:
                cv2.imshow("Vision of the Snake", vision * 255.0)

                # detect any kepresses
                key = cv2.waitKey(1) & 0xFF
                # if the `q` key was pressed, break from the loop
                if key == ord("q"):
                    break
                display(player1, food1, game, record)
                pygame.time.wait(speed)

        # # Pause visualisation if crash
        # if display_option==True:
        #     cv2.imshow("Vision of the Snake", vision * 255.0)
        #
        #     # detect any kepresses
        #     key = cv2.waitKey(1) & 0xFF
        #     # if the `q` key was pressed, break from the loop
        #     if key == ord("q"):
        #         break
        #     display(player1, food1, game, record)
        #     pygame.time.wait(5000)
        time_end_game_update = time.time()
        logger.info(
            "Time to play one game: " +
            str(round((time_end_game_update - time_start_game_update), 3)))

        time_start_long_term = time.time()
        if params['train']:
            agent.replay_new(agent.memory, params['batch_size'])
        time_end_long_term = time.time()
        logger.info("Train long term update step: " +
                    str(round((time_end_long_term - time_start_long_term), 3)))

        if agent.epsilon <= params['min_epsilon']:
            agent.epsilon = params['min_epsilon']
        else:
            agent.epsilon = 1 - (counter_games *
                                 params['epsilon_decay_linear'])
        logger.info(f'The epsilon value is: {agent.epsilon}')

        logger.debug("===========================")

        counter_games += 1
        logger.info(f'Game {counter_games}      Score: {game.score}')
        logger.info(f'The agent memory length is: {len(agent.memory)}')

        score_plot.append(game.score)
        counter_plot.append(counter_games)
        if params['train'] and counter_games % 100 == 0:
            agent.model.save_weights(params['weights_path'])
            logger.info("===========SAVING THE MODEL================")
            with open(params['memory_path'], 'wb') as handle:
                pickle.dump(agent.memory, handle)
        logger.info("End Game Loop")
        time_end = time.time()
        epoch_timer = round((time_end - time_start), 3)
        logger.info(f"One epoch takes: {epoch_timer} seconds")
        eta_prediction = round(
            (params['episodes'] - counter_games) * epoch_timer / 60)
        logger.info(f"Time remaining is: {eta_prediction} minutes")

    if params['train']:
        agent.model.save_weights(params['weights_path'])
        with open(params['memory_path'], 'wb') as handle:
            pickle.dump(agent.memory, handle)
        params['counter_plot'] = counter_plot
        params['score_plot'] = score_plot
        with open(params['params_path'], 'wb') as handle:
            pickle.dump(params, handle)
Esempio n. 11
0
label_file = 'data/bike_w2v' + str(w_size) + str(w_fre) + '2D_label.txt'

pds_r = 0.01
geo_tsne_file = 'data/sampling/bike_w2v' + str(w_size) + str(
    w_fre) + 'geo_tsne' + '.txt'
geo_sem_file = 'data/sampling/bike_w2v' + str(w_size) + str(
    w_fre) + 'geo_sem_tsne' + '.txt'

samples_pos_file = 'data/sampling/bike_w2v' + str(w_size) + str(
    w_fre) + '2D_samping' + str(pds_r) + '.txt'
samples_pos1_file = 'data/sampling/bike_w2v' + str(w_size) + str(
    w_fre) + '2D_samping' + str(pds_r) + '_sem.txt'
samples_name_file = 'data/sampling/bike_w2v' + str(w_size) + str(
    w_fre) + '2D_samping' + str(pds_r) + '_name.txt'
samples_label_file = 'data/sampling/bike_w2v' + str(w_size) + str(
    w_fre) + '2D_samping' + str(pds_r) + '_label.txt'
#tsne geo + semantic  for sampling
station_data = tsne_geo_semantic(name_file, labels_file, dict_id2loc, pos_file,
                                 geo_tsne_file, geo_sem_file)
station_data = readData(geo_sem_file)
#sampling
gene_data = copy.deepcopy(station_data)
samples = generate_uniform_points(pds_r, gene_data)
labelData(samples, station_data)
generate_data(name_file, samples_pos_file, samples_name_file)
samples_label(labels_file, samples_name_file, samples_label_file)
geo_station2sem_staion(samples_name_file, pos_file, name_file,
                       samples_pos1_file)
# display
display(samples)