当前位置: 首页>>代码示例>>Python>>正文


Python Timer.update方法代码示例

本文整理汇总了Python中timer.Timer.update方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.update方法的具体用法?Python Timer.update怎么用?Python Timer.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在timer.Timer的用法示例。


在下文中一共展示了Timer.update方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
def run(path, debug, max_cycles):
    with open(path, "rb") as rom_file:
        debug_title = debug == "TITLE"
        debug_header = debug == "HEADER" or debug == "ALL"
        debug_mem = debug == "MEMORY" or debug == "ALL"
        debug_instructions = debug == "INSTRUCTIONS" or debug == "ALL"
        debug_registers = debug == "REGISTERS" or debug == "ALL"
        rom = [i for i in rom_file.read()]
        
        header = Header(rom, debug_header)
        mem = Memory(rom, header)
        if debug_title:
            print("Title: " + header.name)
        if debug_instructions:
            print("PC:    Operation")
        
        interrupts = Interrupts()
        cpu = CPU(mem, interrupts, debug_instructions, debug_registers)
        timer = Timer(interrupts)
        sound = Sound()
        link = Link()
        joypad = Joypad()
        lcdc = LCDC(mem, interrupts)
        mem.setupIO(lcdc, interrupts, timer, sound, link, joypad)
        total_cycles = 0

        try:
            pygame.init()
            while cpu.run_state != "QUIT":
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        cpu.run_state = "QUIT"
                    if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                        joypad.keyEvent(event)

                interrupts.update()
                if cpu.run_state == "RUN":
                    cpu.run()
                else:
                    cpu.cycles += 1

                timer.update(cpu.cycles)
                lcdc.update(cpu.cycles)

                total_cycles += cpu.popCycles()
                if max_cycles >= 0 and total_cycles > max_cycles:
                    cpu.run_state = "QUIT"
        except AssertionError as e:
            if debug_mem:
                mem.display()
            traceback.print_tb(e.__traceback__)
        except KeyboardInterrupt as e:
            if debug_mem:
                mem.display()
        else:
            if debug_mem:
                mem.display()
开发者ID:rukai,项目名称:GameToy,代码行数:59,代码来源:gametoy.py

示例2: TestTimer

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class TestTimer(unittest.TestCase):
    def setUp(self):
        self.timer = Timer()

    def test_timer_is_running_if_it_is_started(self):
        self.timer.start()
        self.assertTrue(self.timer.running)

    def test_timer_is_not_running_if_it_is_paused(self):
        self.timer.pause()
        self.assertFalse(self.timer.running)

    def test_time_left_is_decremented_one_second_if_timer_is_running(self):
        self.time_left = 300
        self.timer.start()
        self.timer.update()
        self.assertEqual(self.timer.time_left, 299)
开发者ID:GunioRobot,项目名称:dojotools,代码行数:19,代码来源:test_timer.py

示例3: main

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
def main():

    open_canvas()

    global background, score, timer, burger, character_list
    global running
    global current_time, frame_time
    background = Background()
    score = Score()
    timer = Timer()
    character_list = [Character() for i in range(nCharacter)]
    burger.draw()

    running = True
    current_time = get_time()

    while running:
        frame_time = get_frame_time()
        handle_events()
        for character in character_list:
            character.update(frame_time)

        clear_canvas()
        background.draw()
        score.draw()
        score.update(value)
        timer.draw()
        timer.update(time_value)
        for character in character_list:
            character.draw()
            character.draw_bb()
        burger.draw()

        update_canvas()




    close_canvas()
开发者ID:yohan7979,项目名称:2DGP,代码行数:41,代码来源:main_state.py

示例4: __init__

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]

#.........这里部分代码省略.........
        }

        self.blokid = []
        self.pahad = []
        self.laserid = []
        self.lained = []

        pygame.font.get_fonts()
        self.font=pygame.font.SysFont('bauhaus93',35)


        self.level = 1

        self.levelTime = levelTime
        self.levelTimer = Timer(self.levelTime)

        self.run = True

        self.mouseHolding = False

        self.gaming = False

        self.randomItems = []

        # timer mis hakkab random aja tagant maha asju genereerima
        self.randomItemTimer = Timer(random.randint(10,self.levelTime*2))
        self.randomItemTimer.run()

        self.bossInit = False # alguses pole bossi

        self.linex = 300
        self.linexDx = 1

    def update_logic(self):

        if not self.gaming:
            return

        self.generate_random_items()


        self.mees.update_logic() # uuendab meest

        if(self.mouseHolding): # kui hiirt hoitakse all->automaatne tulistamine
            self.mees.automatic()

        for laser in self.laserid:
            laser.update_logic()

            if(collision(laser.rect,self.mees.rect) and laser.wait.end == True and laser.delay.end == True): # kui mees saab laserit
                self.mees.getRekt(laser.dmg) # mees saab dmg
                laser.bye()

        for laine in self.lained:
            if not(laine.update_logic()): # laine joudnud loppu
                if(laine.type == "lyke"): # kui lykkav laine
                    if(laine in self.lained): # kaob ara
                        self.lained.remove(laine)
                else: # vastasel juhul havitame ------------------------------< SIIN [email protected] PAUK
                    for enemy in self.pahad:
                        if(collision_circle_rect(laine,enemy.rect)):
                            if(enemy in self.pahad):
                                self.pahad.remove(enemy)
                    self.lained.remove(laine)
                    continue
开发者ID:Kaspar94,项目名称:SpaceKappaShooter,代码行数:69,代码来源:main.py

示例5: __init__

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class game_client:
    def __init__(self, address, motionblur):
        self.address = address;
        pygame.init();
        self.window = pygame.display.set_mode((800, 600));
        self.screen = pygame.display.get_surface();
        pygame.mouse.set_cursor(*pygame.cursors.diamond);
        self.fpsCounter = Timer(0);
        self.socket_init();
        self.ships = list();
        self.shots = list();
        self.motionblur = motionblur;
        if self.motionblur:
            self.ownBuffer = pygame.Surface((800, 600));
            self.ownBuffer.set_alpha(256-(255.0/motionblur));

        self.pntShip = (
            Vector(0,-10),
            Vector(0,10),
            Vector(30,0)
            );

        self.debugVar = None;
        thread.start_new_thread(self.debug, ());

    def run(self):
        while True:
            self.fpsCounter.update();
            input(pygame.event.get());
            if self.network(): break;
            Shot.updates(self.shots);
            self.draw();

        print "Lost connection to server";
        self.sock.close();

    def draw(self):
        self.screen.fill((0,0,0));
        if self.motionblur: self.screen.blit(self.ownBuffer, (0,0));
        for ship in self.ships:
            pos = Vector(ship[0][0], ship[0][1]);
            self.draw_ship(pos, ship[2] / 100.0);
        for shot in self.shots:
            pygame.draw.circle(self.screen, (0,255,0), shot.pos.get(1), 3);
        pygame.display.flip();
        if self.motionblur: self.ownBuffer.blit(self.screen, (0,0));

    def socket_init(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        while self.sock.connect_ex((self.address, 1234)):
            print "Connection failed";
            time.sleep(5);
        print "Successful connection";
        self.sock.send("0");
        self.sock.recv(1024);
        
        

    def network(self):
        #keys = pygame.key.get_pressed();
        #self.sock.send(repr((0, keys[pygame.K_UP], keys[pygame.K_DOWN], keys[pygame.K_LEFT], keys[pygame.K_RIGHT], keys[pygame.K_SPACE])));
        pos = pygame.mouse.get_pos();
        x = pos[0];
        y = pos[1];
        mshoot = pygame.mouse.get_pressed()[0];
        self.sock.send(repr((1, x, y, mshoot)))
        data = self.sock.recv(1024);
        if not data: return True;
        data = eval(data);
        # ([((50, 50), (0, 0), 0)], [])
        #print data;
        #time.sleep(2);
        self.ships = data[0];
        for shot in data[1]:
            pos = Vector(shot[0][0], shot[0][1]);
            speed = Vector(shot[1][0], shot[1][1]);
            self.shots.append(Shot(pos, speed));
        return False;

    def draw_ship(self, pos, angle):
        self.pntShip[0].rot_to(angle-(pi/2));
        self.pntShip[1].rot_to(angle+(pi/2));
        self.pntShip[2].rot_to(angle);

        pygame.draw.aalines(self.screen, (255, 0, 0), 1, (
            (pos.plus(self.pntShip[0]).get()),
            (pos.plus(self.pntShip[1]).get()),
            (pos.plus(self.pntShip[2]).get())
            ));

    def debug(self):
        while True:
            #print self.ships;
            time.sleep(2);
开发者ID:strykejern,项目名称:strykejern-pythonGame,代码行数:96,代码来源:game_client.py

示例6: Timer

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
    start = time.time()
    print "ceci est un  : ",lmi.p((u'ceci',u'est',u'un'))
    print "It tooks ",time.time()-start,"s"
    start = time.time()
    print "Voici une phrase plutôt simple",lmi.p((u'Voici',u'une',u'phrase',u'plutôt',u'simple'))
    print "It tooks ",time.time()-start,"s"
    start = time.time()
    print "Phrase formé mal avec qwetrqq inconnu mot",lmi.p((u'Phrase',u'formé',u'mal',u'avec',u'qwetrqq',u'inconnu',u'mot'))
    print "It tooks ",time.time()-start,"s"

#    sys.exit(0)

    tmps = 0
    tmpss = 0
    t = Timer(ngram.len(2))
    t.start()
    # need 3-grams for this
    for i, ng in enumerate(ngram.getgrams(2)):
        tmps = 0
        for j, nng in enumerate(ngram.contains(tuple(list(ng)+[""]),(0,-1))):
            tmps += lmi.p(nng)

        tmpss += tmps
        update = t.update(1)
        if update:
            sys.stderr.write("time remaining : "+seconds_to_string(update)+"\n")
        print i,tmpss
        print "tmp %i : %f" % (i,tmpss/(0.+i+1))

    print "final : ",tmpss/(0.+ngram.len(2))
开发者ID:bouthilx,项目名称:toiledemots,代码行数:32,代码来源:KneserNey.py

示例7: __init__

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class Ship:
    def __init__(self, x=50, y=50):
        self.pos = Vector(x, y);
        self.speed = Vector();
        self.accel = Vector();
        self.angle = 0;
        self.tmpAngle = 0;
        self.canShoot = 1;
        self.shootLimiter = Timer(2);
        self.keyb = 1;

        self.keys = {
            "up":0,
            "down":0,
            "left":0,
            "right":0,
            "shoot":0
            };
        self.mouse = Vector(0,0);
        self.mShoot = 0;
        
        self.accel.x = 1;
        self.points = (
            Vector(0,-10),
            Vector(0,10),
            Vector(30,0)
            );

    def update(self, shoot_function, index):
        if self.canShoot:
            self.shootLimiter.reset();
        else:
            self.canShoot = self.shootLimiter.update();
        if self.keyb:
            if self.keys["up"]:       self.accel.y = -0.5;
            elif self.keys["down"]:   self.accel.y = 0.5;
            else:
                self.accel.y = 0;
                self.speed.y *= 0.98;
            if self.keys["left"]:     self.accel.x = -0.5;
            elif self.keys["right"]:  self.accel.x = 0.5;
            else:
                self.accel.x = 0;
                self.speed.x *= 0.98;
            if self.keys["shoot"] and self.canShoot:
                self.canShoot = 0;
                self.shootLimiter.reset();
                shoot_function(index);
        else:
            if self.accel.hyp() < 1: self.accel = Vector(0,1);
            self.accel.rot_to(self.mouse.minus(self.pos).angle());
            if self.mshoot and self.canShoot:
                self.canShoot = 0;
                self.shootLimiter.reset();
                shoot_function(index);

        if not self.accel.isNull(): self.angle = self.accel.angle();
        self.speed.add(self.accel);
        if not self.speed.isNull():
            hyp = self.speed.hyp();
            if hyp > 10:
                self.speed.set_length(10);
            
        self.pos.add(self.speed);
        bounce = self.pos.moveWithinBounds(Vector(800, 600));
        if bounce:
            if bounce   == 1: self.speed.x = -self.speed.x;
            elif bounce == 2: self.speed.y = -self.speed.y;

    def hit(self):
        pass;

    def set_keys(self, up, down, left, right, shoot):
        self.keyb = 1;
        self.keys["up"] = up;
        self.keys["down"] = down;
        self.keys["left"] = left;
        self.keys["right"] = right;
        self.keys["shoot"] = shoot;

    def set_mouse(self, mpos, mshoot):
        self.keyb = 0;
        self.mouse.x = mpos[0];
        self.mouse.y = mpos[1];
        self.mshoot = mshoot;
    
    def net_data(self):
        # [0] = ( posX, posY )
        # [1] = ( speedX, speedY )
        # [2] = angle
        # ( ( posX, posY ), ( speedX, speedY ), angle )
        return (self.pos.get(1), self.speed.get(1), int(self.angle * 100));

    @staticmethod
    def collide(ships, shots, explosions=0):
        for i in ships:
            for shot in shots:
                if ships[i].pos.dist_to(shot.pos) < 10:
                    ships[i].hit();

#.........这里部分代码省略.........
开发者ID:strykejern,项目名称:strykejern-pythonGame,代码行数:103,代码来源:ship.py

示例8: __init__

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class game_server:
    def __init__(self):
        self.connections = dict();
        self.ships = dict();
        self.shots = list();
        self.sendShots = dict();
        self.queueShots = dict();
        self.explosions = dict();
        self.fpsLimit = Timer(30);
        self.data = ();
        self.run = dict();
        self.sock_init();

        self.debugVar = None;
        thread.start_new_thread(self.debug, ());

    def start(self):
        thread.start_new_thread(self.listen, ());
        while True:
            if self.fpsLimit.update() and len(self.ships):

                for i in self.run:
                    self.run[i] = 1;
                Ship.updates(self.ships, self.shoot);
                Ship.collide(self.ships, self.shots, self.explosions);
                Shot.updates(self.shots);
                self.data = (Ship.to_data(self.ships));
            else:
                time.sleep(0.0005);

    def shoot(self, index):
        pos = self.ships[index].pos.copy();
        speed = Vector(1,1);
        speed.rot_to(self.ships[index].angle);
        self.shots.append(Shot(pos, speed, index));
        shotData = self.shots[-1].to_data();
        for i in self.queueShots:
            self.queueShots[i].append(shotData);

    def communicate(self, index):
        print "Connected to ", index;

        conn = self.connections[index];
        data = conn.recv(256);
        if not data: return;
        data = eval(data);

        time.sleep(1);

        conn.send(repr(((self.data), ())));

        while True:
            if self.run[index]:
                self.run[index] = 0;
                conn = self.connections[index];
                data = None;
                try: data = conn.recv(256);
                except: break;
                if not data: break;
                data = eval(data);
                if not data[0]: self.ships[index].set_keys(data[1], data[2], data[3], data[4], data[5]);
                else: self.ships[index].set_mouse((data[1], data[2]), data[3]);

                shots = Shot.net_pack(self.queueShots[index]);
                self.queueShots[index] = list();
                #shots = list();
                #while len(self.queueShots) > 1:
                #    shots.append(self.queueShots.pop());
                conn.send(repr((self.data, shots)));
        print "Client disconnected";
        self.connections[index].close();
        self.remove_player(index);

    def listen(self):
        while True:
            conn, addr              = self.sock.accept();
            self.connections[addr]  = conn;
            self.ships[addr]        = Ship();
            self.queueShots[addr]   = list();
            self.run[addr]          = 0;
            thread.start_new_thread(self.communicate, (addr,));

    def sock_init(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        self.sock.bind(('', 1234));
        self.sock.listen(2);

    def remove_player(self, index):
        del self.connections[index];
        del self.ships[index];
        del self.run[index];
        del self.queueShots[index];

    def debug(self):
        while True:
            #print self.debugVar;
            time.sleep(2);
开发者ID:strykejern,项目名称:strykejern-pythonGame,代码行数:99,代码来源:game_server.py

示例9: Cursor

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class Cursor(object):
    def __init__(self, screen, rad):
        self.init_base_vars(screen, rad)
        self.init_custom_vars()
        self.init_game_logic()

    def init_base_vars(self, screen, rad):
        self.RAD = rad
        self.OUTLINE_THK = 5
        self.BASE_COLOR = 240,240,140
        self.OUTLINE_COLOR = 20,20,20
        self.pos = np.array([0,0])
        self.screen = screen
        self.color = self.BASE_COLOR
        self.screen_mid = np.array([0.5*self.screen.get_width(),
                                    0.5*self.screen.get_height()])
        self.pos_lims = ((self.screen_mid[0]-self.screen_mid[0]+self.RAD
                          +self.OUTLINE_THK),
                         (self.screen_mid[0]+self.screen_mid[0]-self.RAD
                          -self.OUTLINE_THK),
                         self.RAD+self.OUTLINE_THK,
                         2*self.screen_mid[1]-self.RAD-self.OUTLINE_THK)

    def init_custom_vars(self):
        self.WARN_COLOR = 240,140,140
        self.WARN_TIME = .3
        self.warn_timer = Timer(self.WARN_TIME)
        self.warn_bool = False

    def init_game_logic(self):
        self.has_left = False
        self.start_ready = False
        self.in_start = False

    def update(self, new_pos): 
        self.pos[:] = new_pos[0], new_pos[1]
        self.trap()

    def update_warn(self, time_passed, target_status):
        if target_status:
            self.warn_bool = True
        if self.warn_bool:
            self.color = self.WARN_COLOR
            self.warn_timer.update(time_passed)
            if self.warn_timer.time_limit_hit:
                self.warn_timer.reset()
                self.warn_bool = False
                self.color = self.BASE_COLOR

    def trap(self):
        if self.pos[0] < self.pos_lims[0]:
            self.pos[0] = self.pos_lims[0]
        elif self.pos[0] > self.pos_lims[1]:
            self.pos[0] = self.pos_lims[1]
        if self.pos[1] < self.pos_lims[2]:
            self.pos[1] = self.pos_lims[2]
        elif self.pos[1] > self.pos_lims[3]:
            self.pos[1] = self.pos_lims[3]

    def check_within_dist(self, pos, dist):
        if (np.sqrt((self.pos[0]-pos[0])**2
                   +(self.pos[1]-pos[1])**2)
                < (dist)):
            return True
        else:
            return False


    def draw(self): 
        for idx in range(self.OUTLINE_THK):
            pygame.gfxdraw.aacircle(self.screen,
                                self.pos[0],
                                self.pos[1],
                                self.RAD+idx,
                                self.color)
            pygame.gfxdraw.aacircle(self.screen,
                                self.pos[0]+1,
                                self.pos[1],
                                self.RAD+idx,
                                self.color)
            pygame.gfxdraw.aacircle(self.screen,
                                self.pos[0],
                                self.pos[1]+1,
                                self.RAD+idx,
                                self.color)
开发者ID:efunn,项目名称:hemo-control,代码行数:87,代码来源:cursor.py

示例10: Mees

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class Mees(object): # peamees
    global SCREEN_WIDTH, SCREEN_HEIGHT  # ekraani laius ja pikkus
    def __init__(self):

        #pygame.mixer.init(frequency=22050, size=-16, channels=4)
        self.saund = pygame.mixer.Sound("Sounds/singleshot.wav")
        self.saund.set_volume(0.2)
        self.chan = pygame.mixer.find_channel()

        self.saund2 = pygame.mixer.Sound("Sounds/teleport2.wav")
        self.saund2.set_volume(0.8)
        self.chan2 = pygame.mixer.find_channel()

        self.saund3 = pygame.mixer.Sound("Sounds/pickup.wav")
        self.saund3.set_volume(0.8)
        self.chan3 = pygame.mixer.find_channel()

        self.saund4 = pygame.mixer.Sound("Sounds/slurp.wav")
        self.saund4.set_volume(1)
        self.chan4 = pygame.mixer.find_channel()


        self.lives = 7 # mitu elu mehel
        self.rect = Rect(30,SCREEN_HEIGHT-100,10,10) # ta kast
        self.image = pygame.transform.scale((pygame.image.load("Pics/Kappa.png").convert_alpha()), (30,30))
        self.imageDisco = pygame.transform.scale((pygame.image.load("Pics/discokappa.png").convert_alpha()), (30,30))
        self.image2 = pygame.image.load('Pics/Untitled.png').convert_alpha()
        self.image2Rect = self.image2.get_rect()
        self.newRect = self.image.get_rect()
        self.rect.w = self.newRect[2]
        self.rect.h = self.newRect[3]
        self.speed = 0.8 # kiirus

        self.bullets = [] # valjalastud kuulid

        self.bulletCount = 20 # kuulide arv
        
        self.font=pygame.font.Font(None,30)

        #voimalikud relvad
        self.relvad = {
            "handgun" :
                { "dmg" : 1, # palju relv dmg teeb
                  "speed" : 2, # kui kiirelt kuul lendabs
                  "hoida" : 0, # kas automaat
                  "bullets" : 12, # palju kuule
                  "pide" : 12, # palju pide hoiab
                  "kokku" : -1 # palju kokku kuule
                },
            "machinegun" :
                { "dmg" : 1,
                  "speed" : 4,
                  "hoida" : 1,
                  "bullets" : 50,
                  "pide" : 50,
                  "kokku" : 300,
                  "vahe" : 0.2 # kuulide laskmis vahe ajaliselt automaatselt
                },
            "pump" :
                { "dmg" : 1,
                  "speed" : 2,
                  "hoida" : 0,
                  "bullets" : 8,
                  "pide" : 8,
                  "kokku" : 72,
               }
        }
        self.potid = {
            0 :
                {
                    "heals" : 2,
                     #"img" : "Pics/2HPpot.png"
                },
            1 :
                {
                    "heals" : 5
                    #"img" : "Pics/5HPpot.png"
                },
            2 :
                {
                    "speed" : 1,
                    "time" : 20
                }
        }

        self.relv = "handgun" # mis relv hetkel

        self.relvakogu = ["handgun","machinegun"]
        self.potikogu = []

        self.shootTimer = Timer(1)
        self.speedTimer = Timer(0)
        self.shootTimer.run()
        self.koos = []
        self.saiJuurde = 0
        self.dead = 0
        self.ulti = 5
    def update_logic(self):
        self.shootTimer.update()
        self.speedTimer.update()
#.........这里部分代码省略.........
开发者ID:Kaspar94,项目名称:SpaceKappaShooter,代码行数:103,代码来源:mees.py

示例11: Player

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class Player (Sprite):

	def __init__ (self, x, y):
		
		Sprite.__init__(self, x, y, 'princess')
		
		self.grid_x = x
		self.grid_y = y

		self.light = Sprite(x, y, 'light')
		self.light.offset_x = -96
		self.light.offset_y = -106
		self.light.play('default', loop=True)
		
		# walk timer
		self.timer = None
		
		# default orientation
		self.ori = 'up'
		
		# animations		
		self.add_anim('walk_up', common.WALK_MOVEMENT_TIME, range(0, 9))
		self.add_anim('walk_left', common.WALK_MOVEMENT_TIME, range(9, 18))
		self.add_anim('walk_down', common.WALK_MOVEMENT_TIME, range(18, 27))
		self.add_anim('walk_right', common.WALK_MOVEMENT_TIME, range(27, 36))
	
	@property
	def grid_x (self):		
		return int(self.x / common.TILE_SIZE)
		
	@property
	def grid_y (self):		
		return int(self.y / common.TILE_SIZE)
	
	@grid_x.setter
	def grid_x (self, x):		
		self.x = x * common.TILE_SIZE
		
	@grid_y.setter
	def grid_y (self, y):		
		self.y = y * common.TILE_SIZE
	
	def walk (self, x, y):
		
		assert(x == 1 or x == -1 or x == 0)
		assert(y == 1 or y == -1 or y == 0)
		
		if x == 0 and y == 0:
			return
		
		elif self.timer is None or self.timer.is_complete():
		
			x *= common.TILE_SIZE
			y *= common.TILE_SIZE
			
			self._prev_x = self.x
			self._prev_y = self.y
			
			self._next_x = self.x + x
			self._next_y = self.y + y
			
			self._move_x = x
			self._move_y = y
			
			if x < 0:
				self.ori = 'left'
			elif x > 0:
				self.ori = 'right'
			elif y > 0:
				self.ori = 'down'
			else:
				self.ori = 'up'

			self.play('walk_' + self.ori)
			self.timer = Timer(common.WALK_MOVEMENT_TIME)
	
	def update (self, time):
		
		Sprite.update(self, time)		
		self.light.update(time)
		
		if self.timer is not None and not self.timer.is_complete():

			self.timer.update(time)
			
			self.x = self._prev_x + self.timer.percent_done * self._move_x
			self.y = self._prev_y + self.timer.percent_done * self._move_y

		# adjust player light position
		self.light.x = self.x
		self.light.y = self.y
开发者ID:thiagojobson,项目名称:Maze-Of-Kindred,代码行数:93,代码来源:player.py

示例12: MazeOfKindred

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]

#.........这里部分代码省略.........
			self.fog.blit(l.image, (l.vx, l.vy))
		
		player_light = self.player.light
		self.fog.blit(player_light.image, (player_light.vx, player_light.vy))

		self.screen.blit(surface, (x, y))
		
		if common.ENABLE_FOG:
			self.screen.blit(self.fog, (x, y))
		
		if not self.fade_timer.is_complete():
		
			alpha = 255 - self.fade_timer.percent_done * 255 
			alpha = int(alpha)
			
			fog = pygame.Surface((common.GAME_WIDTH, common.GAME_HEIGHT), pygame.SRCALPHA)
			pygame.draw.rect(fog, (0, 0, 0, alpha), (0, 0, common.GAME_WIDTH, common.GAME_HEIGHT))
			self.screen.blit(fog, (0, 0))
			
		elif self.is_at_door():
		
			fog = pygame.Surface((common.GAME_WIDTH, common.GAME_HEIGHT), pygame.SRCALPHA)
			pygame.draw.rect(fog, (0, 0, 0, 170), (0, 0, common.GAME_WIDTH, common.GAME_HEIGHT))
			self.screen.blit(fog, (0, 0))
			
			self.screen.blit(self.restart.image, (self.restart.vx, self.restart.vy))

		elif self.enable_sound:	
			self.screen.blit(self.sound.image, (self.sound.vx, self.sound.vy))
			
		else:
			self.screen.blit(self.nosound.image, (self.nosound.vx, self.nosound.vy))
		
		pygame.display.update()
		
	def main (self):
		
			clock = pygame.time.Clock()
			
			pygame.key.set_repeat(1, 100)
			
			x = y = 0
			
			while True:
				
				time = clock.tick(60)
				
				self.fade_timer.update(time)
				
				for event in pygame.event.get():
					
					if event.type == pygame.QUIT:
						pygame.quit()
						return
						
					elif event.type == pygame.MOUSEBUTTONUP:
						
						if self.sound.rect.collidepoint(event.pos):
							
							if self.is_at_door(): # clicking on restart button
								self.create()
								
							else: # clicking on enable/disable sound
								self.enable_sound = not self.enable_sound
							
						if self.enable_sound:
开发者ID:thiagojobson,项目名称:Maze-Of-Kindred,代码行数:70,代码来源:main.py

示例13: Target

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class Target(object):

    def __init__(self, screen, pos, zero_pos, rad,
                 cursor_rad, success_time, min_time):
        # constants
        self.HIGHLIGHT_COLOR = 20,255,20
        self.HIGHLIGHT_COLOR_FAIL = 255,20,20
        self.CURRENT_COLOR_ACTIVE = 40,180,40
        self.CURRENT_COLOR = 40,180,40
        self.NEXT_COLOR = 40,80,40
        self.NEXT_NEXT_COLOR = 40,50,40
        self.BG_COLOR = 40,40,40
        self.DEFAULT_COLOR = self.CURRENT_COLOR
        self.DEFAULT_OUTLINE_COLOR = 20,20,20

        # display
        self.screen = screen
        self.color = self.DEFAULT_COLOR
        self.outline_color = self.DEFAULT_OUTLINE_COLOR

        # game logic
        self.pos = (zero_pos[0]+pos[0],
                    zero_pos[1]+pos[1])
        self.outline_rad = 2
        self.rad = rad
        self.cursor_rad = cursor_rad
        self.success_timer = Timer(success_time)
        self.target_timer = Timer(success_time)
        self.active_timer = Timer(min_time)
        self.highlight = False
        self.wait_prev_target = True
        self.success = True
        self.complete_success = False

    def update_active(self, time_passed):
        self.active_timer.update(time_passed)

    def update(self, time_passed, cursor_pos):
        if self.prev_target == None:
            self.wait_prev_target = False
        elif not(self.prev_target.active_timer.time_limit_hit):
            self.wait_prev_target = True
        else:
            self.wait_prev_target = False
        if not(self.wait_prev_target):
            self.update_active(time_passed)

        if (self.check_in_rad(cursor_pos)
                and not(self.wait_prev_target)):
            self.highlight = True

        if self.highlight:
            self.target_timer.update(time_passed)
            if not self.check_in_rad(cursor_pos):
                self.success = False

        if self.target_timer.time_limit_hit:
            if self.success:
                self.complete_success = True
            return True
        else:
            return False

    def check_in_rad(self, cursor_pos):
        if (np.sqrt((self.pos[0]-cursor_pos[0])**2
                   +(self.pos[1]-cursor_pos[1])**2)
                < (self.cursor_rad-self.rad-1)):
            return True
        else:
            return False

    def draw(self, draw_type):
        if draw_type == 'next_next':
            self.color = self.NEXT_NEXT_COLOR
        elif draw_type == 'next':
            self.color = self.NEXT_COLOR
        elif draw_type == 'current':
            if self.highlight:
                if self.success:
                    self.color = self.HIGHLIGHT_COLOR
                else:
                    self.color = self.HIGHLIGHT_COLOR_FAIL
            elif self.wait_prev_target:
                self.color = self.CURRENT_COLOR
            else:
                self.color = self.CURRENT_COLOR_ACTIVE
        gg.draw_filled_aacircle(self.screen, self.rad, self.color,
                                self.pos[0], self.pos[1])
开发者ID:efunn,项目名称:hemo-control,代码行数:90,代码来源:target.py

示例14: Game

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import update [as 别名]
class Game(Menu): # Need draw_text()

  def __init__(self, start=1):
    if start:
      pygame.init()

      environ['SDL_VIDEO_CENTERED'] = '1'
      self.scr_size = (800, 600)
      self.screen = pygame.display.set_mode(self.scr_size)
      pygame.display.set_caption('Chain Pain - By Jach')
    
    while 1:
      cont = self.load_menu()
      if cont == 'play':
        self.load_crap()
        self.play()
        break
      elif cont == 'time':
        self.high_time()
      elif cont == 'man':
        self.instructions()
      else:
        exit()

  def load_menu(self):
    m = Menu(self.screen)
    return m.load()

  def high_time(self): # Display highest time
    self.screen.fill( (0,0,0) ) # Kill menu
    best_time = BestTime(self.screen)

  def instructions(self):
    self.screen.fill( (0,0,0) ) # Kill menu
    manual = Man(self.screen)

  def play(self):

    self.screen.fill( (0,0,0) )
    self.clock = pygame.time.Clock()
    self.time_passed = 0
    self.manlinesses = 2 # Lives
    self.masters_allowed = 0 # To update
    self.time_since_whip = 0
    self.master_chosen = 0
    while 1:
      self.secs = self.clock.tick(FPS) / 1000.0
      self.time_passed += self.secs

      self.events()
      self.update_crap() # Updates, no more no less
      self.draw_crap() # Erases too
      self.collision_crap()

  def load_crap(self):
    # Loads all images, makes objects if applicable, adds any images and
    # rects to all_sprites{}
    # Now also loads all sounds at the very top!

    self.sounds = {'gasp' : self.load_sound('gasp.ogg'),\
        'ugh' : self.load_sound('ugh.ogg'),\
        'ow' : self.load_sound('ow.ogg'),\
        'ahh' : self.load_sound('ahh.ogg'),\
        'cry' : self.load_sound('cry.ogg'),\
        'whip' : self.load_sound('whip.ogg'),\
        'music' : self.load_sound('music1.ogg'),\
        'haha' : self.load_sound('haha.ogg')}
    self.sounds['music'].play(-1)

    self.all_sprites = {}

    self.bg_img = pygame.image.load(\
        path.join('data','background.png')).convert_alpha()

    playerimg=pygame.image.load(path.join('data', 'player.png')).convert_alpha()
    player_pos = [370,384] # Does not move?
    self.all_sprites['player'] = [playerimg,player_pos]

    self.master1 = Master('left', self.screen)
    self.master2 = Master('right', self.screen)
    self.all_sprites['master1'] = [self.master1.image, self.master1.rect]
    self.all_sprites['master2'] = [self.master2.image, self.master2.rect]

    big_bar = pygame.image.load(path.join('data','big_bar.png')).convert_alpha()
    big_bar_pos = (400-250, 500) # 500 bottom? 10 top? Edit background for bot
    self.all_sprites['big_bar'] = [big_bar, big_bar_pos]

    self.bar = Bar(self.sounds) # Moving bar
    self.all_sprites['moving_bar'] = [self.bar.image, self.bar.rect]

    self.timer = Timer() #Clock so player knows how long they've gone
    self.all_sprites['timer'] = [self.timer.image, self.timer.rect]

    manliness = pygame.image.load(\
        path.join('data','manliness.png')).convert_alpha()
    manliness1pos = (65, 1)
    manliness2pos = (100, 1)
    self.all_sprites['man1'] = [manliness, manliness1pos]
    self.all_sprites['man2'] = [manliness, manliness2pos]

#.........这里部分代码省略.........
开发者ID:Jach,项目名称:ludum_dare_entries,代码行数:103,代码来源:main.py


注:本文中的timer.Timer.update方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。