Exemple #1
1
def main():
    start_time = time.time()

    ## Graphics class
    screen = Screen(constants.WIDTH, constants.HEIGHT)

    player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.BLACK)
    player2 = Paddle(screen, constants.WIDTH - 4, constants.HEIGHT / 2 - 1,
                     constants.BLACK)

    net = Net(screen, constants.BLACK)

    ball = Ball(screen, 0, 0, constants.BALL_COLOUR)
    # Dummy values
    ball.velocity = [8.0, 8.0]  #Roughly 10 seconds to cross screen?
    ball._served = True

    while (True):
        end_time = time.time()
        frame_time = end_time - start_time
        start_time = end_time

        player1.update(frame_time)
        player2.update(frame_time)
        ball.update(frame_time)

        player1.draw()
        player2.draw()
        ball.draw()

        net.draw()

        screen.draw_num(*constants.SCORE1, score1, constants.SCORE_COLOUR)
        screen.draw_num(*constants.SCORE2, score2, constants.SCORE_COLOUR)
    def test_paint_fill_nine_point_one_color(self):
        before_screen = Screen(3, 3, Color(0, 0, 0))
        after_screen = Screen(3, 3, Color(255, 255, 255))
        recursive_paint_fill_strategy = RecursivePaintFillStrategy(
            before_screen, Point(0, 0), Color(255, 255, 255))

        recursive_paint_fill_strategy.paint_fill()

        self.assertEqual(str(after_screen), str(before_screen))
    def test_paint_fill_one_point_one_color(self):
        """BUILD-OPERATE-TEST pattern used."""
        # Build
        before_screen = Screen(1, 1, Color(0, 0, 0))
        after_screen = Screen(1, 1, Color(255, 255, 255))
        recursive_paint_fill_strategy = RecursivePaintFillStrategy(
            before_screen, Point(0, 0), Color(255, 255, 255))

        # Operate
        recursive_paint_fill_strategy.paint_fill()

        # Test
        self.assertEqual(str(after_screen), str(before_screen))
Exemple #4
0
    def __init__(self):
        pygame.init()
        pygame.key.set_repeat(20)
        self.clock = pygame.time.Clock()

        self.screen = pygame.display.set_mode(config.WINDOW_SIZE, DOUBLEBUF)
        self.screen.set_alpha(None)

        self.players = []
        self.walls = []
        self.roads = []

        self.startScreen = Screen("wait.jpg")
        self.loseScreen = Screen("lose.png")
        self.winScreen = Screen("win.png")
    def test_paint_fill_nine_points_two_colors(self):
        before_screen = Screen(3, 3, Color(0, 0, 0))
        after_screen = Screen(3, 3, Color(0, 0, 0))
        for row in range(2):
            for column in range(2):
                before_screen.set_color_at_point(Point(row, column),
                                                 Color(128, 128, 128))
                after_screen.set_color_at_point(Point(row, column),
                                                Color(255, 255, 255))
        recursive_paint_fill_strategy = RecursivePaintFillStrategy(
            before_screen, Point(0, 0), Color(255, 255, 255))

        recursive_paint_fill_strategy.paint_fill()

        self.assertEqual(str(after_screen), str(before_screen))
Exemple #6
0
    def __init__(self, rom="invaders.rom"):
        self.cpu = CPU()
        self.memory = Memory()
        self.memory.Load(rom)

        self.ports = Puertos()
        self.Screen = Screen()
Exemple #7
0
 def __init__(self):
     print("ZeMo is Running")
     self.screen = Screen()
     self.screen.drawImage("logo.png", self.screen.background.get_rect(), 223, 57)
     self.conn = Connection()
     self.done = False
     self.takeReadFlag = True
     self.readingNow = False
     self.waitTime = 0
     jsonFile = self.conn.getJSONconfig()
     self.daysToKeep = jsonFile["settings"]["days"]
     self.readsPerDay = jsonFile["settings"]["reads"]
     self.timeList = []
     piName = self.conn.getPiName()
     self.phSensor = PH(jsonFile, piName, self.screen)
     self.condSensor = Conductivity(jsonFile, piName, self.screen)
     self.dOSensor = DissolvedOxygen(jsonFile, piName, self.screen)
     self.tempSensor = Temperature(jsonFile, piName, self.screen)
     self.sensorList = []
     self.sensorList.append(self.tempSensor)
     self.sensorList.append(self.condSensor)
     self.sensorList.append(self.phSensor)
     self.sensorList.append(self.dOSensor)
     for sensor in self.sensorList:
         sensor.takeRead(self.conn)
     self.t2 = Thread(target=App.checkTime_loop, args=(self,))
     self.t2.start()
     self.update_reads_per_day()        
Exemple #8
0
 def left(self, length=None):
     """
     Return left area relates to self, do not including self.
     Height of new area is equal to height of self.
     Width of new area is equal to 'length' or till the end of the screen
     if 'length' is not set
     """
     left_title = 'Region left of {}'.format(self.title)
     try:
         if length is None:
             scr = Region(*Screen(self.screen_number).area)
             reg = Region(scr.x,
                          self.y, (self.x - 1) - scr.x + 1,
                          self.h,
                          find_timeout=self._find_timeout,
                          title=left_title)
         elif isinstance(length, int) and length > 0:
             reg = Region(self.x - length,
                          self.y,
                          length,
                          self.h,
                          find_timeout=self._find_timeout,
                          title=left_title)
         else:
             raise FailExit(
                 'Incorrect length: type is {type}; value is {length}'.
                 format(typr=str(type(length)), length=str(length)))
     except FailExit:
         raise FailExit(
             'Incorrect left() method call:\n\tlength = {length}'.format(
                 length=length))
     return reg
Exemple #9
0
def main_old():

    screen = Screen(600, 600)
    screen.start()
    b = []
    active = True
    tic = TicTacToe()
    tic.start(screen)
    reset_counter = 0
    while (active):

        if (tic.show(screen) == -1):
            tic = TicTacToe()
            tic.start(screen)
            continue
        act = screen.act()
        if (isinstance(act, (list, tuple))):
            if (act[0] >= 0):
                tic.press(act[1])

        if (act == -1):

            active = False
            break
        if (act == 'r' or reset_counter < 0):
            tic = TicTacToe()
            tic.start(screen)
            reset_counter = 0
        if (0 not in tic.values):
            if (reset_counter <= 0):
                reset_counter = 101
            else:
                reset_counter -= 2
    screen.close()
Exemple #10
0
def main():
    cols, rows = 10, 10
    screen = Screen(500, 500, rows)
    screen.show()
    screen.makeGrid()
    
    grid = [[Spot(screen, i, j) for j in range(0, rows)] for i in range(0, cols)]

    for i in range(0, cols):
        for j in range(0, rows):
            grid[i][j].addNeigbors(grid, cols, rows)

    start = grid[0][0]
    start.obstacle = False
    stop = grid[cols - 1][rows - 1]
    stop.obstacle = False

    pathFinder = PathFinder(grid, start, stop)
    
    while True:
        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                screen.close()
        
        
        result = pathFinder.findPath()
        pathFinder.showOpenSet()
        pathFinder.showPath()
        screen.update()
Exemple #11
0
def set_screen():
    WINDOW_SIZE = [255, 255]
    title = "Tic Tac Toe"
    screen = Screen(WINDOW_SIZE, title)
    screen = screen.setup_screen(Color.BLACK)
    clock = pygame.time.Clock()
    return screen, clock
    def reset(self):
        # Initialize Pygame
        pygame.init()
        pygame.display.set_caption('Snake')

        self.frames = collections.deque(maxlen=4)

        # Initialize screen
        self.screenPyGame = pygame.display.set_mode((GRID_SIZE, GRID_SIZE))
        self.screen = Screen(region=(0, 40, GRID_SIZE, GRID_SIZE + 40))

        # Initialize score
        self.score = 0

        # Initialize direction
        self.direction = LEFT

        # Initialize snake
        self.snake = [(100, 100), (110, 100), (120, 200)]
        self.snake_skin = pygame.Surface((10, 10))
        self.snake_skin.fill((255, 255, 255))

        # Initialize apple
        self.apple_pos = self.on_grid_random()
        self.apple = pygame.Surface((10, 10))
        self.apple.fill((255, 0, 0))

        # Initialize clock
        self.clock = pygame.time.Clock()

        return self.preprocess_image(self.screen_state())
Exemple #13
0
def main():
    # initialize the pygame module
    pygame.init()
    pygame.display.set_caption("Tetris Clone")

    # create a surface on screen that has the size of 240 x 180
    screen = pygame.display.set_mode((640, 480))
    screen_model = Screen()
    screen_model.spawnPiece()

    # define a variable to control the main loop
    running = True
    score = Score()

    i = 0
    # main loop
    while running:
        pygame.time.delay(350)
        on_event(pygame, running, screen_model, score)
        on_loop(pygame, screen_model, score)
        on_render(pygame, screen, screen_model, score)
        if i == 0:
            playMidi(pygame, "GameBegin1.wav")
            pygame.time.delay(1000)
            playMidi(pygame, "GameBegin2.wav")
            playMidi(pygame, "Theme.wav")
        i += 1
    pygame.midi.quit()
Exemple #14
0
    def reset(self):
        # Initialize Pygame
        pygame.init()
        pygame.display.set_caption('Snake')

        # Initialize screen
        self.screenPyGame = pygame.display.set_mode((GRID_SIZE, GRID_SIZE))
        self.screen = Screen(region=(0, 40, GRID_SIZE, GRID_SIZE + 40))

        # Initialize score
        self.score = 0

        # Initialize direction
        self.direction = LEFT

        # Initialize snake
        self.snake = [(50, 50), (60, 50), (70, 50)]
        self.head_skin = pygame.Surface((10, 10))
        self.head_skin.fill((25, 255, 25))
        self.snake_skin = pygame.Surface((10, 10))
        self.snake_skin.fill((255, 255, 255))

        # Initialize apple
        self.apple_pos = self.on_grid_random()
        self.apple = pygame.Surface((10, 10))
        self.apple.fill((255, 0, 0))

        # Initialize clock
        self.clock = pygame.time.Clock()
    def CollectingTrainingData(self):
        keys = Keys()
        screen = Screen()
        agent = Agent()
        print('Starting Training in...')

        # Countdown to start the training
        for i in list(range(4))[::-1]:
            print(i + 1)
            time.sleep(1)

        paused = False
        last_time = time.time()

        while True:

            if not paused:
                grabbed_screen = screen.GrabScreen()  # Get actual frame
                keys_pressed = keys.KeyCheck()  # Check for pressed keys
                output_action = keys.KeysActionFreeKicksOutput(
                    keys_pressed)  # Verifies if one action key was pressed
                if output_action != [0, 0, 0, 0]:
                    self.training_data.append(
                        [grabbed_screen,
                         output_action])  # Create an instance of training data

            if output_action == [1, 0, 0, 0]:
                print('Left')
                agent.left()
            elif output_action == [0, 1, 0, 0]:
                print('Right')
                agent.right()
            elif output_action == [0, 0, 1, 0]:
                print('Low Kick')
                agent.low_shoot()
            elif output_action == [0, 0, 0, 1]:
                print('High Kick')
                agent.high_shoot()

            if len(self.training_data) % 100 == 0 and len(
                    self.training_data) > 0:
                print(len(self.training_data))

            keys_pressed = keys.KeyCheck()

            # Pausing or Unpausing training
            if 'Q' in keys_pressed:
                if paused:
                    paused = False
                    print('Unpausing training...')
                    time.sleep(2)
                else:
                    print('Pausing training!')
                    paused = True
                    time.sleep(1)

# Saving Data
            if 'R' in keys_pressed:
                np.save(self.path_file, self.training_data)
Exemple #16
0
    def __init__(self):
        super().__init__()

        self._stop = threading.Event()
        self.cnt = 0
        GameStatus().window.status_changed()
        self.screen = Screen()
        self.do_loop = True
 def GetScreen(self, screenShot):
     screenType = ScreenType.UNKNOWN
     image = None
     for template in self.templates:
         if template.IsMatch(screenShot) == True:
             screenType = template.screenType
             image = screenShot.image
             break
     return Screen(screenType, image)
Exemple #18
0
    def __init__(self):
        print("Press Ctrl-C to quit")

        self.gamepad = GamePad()
        self.screen = Screen()
        self.entityManager = EntityManager()
        self.player = Player(self)
        self.world = World(self)
        self.entityManager.add(self.player)
Exemple #19
0
    def __init__(self, sense):
        x, y = 1, 3
        self.player = Player(x, y)
        self.screen = Screen(sense)
        self.screen.setWhiteScreen()

        self.state = 0
        self.counter = 0
        self.points = 0
Exemple #20
0
    def __init__(self):

        self.Screen = Screen()
        self.config = Config()
        self.playerlist = None

        self.turn = 0
        self.game_ended = False

        pass
Exemple #21
0
class Symulation:
    running = True
    space = Space()
    drone = Drone()
    screen = Screen(space)
    clock = time.Clock()
    fps = 35

    def __init__(self):
        self.space.gravity = 0, -980.7
        self.space.damping = 0.3
        self.space.add(self.drone.GetDrone())

    def Start(self):
        while self.running:
            for ev in event.get():
                if key.get_pressed()[K_ESCAPE]:
                    self.running = False
                if ev.type == KEYDOWN:
                    if ev.key == K_UP:
                        self.drone.moveDirection[0] = True
                    if ev.key == K_DOWN:
                        self.drone.moveDirection[1] = True
                    if ev.key == K_RIGHT:
                        self.drone.moveDirection[2] = True
                    if ev.key == K_LEFT:
                        self.drone.moveDirection[3] = True
                if ev.type == KEYUP:
                    if ev.key == K_UP:
                        self.drone.moveDirection[0] = False
                    if ev.key == K_DOWN:
                        self.drone.moveDirection[1] = False
                    if ev.key == K_RIGHT:
                        self.drone.moveDirection[2] = False
                    if ev.key == K_LEFT:
                        self.drone.moveDirection[3] = False
            if mouse.get_pressed()[0]:
                pos = mouse.get_pos()
                if 10 <= pos[0] <= 120:
                    if 250 <= pos[1] <= 270:
                        self.drone.logicModel = "Neural Network"
                        self.fps = 35
                        self.screen.repeats = 2
                    elif 280 <= pos[1] <= 300:
                        self.drone.logicModel = "Fuzzy Logic"
                        self.fps = 60
                        self.screen.repeats = 4
            self.drone.Move()
            self.screen.UpdateScreen(self.space, self.drone)
            self.UpdateTimes()

    def UpdateTimes(self):
        dt = 1. / self.fps
        self.space.step(dt)
        self.clock.tick(self.fps)
Exemple #22
0
    def execute_agent(self):

        keys = Keys()
        screen = Screen()

        print('Starting running Direct Imitation Learning in...')

        # Countdown to start running the agent
        for i in list(range(4))[::-1]:
            print(i + 1)
            time.sleep(1)

        paused = False

        while True:

            if not paused:
                img = screen.GrabScreenBGR()

                # Preprocessing input image
                converted_img = np.array(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
                resized_img = cv2.resize(converted_img, (120, 90))
                reshaped_img = resized_img.reshape(-1, 90, 120, 1)
                normalized_img = reshaped_img.astype('float32') / 255.0
                final_img = normalized_img

                # Prediction and Entropy of the Labels
                move_prediction = self.predict_move(final_img)
                action_prediction = self.predict_action(final_img)
                move_action = np.argmax(move_prediction[0])
                control_action = np.argmax(action_prediction[0])
                print(move_prediction[0], ' - ', action_prediction[0])

                # Move action
                self.execute_movement_action(move_action)
                #self.execute_movement_action_with_threshold(move_prediction[0])

                # Action action
                self.execute_control_action(control_action)
                #self.execute_control_action_with_threshold(action_prediction[0])

            keys_pressed = keys.KeyCheck()

            if 'Q' in keys_pressed:
                if paused:
                    paused = False
                    print('unpaused!')
                    time.sleep(1)
                else:
                    print('Pausing!')
                    self.release_moves()
                    paused = True
                    time.sleep(1)
Exemple #23
0
    def __init__(self):
        self.screen = Screen()
        self.surface = self.screen.make_screen()  # screen itself
        self.platform = Platform(self.screen)
        self.game_over = False
        self.objects = []
        self.ball = Image(self.filename)
        self.game_over_text = Text("Game over!")

        self.buttons = {
            'd_is_pressed':
            False,  # Переменные для постоянного движения платформы при длительном нажатии
            'a_is_pressed': False
        }
Exemple #24
0
    def CreateTrainingData(self):
        keys = Keys()
        screen = Screen()
        print('Starting Training in...')

        # Countdown to start the training
        for i in list(range(4))[::-1]:
            print(i + 1)
            time.sleep(1)

        paused = False
        last_time = time.time()

        while True:

            if not paused:
                grabbed_screen = screen.GrabScreenBGR()  # Get actual frame
                new_screen = cv2.resize(
                    cv2.cvtColor(grabbed_screen, cv2.COLOR_BGR2GRAY),
                    (120, 90))  # Converted and Resized frame
                #normalized_screen = new_screen.astype('float32') / 255 # Normalizing
                keys_pressed = keys.KeyCheck()  # Check for pressed keys
                output_move = keys.KeysMovementOutput(
                    keys_pressed)  # Verifies if one move key was pressed
                output_action = keys.KeysActionOutput(
                    keys_pressed)  # Verifies if one action key was pressed
                self.training_data.append(
                    [new_screen, output_move,
                     output_action])  # Create an instance of training data

            if len(self.training_data) % 1000 == 0:
                print(len(self.training_data))

            keys_pressed = keys.KeyCheck()

            # Pausing or Unpausing training
            if 'Q' in keys_pressed:
                if paused:
                    paused = False
                    print('Unpausing training...')
                    time.sleep(2)
                else:
                    print('Pausing training!')
                    paused = True
                    time.sleep(1)

# Saving Data
            if 'P' in keys_pressed:
                np.save(self.path_file, self.training_data)
Exemple #25
0
def main():
    ## Graphics class
    screen = Screen(constants.WDITH, constants.HEIGHT)

    player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.BLUE)
    player2 = Paddle(screen, constants.WDITH - 4, constants.HEIGHT / 2 - 1,
                     constants.BLUE)

    net = Net(screen, constants.BLACK)

    sceen.clear()

    player1.draw()
    player2.draw()
    net.draw()
Exemple #26
0
def display_evaluation_game(input_file):
    pygame.init()
    stan = State()
    game_screen = Screen(stan.game_width, stan.game_length)
    clock = pygame.time.Clock()

    with open(input_file, "r") as fp:
        for line in fp:
            single_move = eval(line)
            screen, reward_print, total_reward = single_move
            clock.tick(5)
            convert_env_to_state(stan, screen)
            game_screen.display_move(stan)
            text2 = game_screen.myfont.render(
                "Score: {:0.0f} | Step reward: {:0.2f} | Total reward: {:0.1f}"
                .format(stan.points, reward_print, total_reward), 1, (0, 0, 0))
            game_screen.game_display.blit(text2, (10, 10))
            pygame.display.update()
Exemple #27
0
def main():
    pygame.init() #Initialize pygame
    stan = State() #Initialize state of the game
    game_screen = Screen(stan.game_width, stan.game_length) #Initialize game screen
    snake_dead = False
    clock = pygame.time.Clock()

    while not snake_dead:
        clock.tick(5)
        key = handle_keys()
        if key is None:
            key = stan.prev_key
        stan.move_snake(key)
        snake_dead = not stan.check_if_snake_lives()
        text = game_screen.myfont.render("Score {0}".format(stan.points), 1, (0, 0, 0))
        game_screen.game_display.blit(text, (5, 10))
        game_screen.display_move(stan) #Update game screen
        pygame.display.update()
Exemple #28
0
 def __init__(self):
     pygame.init()
     self.WIDTH = 640
     self.HEIGHT = 480
     self.screen = Screen(self.WIDTH, self.HEIGHT)
     self.screen.caption("Squash game")
     self.clock = pygame.time.Clock()
     self.FPS = 30
     RED = (255, 0, 0)
     START = (randint(0, self.WIDTH - 1), 0)
     self.ball = Ball(self.screen.surface, color=RED, start=START)
     left = self.WIDTH // 2
     top = self.HEIGHT - 50
     self.racket = Racket(self.screen.surface, left=left, top=top)
     xpos = left
     ypos = self.HEIGHT // 2
     YELLOW = (255, 255, 0)
     self.msg_gover = Message( self.screen.surface, 'Game Over!!',\
                               xpos, ypos, color=YELLOW )
     pygame.key.set_repeat(10, 10)
Exemple #29
0
    def __init__(self, _interval=20 * 60, _total=30):
        # 图片显示
        self.screen = Screen()
        # 时间间隔 & 提醒次数
        self.interval = _interval  # 20*60 20min 20-20-20原则
        self.total = _total  # 30次 -> 10小时

        # html内容
        self.html_content = r'''<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible"content="ie=edge"><title>Take A Break</title><style>body{margin:0;position:relative}img{height:auto;width:auto\9;width:100%}.center{position:absolute;margin:auto;padding:auto;width:100%;text-align:center}.text{font-size:60px;color:rgb(255,255,255);width:100%;font-family:PMingLiu,MingLiU,Microsoft YaHei}.time{font-size:200px;color:rgb(255,255,255);width:100%;height:400px;line-height:400px}</style></head><body onload="time()"><div class="center"><div class="text time">20</div><div class="text">远眺</div></div><img src="https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture"/></body><script type="text/javascript">var wait=20;function time(){document.getElementsByClassName("time")[0].innerHTML=wait.toString();if(wait==0){texts=document.getElementsByClassName("text");for(const index in texts){if(texts.hasOwnProperty(index)){const text=texts[index];text.innerHTML=""}}}else{wait--;setTimeout(function(){time()},1000)}}</script></html>'''

        # 获取文件绝对路径
        self.Dir_Path = os.path.dirname(os.path.abspath(__file__))
        self.html_file_path = os.path.join(self.Dir_Path, 'TakeABreak.html')

        # 创建html文件(如果不存在的话)
        if not os.path.isfile(self.html_file_path):
            print('正在创建html文件...')
            with open(self.html_file_path, 'w', encoding='utf-8') as file:
                file.write(self.html_content)
                print('创建完成:', self.html_file_path)
Exemple #30
0
 def __init__(self):
     logging.basicConfig(filename="/home/pi/ZeMoCode/Data/ZeMo.log",
                         level=logging.INFO)
     self.screen = Screen()
     self.eth0 = self.get_ip("eth0", 3)
     self.wlan0 = self.get_ip("wlan0", 3)
     registered = False
     try:
         with open("/home/pi/ZeMoCode/account") as f:
             acnt = f.read()
             self.account = acnt.strip('\n')
             self.logInfo("ACCOUNT " + self.account)
     except:
         # Occurs if the account file did not create properly from SetupZeMo.sh file
         self.account = "NULL_ACCOUNT_NAME"
     if self.account is "NULL_ACCOUNT_NAME":
         self.screen.drawMessage("No Account Found, Please Retry")
         self.logInfo("No account found")
         time.sleep(30)
     self.piName = socket.gethostname()
     try:
         # Tries to load an existing account
         self.accountJSON = json.load(
             open('/home/pi/ZeMoCode/account.json'))
         self.secret = self.accountJSON["secret"]
         try:
             self.jsonConfig = self.getConfigData()
         except:
             self.logInfo("Did not grab config file")
         if self.secret is "none":
             # Loops until registration is completed
             while registered is False:
                 registered = self.register()
     except Exception as e:
         # Registers if no existing account is found
         self.secret = "none"
         # Loops until registration is completed
         while registered is False:
             registered = self.register()
     self.screen.drawImage("logo.png", self.screen.background.get_rect(),
                           223, 57)