示例#1
0
class Game:
    def __init__(self, scr, loop):

        self.scr = scr

        from block import Block
        self.block = Block(scr)

        from message import Messages
        self.msg = Messages(self.scr)

        self.loop = loop

        self.FPS = 60

        self.block(self, self.loop)

    def update(self):

        lasttime = time.time()

        self.block.update()

        self.FPS = 1.0 / (time.time() - lasttime)

    def draw(self):

        scr = self.scr
        scr.fill((35, 35, 35))

        self.block.draw()
        self.msg.message(round(self.FPS, 1), (10, 10))
示例#2
0
文件: run.py 项目: xhalo32/advpy
	def loop( self ):

		clk = p.time.Clock(  )

		while self.active:
			lasttime = time.time(  )

			self.events = p.event.get(  )

			self.eventListener(  )
			self.update(  )
			self.draw(  )

			FPS = 0
			for x in self.FPSlist:
				FPS += x

			Messages.message( self.scr, round( FPS / len( self.FPSlist ), 1 ), ( 10, 10 ), p.Color( 'magenta' ) )

			p.display.update(  )

			now = time.time(  )
			self.FPSlist.append( round( 1.0 / ( now - lasttime ), 0 ) )
			if len( self.FPSlist ) > 100: del self.FPSlist[ 0 ]

			clk.tick( self.WFPS )
示例#3
0
文件: game.py 项目: xhalo32/advpy
class Game:

	def __init__( self, scr, loop ):

		self.scr = scr

		from block import Block
		self.block = Block( scr )

		from message import Messages
		self.msg = Messages( self.scr )

		self.loop = loop

		self.FPS = 60

		self.block( self, self.loop )

	def update( self ):

		lasttime = time.time(  )

		self.block.update(  )

		self.FPS = 1.0 / ( time.time(  ) - lasttime )

	def draw( self ):

		scr = self.scr
		scr.fill( ( 35, 35, 35 ) )

		self.block.draw(  )
		self.msg.message( round( self.FPS, 1 ), ( 10, 10 ) )
示例#4
0
文件: fps.py 项目: xhalo32/advpy
def printfps( self ):

	if self.timer % int( self.loopfps / len( self.loopfpslist ) ) == 0:
		loopfps = 0
		for i in self.loopfpslist:
			loopfps += i	
		self.loopfps = loopfps

	try: Messages.message( self.scr, round( self.loopfps / len( self.loopfpslist ), 1 ), [ 10, 100 ], ( 200, 0, 0 ) )
	except: pass
示例#5
0
文件: fps.py 项目: xhalo32/advpy
def printfps(self):

    if self.timer % int(self.loopfps / len(self.loopfpslist)) == 0:
        loopfps = 0
        for i in self.loopfpslist:
            loopfps += i
        self.loopfps = loopfps

    try:
        Messages.message(self.scr,
                         round(self.loopfps / len(self.loopfpslist), 1),
                         [10, 100], (200, 0, 0))
    except:
        pass
示例#6
0
    def __init__(self, scr, loop):

        self.scr = scr

        from block import Block
        self.block = Block(scr)

        from message import Messages
        self.msg = Messages(self.scr)

        self.loop = loop

        self.FPS = 60

        self.block(self, self.loop)
示例#7
0
文件: main.py 项目: davorgraj/Bmail
    def post(self):
        receiver_mail = self.request.get("email")
        receiver = Users.query(Users.email == receiver_mail).get()

        if not receiver:
            params = {
                "notification": "Uporabnik " + receiver_mail + " ne obstaja.",
                "alert_type": "danger"
            }
            return self.render_template("bmail.html", params=params)

        if receiver_mail == self.current_user().email:
            params = {
                "notification": "Sebi ne morete poslati sporočila !!!",
                "alert_type": "danger"
            }
            return self.render_template("bmail.html", params=params)

        message = self.request.get("message")

        Messages(message=message,
                 sender=self.current_user().key,
                 receiver=receiver.key).put()

        params = {
            "notification": "Uspešno poslano za " + receiver_mail,
            "alert_type": "success"
        }
        return self.render_template("bmail.html", params=params)
示例#8
0
文件: fps.py 项目: xhalo32/advpy
def printfps(self):

    if self.timer % 60 == 0:
        loopfps = 0
        for i in self.loopfpslist:
            loopfps += i
        self.loopfps = loopfps

    try:
        Messages.message(self.s, round(self.loopfps / len(self.loopfpslist), 1), [10, 30], (200, 0, 0))
    except:
        pass

    try:
        Messages.message(self.s, round(self.updatefps / len(self.updatefpslist), 1), [10, 10], (0, 255, 0))
    except:
        pass
示例#9
0
文件: main.py 项目: davorgraj/Bmail
    def get(self):
        if self.current_user().key == Messages.receiver:
            messages = Messages.query(
                Messages.receiver_delete == False,
                Messages.receiver == self.current_user().key).fetch()

        params = {"messages": messages}
        return self.render_template("received_messages.html", params=params)
示例#10
0
文件: main.py 项目: davorgraj/Bmail
    def post(self, message_id):
        if Messages.receiver == self.current_user().key:
            message_delete = Messages.get_by_id(int(message_id))
            message_delete.key.delete()
            message_delete.receiver_delete = True
            message_delete.put()

        return self.redirect_to("home")
示例#11
0
文件: main.py 项目: davorgraj/Bmail
    def get(self):
        deleted_messages = Messages.query(
            ndb.OR(
                Messages.sender == self.current_user().key,
                Messages.receiver == self.current_user().key,
            )).fetch()

        params = {"deleted_messages": deleted_messages}
        return self.render_template("deleted_messages.html", params=params)
示例#12
0
文件: main.py 项目: xhalo32/advpy
	def draw( self ):

		self.s.fill( ( 0, 42, 32 ) )

		for e in [ e for e in self.entitylist if e != self.player ]:
			e.type.draw(  )

		self.player.type.draw(  )
		
		Messages.message( self.s, len( self.entitylist ), [ 10, 50 ], ( 200, 200, 0 ) )

		self.loopnow = time.time(  )
		fps.calcfps( self )
		fps.printfps( self )
		self.looplast = time.time(  )

		with self.screenlock:
			p.display.flip(  )
示例#13
0
    def draw(self):

        self.s.fill((0, 42, 32))

        for e in [e for e in self.entitylist if e != self.player]:
            e.type.draw()

        self.player.type.draw()

        Messages.message(self.s, len(self.entitylist), [10, 50], (200, 200, 0))

        self.loopnow = time.time()
        fps.calcfps(self)
        fps.printfps(self)
        self.looplast = time.time()

        with self.screenlock:
            p.display.flip()
示例#14
0
    def __init__(self):

        self.blocklist = []
        self.scr = pg.display.set_mode((1080, 720), pg.RESIZABLE)
        self.clock = pg.time.Clock()

        self.active = False
        self.designated_speed = 0
        self.designated_timing = 60
        self.not100 = False
        self.FPS = 40

        self.center = self.scr.get_width() / 2, self.scr.get_height() / 2

        self.sliders()
        self.effect = Effect(self)
        self.msg = Messages(self.scr)

        self.reset()
示例#15
0
文件: fps.py 项目: xhalo32/advpy
def printfps(self):

    if self.timer % 60 == 0:
        loopfps = 0
        for i in self.loopfpslist:
            loopfps += i
        self.loopfps = loopfps

    try:
        Messages.message(self.s, round(self.loopfps / len(self.loopfpslist),
                                       1), [10, 30], (200, 0, 0))
    except:
        pass

    try:
        Messages.message(self.s,
                         round(self.updatefps / len(self.updatefpslist), 1),
                         [10, 10], (0, 255, 0))
    except:
        pass
示例#16
0
    def __init__(self, scr, spd, color, game):

        self.scr = scr
        self.w = 100
        self.h = 50
        self.x = random.randint(0, self.scr.get_width() - self.w)
        self.y = -self.h
        self.center = [self.x + self.w / 2, self.y + self.h / 2]
        self.speed = spd
        self.color = color

        self.randomness = 10
        self.terminate = self.fail = False

        self.calc = [random.randint(0, 4), random.randint(0, 5)]
        self.ans = self.calc[0] + self.calc[1]
        self.displayCalc = str(self.calc[0]) + " + " + str(self.calc[1])

        self.msg = Messages(self.scr)
        self.game = game
示例#17
0
文件: slider.py 项目: xhalo32/advpy
 def __init__(self,
              scr,
              colour = (255, 255, 255),
              secondary_colour = (200, 200, 200),
              pos_size = [100, 100, 100, 20],
              steps = 10):
     
     self.scr = scr
     self.pos_size = pos_size
     self.steps = steps
     self.color = colour
     self.secondary_color = secondary_colour
     self.dragging = False
     self.sliderpos = math.floor((steps)/2.0)
     
     self.steplen = pos_size[2] / float(steps)
     self.center = pos_size[0] + pos_size[2] / 2, \
                   pos_size[1] + pos_size[3] / 2
     
     self.button = self.center[0]
     
     self.msg = Messages(self.scr)
示例#18
0
文件: main.py 项目: davorgraj/Bmail
    def get(self):
        if not self.current_user():
            return self.redirect_to("login")

        messages = Messages.query(
            ndb.OR(
                Messages.sender == self.current_user().key,
                Messages.receiver == self.current_user().key,
            )).fetch()

        params = {"messages": messages}

        return self.render_template("bmail.html", params=params)
示例#19
0
文件: game.py 项目: xhalo32/advpy
	def __init__( self, scr, loop ):

		self.scr = scr

		from block import Block
		self.block = Block( scr )

		from message import Messages
		self.msg = Messages( self.scr )

		self.loop = loop

		self.FPS = 60

		self.block( self, self.loop )
示例#20
0
文件: world.py 项目: xhalo32/advpy
    def draw(self):

        Stars.draw()

        self.s1.draw()

        self.effectC.draw()
        self.projectile.draw()
        self.enemyC.draw()
        self.player.draw()

        Messages.message(self.scr, str(self.wsx) + " " + str(self.wsy), (10, 40), p.Color("magenta"))
        Messages.message(self.scr, len(self.projectile.projectiles), (10, 70), p.Color("magenta"))
        Messages.message(self.scr, self.enemyC.totaldied, (10, 100), p.Color("green"))
示例#21
0
文件: block.py 项目: xhalo32/advpy
	def __init__(self, scr, spd, color, game):
		
		self.scr = scr
		self.w = 100
		self.h = 50
		self.x = random.randint(0, self.scr.get_width() - self.w)
		self.y = -self.h
		self.center = [self.x + self.w/2, self.y + self.h/2]
		self.speed = spd
		self.color = color
		
		self.randomness = 10
		self.terminate = self.fail = False
		
		self.calc = [random.randint(0, 4), random.randint(0, 5)]
		self.ans = self.calc[0] + self.calc[1]
		self.displayCalc = str(self.calc[0]) + " + " + str(self.calc[1])
		
		self.msg = Messages(self.scr)
		self.game = game
示例#22
0
    def draw(self):

        Stars.draw()

        self.s1.draw()

        self.effectC.draw()
        self.projectile.draw()
        self.enemyC.draw()
        self.player.draw()

        Messages.message(self.scr,
                         str(self.wsx) + " " + str(self.wsy), (10, 40),
                         p.Color('magenta'))
        Messages.message(self.scr, len(self.projectile.projectiles), (10, 70),
                         p.Color('magenta'))
        Messages.message(self.scr, self.enemyC.totaldied, (10, 100),
                         p.Color('green'))
示例#23
0
 def messages(self, messages):
     return Messages(self.message_class, self, messages)
示例#24
0
    def belief_propogation_log(self,
                               gold_tags,
                               lang,
                               sentLen,
                               batch_lstm_feats,
                               test=False):

        # fwd messages, then bwd messages for each tag => ! O(n^2)

        # start_time = time.time()

        threshold = 0.05
        maxIters = 50
        batch_size = len(batch_lstm_feats)
        if self.model_type == "specific":
            langIdx = self.langs.index(lang)

        # Initialize factor graph, add vars and factors
        print("Creating Factor Graph...")
        graph = FactorGraph(sentLen, batch_size, self.gpu)

        # Add variables to graph
        for tag in self.uniqueTags:
            for t in range(sentLen):
                label = None
                graph.addVariable(tag, label, t)

        if not self.no_pairwise:
            # Add pairwise factors to graph
            kind = "pair"
            for tag1 in self.uniqueTags:
                for tag2 in self.uniqueTags:
                    if tag1 != tag2 and tag1.idx < tag2.idx:
                        for t in range(sentLen):
                            var1 = graph.getVarByTimestepnTag(t, tag1.idx)
                            var2 = graph.getVarByTimestepnTag(t, tag2.idx)
                            graph.addFactor(kind, var1, var2)

            # Retrieve pairwise weights
            pairwise_weights_np = []
            for i in range(len(self.pairs)):
                pairwise_weights_np.append(
                    self.pairwise_weights[i].cpu().data.numpy())

            if self.model_type == "specific":
                for i in range(len(self.pairs)):
                    pairwise_weights_np[i] = utils.logSumExp(
                        pairwise_weights_np[i], self.lang_pairwise_weights[i]
                        [langIdx].cpu().data.numpy())

        if not self.no_transitions:
            # Add transition factors to graph
            kind = "trans"
            for tag in self.uniqueTags:
                for t in range(sentLen - 1):
                    var1 = graph.getVarByTimestepnTag(t, tag.idx)
                    var2 = graph.getVarByTimestepnTag(t + 1, tag.idx)
                    graph.addFactor(kind, var1, var2)

            transition_weights_np = {}
            for tag in self.uniqueTags:
                transition_weights_np[tag.idx] = self.transition_weights[
                    tag.idx].cpu().data.numpy()

            if self.model_type == "specific":
                for tag in self.uniqueTags:
                    transition_weights_np[tag.idx] = utils.logSumExp(
                        transition_weights_np[tag.idx],
                        self.lang_transition_weights[
                            tag.idx][langIdx].cpu().data.numpy())

        kind = "lstm"
        for tag in self.uniqueTags:
            for t in range(sentLen):
                var = graph.getVarByTimestepnTag(t, tag.idx)
                graph.addFactor(kind, var, "LSTMVar")

        # Initialize messages
        messages = Messages(graph, batch_size)

        # Add LSTM unary factor message to each variable
        for tag in self.uniqueTags:
            for t in range(sentLen):
                lstm_vecs = []
                var = graph.getVarByTimestepnTag(t, tag.idx)
                lstm_factor = graph.getFactorByVars(var, "LSTMVar")
                cur_tag_lstm_weights = self.lstm_weights[tag.idx]

                for batchIdx in range(batch_size):
                    lstm_feats = batch_lstm_feats[batchIdx]
                    cur_lstm_feats = lstm_feats[t]
                    cur_tag_lstm_feats = cur_lstm_feats[
                        self.tag_offsets[tag.name]:self.tag_offsets[tag.name] +
                        tag.size()]
                    lstm_vec = torch.unsqueeze(
                        cur_tag_lstm_weights + cur_tag_lstm_feats, 0)
                    lstm_vec = utils.logNormalizeTensor(lstm_vec).squeeze(
                        dim=0)
                    lstm_vecs.append(lstm_vec.cpu().data.numpy())

                messages.updateMessage(lstm_factor, var, np.array(lstm_vecs))

        iter = 0
        while iter < maxIters:
            print("[BP iteration %d]" % iter, end=" ")
            maxVal = [-float("inf")] * batch_size
            for tag in self.uniqueTags:
                var_list = graph.getVarsByTag(tag.idx)

                # FORWARD

                for t in range(sentLen):

                    var = var_list[t]

                    # Get pairwise potentials

                    factor_list = graph.getFactorByVars(var)
                    factor_sum = np.zeros((batch_size, var.tag.size()))

                    # Maintaining factor sum improves efficiency
                    for factor_mult in factor_list:
                        factor_sum += messages.getMessage(factor_mult,
                                                          var).value

                    for factor in factor_list:
                        if factor.kind == "pair":
                            var2 = factor.getOtherVar(var)

                            # variable2factor

                            message = np.zeros((batch_size, var.tag.size()))
                            message = factor_sum - messages.getMessage(
                                factor, var).value
                            message = utils.logNormalize(message)
                            curVal = messages.getMessage(var, factor).value

                            # From (Sutton, 2012)
                            maxVal = np.maximum(
                                maxVal, np.amax(np.abs(curVal - message), 1))
                            messages.updateMessage(var, factor, message)

                            # factor2variable
                            if var2.tag.idx < var.tag.idx:
                                pairwise_idx = self.pairs.index(
                                    (var2.tag.idx, var.tag.idx))
                                transpose = False
                            else:
                                pairwise_idx = self.pairs.index(
                                    (var.tag.idx, var2.tag.idx))
                                transpose = True

                            cur_pairwise_weights = pairwise_weights_np[
                                pairwise_idx]

                            if transpose:

                                pairwise_pot = utils.logDot(
                                    cur_pairwise_weights,
                                    messages.getMessage(var2, factor).value,
                                    redAxis=1)
                            else:
                                pairwise_pot = utils.logDot(
                                    messages.getMessage(var2, factor).value,
                                    cur_pairwise_weights,
                                    redAxis=0)

                            pairwise_pot = utils.logNormalize(pairwise_pot)
                            curVal = messages.getMessage(factor, var).value
                            maxVal = np.maximum(
                                maxVal,
                                np.amax(np.abs(curVal - pairwise_pot), 1))
                            messages.updateMessage(factor, var, pairwise_pot)
                            factor_sum += pairwise_pot - curVal

                    if not self.no_transitions:

                        cur_tag_weights = transition_weights_np[tag.idx]

                        # Get transition potential
                        if t != sentLen - 1:

                            var2 = graph.getVarByTimestepnTag(t + 1, tag.idx)
                            trans_factor = graph.getFactorByVars(var, var2)

                            # Variable2Factor Message

                            message = np.zeros((batch_size, var.tag.size()))
                            message = factor_sum - messages.getMessage(
                                trans_factor, var).value

                            # for factor_mult in factor_list:
                            # 	if factor_mult!=trans_factor:
                            # 		message += messages.getMessage(factor_mult, var).value

                            message = utils.logNormalize(message)
                            curVal = messages.getMessage(var,
                                                         trans_factor).value
                            maxVal = np.maximum(
                                maxVal, np.amax(np.abs(curVal - message), 1))
                            messages.updateMessage(var, trans_factor, message)
                            # Factor2Variable Message

                            transition_pot = utils.logDot(messages.getMessage(
                                var, trans_factor).value,
                                                          cur_tag_weights,
                                                          redAxis=0)

                            transition_pot = utils.logNormalize(transition_pot)
                            curVal = messages.getMessage(trans_factor,
                                                         var2).value
                            maxVal = np.maximum(
                                maxVal,
                                np.amax(np.abs(curVal - transition_pot), 1))
                            messages.updateMessage(trans_factor, var2,
                                                   transition_pot)

                # BACKWARD
                if not self.no_transitions:

                    for t in range(sentLen - 1, 0, -1):

                        var = var_list[t]
                        factor_list = graph.getFactorByVars(var)

                        # Variable2Factor Message

                        var2 = graph.getVarByTimestepnTag(t - 1, tag.idx)
                        trans_factor = graph.getFactorByVars(var, var2)

                        message = np.zeros((batch_size, var.tag.size()))

                        for i, factor_mult in enumerate(factor_list):
                            if factor_mult != trans_factor:
                                message += messages.getMessage(
                                    factor_mult, var).value

                        message = utils.logNormalize(message)
                        curVal = messages.getMessage(var, trans_factor).value
                        maxVal = np.maximum(
                            maxVal, np.amax(np.abs(curVal - message), 1))
                        messages.updateMessage(var, trans_factor, message)
                        transition_pot = utils.logDot(cur_tag_weights,
                                                      messages.getMessage(
                                                          var,
                                                          trans_factor).value,
                                                      redAxis=1)

                        transition_pot = utils.logNormalize(transition_pot)
                        curVal = messages.getMessage(trans_factor, var2).value
                        maxVal = np.maximum(
                            maxVal, np.amax(np.abs(curVal - transition_pot),
                                            1))
                        messages.updateMessage(trans_factor, var2,
                                               transition_pot)

            iter += 1
            print("Max Res Value: %f" % max(maxVal))
            if max(maxVal) <= threshold:
                print("Converged in %d iterations" % (iter))
                break
            if iter == 1000:
                print("Diverging :( Finished 1000 iterations.")
                return None

        # Calculate belief values and marginals

        # Variable beliefs
        for tag in self.uniqueTags:
            for t in range(sentLen):

                var = graph.getVarByTimestepnTag(t, tag.idx)

                factor_list = graph.getFactorByVars(var)
                for factor in factor_list:
                    factorMsg = Variable(
                        torch.FloatTensor(
                            messages.getMessage(factor, var).value))
                    if self.gpu:
                        factorMsg = factorMsg.cuda()
                    var.belief = var.belief + factorMsg

                # Normalize
                var.belief = utils.logNormalizeTensor(var.belief)

        # Factor beliefs
        for factor in graph.iterFactors():
            var1, var2 = graph.getVarsByFactor(factor)
            if factor.kind == "trans":
                factor.belief = self.transition_weights[var1.tag.idx]
                if self.model_type == "specific":
                    factor.belief = utils.logSumExpTensors(
                        factor.belief,
                        self.lang_transition_weights[var1.tag.idx][langIdx])
            elif factor.kind == "pair":
                pairwise_idx = self.pairs.index((var1.tag.idx, var2.tag.idx))
                factor.belief = self.pairwise_weights[pairwise_idx]
                if self.model_type == "specific":
                    factor.belief = utils.logSumExpTensors(
                        factor.belief,
                        self.lang_pairwise_weights[pairwise_idx][langIdx])
            else:
                continue

            factor.belief = factor.belief.view(1, factor.belief.size(0),
                                               -1).expand(batch_size, -1, -1)

            msg1 = torch.FloatTensor(messages.getMessage(var1, factor).value)
            msg2 = torch.FloatTensor(messages.getMessage(var2, factor).value)
            if self.gpu:
                msg1 = msg1.cuda()
                msg2 = msg2.cuda()

            factor.belief = Variable(
                msg1.view(batch_size, -1, 1).expand(
                    -1, -1, var2.tag.size())) + factor.belief
            factor.belief = Variable(
                msg2.view(batch_size, 1, -1).expand(-1, var1.tag.size(),
                                                    -1)) + factor.belief
            factor.belief = utils.logNormalizeTensor(factor.belief)

        # Calculate likelihood
        # likelihood = self.calc_likelihood(graph, gold_tags)
        # print("--- %s seconds ---" % (time.time() - start_time))
        return graph, max(maxVal)
示例#25
0
文件: fps.py 项目: xhalo32/advpy
def printall(self):

    printfps(self)

    if self.timer % 30 == 0:
        updatefps = 0
        for i in self.updatefpslist:
            updatefps += i
        self.updatefps = updatefps

    if self.timer % 30 == 0:
        drawfps = 0
        for i in self.drawfpslist:
            drawfps += i
        self.drawfps = drawfps

    if self.timer % 30 == 0:
        totalfps = 0
        for i in self.totalfpslist:
            totalfps += i
        self.totalfps = totalfps

    try:
        Messages.message(self.scr,
                         round(self.updatefps / len(self.updatefpslist), 1),
                         [10, 10], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr,
                         round(self.drawfps / len(self.drawfpslist), 1),
                         [10, 30], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr,
                         round(self.totalfps / len(self.totalfpslist), 1),
                         [10, 50], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(
            self.scr, 1.0 / (self.updatefps / len(self.updatefpslist)) * 1000,
            [120, 10], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr,
                         1.0 / (self.drawfps / len(self.drawfpslist)) * 1000,
                         [120, 30], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr,
                         1.0 / (self.totalfps / len(self.totalfpslist)) * 1000,
                         [120, 50], (0, 0, 0))
    except:
        pass
示例#26
0
文件: block.py 项目: xhalo32/advpy
class Block():
	
	def __init__(self, scr, spd, color, game):
		
		self.scr = scr
		self.w = 100
		self.h = 50
		self.x = random.randint(0, self.scr.get_width() - self.w)
		self.y = -self.h
		self.center = [self.x + self.w/2, self.y + self.h/2]
		self.speed = spd
		self.color = color
		
		self.randomness = 10
		self.terminate = self.fail = False
		
		self.calc = [random.randint(0, 4), random.randint(0, 5)]
		self.ans = self.calc[0] + self.calc[1]
		self.displayCalc = str(self.calc[0]) + " + " + str(self.calc[1])
		
		self.msg = Messages(self.scr)
		self.game = game
	
	def draw(self):
		
		self.randomness = self.game.combo * (self.game.score) + 10

		if self.randomness > 100:
			self.randomness = 100
		
		pg.draw.complex.rrect(self.scr, self.randomC(), [int(self.x), int(self.y), int(self.w), int(self.h)], 6)

		self.msg.message(
						self.displayCalc,
						[self.x + self.w/2, self.y + self.h/2],
						size = 30,
						color=self.invert(self.color)
						)
	
	def update(self):

		self.y += self.speed
		self.center = [self.x + self.w/2, self.y + self.h/2]

		if self.y > self.scr.get_height() - 100:
			self.y -= self.speed / 2.0
		
		if self.y + self.h/2 >= self.scr.get_height():
			
			self.terminate = self.fail = True
	
	def randomC(self):

		self.c1, self.c2, self.c3 = self.color
		self.rclist = [0, 0, 0]
		
		rcolor = []
		color = self.color
		try:
			for i in range(len(color)):
				
				self.rclist[i] = random.randrange(-int(self.randomness) - 1,
												   int(self.randomness) + 1)
				tries = 50
				while color[i] + self.rclist[i] >= 255 or color[i] + self.rclist[i] <= 0:
					
					self.rclist[i] = random.randrange(-int(self.randomness),
													   int(self.randomness))
					tries -= 1
					if tries < 0: 
						self.rclist[i] = 0
						continue

				rcolor.append(color[i] + self.rclist[i])
		except:
			return color

		return rcolor
	
	def invert(self, color):
		rcolor = []
		try:
			for c in color:
				rcolor.append(255 - c)
			return rcolor
		except:
			return color
示例#27
0
class Run():
    def __init__(self):

        self.blocklist = []
        self.scr = pg.display.set_mode((1080, 720), pg.RESIZABLE)
        self.clock = pg.time.Clock()

        self.active = False
        self.designated_speed = 0
        self.designated_timing = 60
        self.not100 = False
        self.FPS = 40

        self.center = self.scr.get_width() / 2, self.scr.get_height() / 2

        self.sliders()
        self.effect = Effect(self)
        self.msg = Messages(self.scr)

        self.reset()

    def sliders(self):

        randCols = [0, 50, 200, 250]

        self.startSlider = Slider(
            self.scr,
            pos_size=[200, 100, 160, 40],
            steps=10,
            colour=(randCols[random.randint(0, 3)],
                    randCols[random.randint(0,
                                            3)], randCols[random.randint(0,
                                                                         3)]),
            secondary_colour=(randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)]),
        )

        self.startSlider2 = Slider(
            self.scr,
            pos_size=[200, 50, 160, 40],
            steps=100,
            colour=(randCols[random.randint(0, 3)],
                    randCols[random.randint(0,
                                            3)], randCols[random.randint(0,
                                                                         3)]),
            secondary_colour=(randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)]),
        )

    def reset(self):

        self.timing = self.designated_timing
        self.speed = self.designated_speed
        self.score = 0
        self.combo = 1
        self.timer = 0
        self.effect.fireworks = []

    def mkBlock(self):

        randCols = [0, 50, 200, 250]

        b = Block(self.scr, self.speed,
                  (randCols[random.randint(0, 3)], randCols[random.randint(
                      0, 3)], randCols[random.randint(0, 3)]), self)

        self.blocklist.append(b)

    def updateBlock(self, event):

        if len(self.blocklist) > 0:

            for e in event:
                if e.type == pg.KEYDOWN:

                    if e.key in range(48, 58) or e.key in range(256, 266):

                        if e.key == 48 + self.blocklist[0].ans or \
                        e.key == 256 + self.blocklist[0].ans:

                            ##SCORE!

                            self.effect.fireWork(
                                data={
                                    "pos": self.blocklist[0].center,
                                    "size": 90,
                                    "radius": 3,
                                    "speed": 5,
                                    "timer": 1,
                                    "dragindex": 0.005,
                                    "type": EffectTypes.DIFFUSE,
                                    #"subtypes" : [EffectSubTypes.RAINBOW],
                                    "color": self.blocklist[0].color
                                })

                            self.blocklist[0].terminate = True

                            self.score += (1 + self.speed / 10) + \
                              self.combo * self.blocklist[0].ans
                            self.combo += self.blocklist[0].ans / 50.0

                        else:

                            #WRONG KEY
                            self.score -= self.blocklist[0].ans
                            self.combo -= 0.1

        toterminate = []

        for b in range(len(self.blocklist)):

            self.blocklist[b].update()

            if self.blocklist[b].terminate:
                toterminate.append(b)

            if self.blocklist[b].fail:
                self.score -= 2 * self.blocklist[b].ans
                self.combo -= 0.5
                self.effect.fireWork(
                    data={
                        "pos": self.blocklist[b].center,
                        "size": 80,
                        "radius": 3,
                        "speed": 6,
                        "timer": 1.3,
                        "dragindex": 0.002,
                        "type": EffectTypes.EXPAND,
                        #"subtypes" : [EffectSubTypes.RAINBOW],
                        "color": self.blocklist[0].color
                    })

        for b in toterminate:

            del self.blocklist[b]

    def draw(self):

        self.effect.draw()

        for b in self.blocklist:
            b.draw()

        self.msg.message(round(self.score, 2), [70, 40], pg.Color('blue'), 30)
        self.msg.message(round(self.timer / 40, 5), [70, 120], pg.Color('red'),
                         30)
        self.msg.message(round(self.combo, 2), [70, 80], pg.Color('darkgreen'),
                         30)

    def lose(self):

        done = 0

        self.msg.message("YOU LOSE!", [200, 200], pg.Color('red'), 45)

        self.msg.message(
            "YOU SURVIVED " + str(round(self.timer / 40, 2)) + "s!",
            [200, 250], pg.Color('black'), 40)

        pg.display.flip()

        while not done:

            for e in pg.event.get():

                if e.type == pg.QUIT:
                    pg.quit()
                    quit()

                if e.type == pg.KEYDOWN:
                    if e.key == pg.K_SPACE:
                        done = 1

    def start(self):

        while not self.active:

            self.scr.fill(pg.Color('gray'))

            event = pg.event.get()
            for e in event:
                if e.type == pg.QUIT:
                    pg.quit()
                    quit()
                elif e.type == pg.KEYDOWN:
                    if e.key == pg.K_SPACE:
                        self.loop()

                elif e.type == pg.VIDEORESIZE:
                    self.scr = pg.display.set_mode(e.dict["size"],
                                                   pg.RESIZABLE)

            speed_sliderpos = self.startSlider.run(self.speed)
            timing_sliderpos = self.startSlider2.run(self.timing)

            self.designated_speed = speed_sliderpos + 1
            self.speed = speed_sliderpos + 1

            self.designated_timing = timing_sliderpos + 10
            self.timing = timing_sliderpos + 10

            self.designated_timing = timing_sliderpos

            self.msg.message("[SPACE]", [200, 200], pg.Color('magenta'), 45, 1)

            pg.display.update()
            self.clock.tick(40)

    def loop(self):

        self.active = True
        self.losing = False

        clock = pg.time.Clock()
        self.reset()

        self.blocklist = []
        self.scr = pg.display.set_mode(self.scr.get_size())

        while self.active:

            lasttime = time.time()

            self.scr.fill(pg.Color('gray'))
            event = pg.event.get()
            for e in event:
                if e.type == pg.QUIT:
                    self.active = False
                elif e.type == pg.KEYDOWN:

                    if e.key == pg.K_ESCAPE:
                        self.active = False
                        pg.quit()
                        quit()

            if self.score < 0:
                self.active = False
                self.losing = True

            self.timer += 1
            self.speed += 0.003
            self.timing -= 0.005
            self.combo -= 0.01 / 40

            if self.combo <= 0.5:
                self.combo = 0.5

            if self.timer % int(self.timing + 1) == 0:
                self.mkBlock()

            self.effect.update()

            self.updateBlock(event)
            self.draw()

            self.FPS = 1.0 / (time.time() - lasttime)
            self.msg.message(round(self.FPS, 1), (500, 20), size=25)

            pg.display.flip()

            clock.tick(40)

        if self.losing:
            self.lose()
示例#28
0
文件: fps.py 项目: xhalo32/advpy
def printall(self):

    printfps(self)

    if self.timer % 30 == 0:
        updatefps = 0
        for i in self.updatefpslist:
            updatefps += i
        self.updatefps = updatefps

    if self.timer % 30 == 0:
        drawfps = 0
        for i in self.drawfpslist:
            drawfps += i
        self.drawfps = drawfps

    if self.timer % 30 == 0:
        totalfps = 0
        for i in self.totalfpslist:
            totalfps += i
        self.totalfps = totalfps

    try:
        Messages.message(self.scr, round(self.updatefps / len(self.updatefpslist), 1), [10, 10], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr, round(self.drawfps / len(self.drawfpslist), 1), [10, 30], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr, round(self.totalfps / len(self.totalfpslist), 1), [10, 50], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr, 1.0 / (self.updatefps / len(self.updatefpslist)) * 1000, [120, 10], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr, 1.0 / (self.drawfps / len(self.drawfpslist)) * 1000, [120, 30], (0, 0, 0))
    except:
        pass

    try:
        Messages.message(self.scr, 1.0 / (self.totalfps / len(self.totalfpslist)) * 1000, [120, 50], (0, 0, 0))
    except:
        pass
示例#29
0
class Block():
    def __init__(self, scr, spd, color, game):

        self.scr = scr
        self.w = 100
        self.h = 50
        self.x = random.randint(0, self.scr.get_width() - self.w)
        self.y = -self.h
        self.center = [self.x + self.w / 2, self.y + self.h / 2]
        self.speed = spd
        self.color = color

        self.randomness = 10
        self.terminate = self.fail = False

        self.calc = [random.randint(0, 4), random.randint(0, 5)]
        self.ans = self.calc[0] + self.calc[1]
        self.displayCalc = str(self.calc[0]) + " + " + str(self.calc[1])

        self.msg = Messages(self.scr)
        self.game = game

    def draw(self):

        self.randomness = self.game.combo * (self.game.score) + 10

        if self.randomness > 100:
            self.randomness = 100

        pg.draw.complex.rrect(
            self.scr, self.randomC(),
            [int(self.x), int(self.y),
             int(self.w), int(self.h)], 6)

        self.msg.message(self.displayCalc,
                         [self.x + self.w / 2, self.y + self.h / 2],
                         size=30,
                         color=self.invert(self.color))

    def update(self):

        self.y += self.speed
        self.center = [self.x + self.w / 2, self.y + self.h / 2]

        if self.y > self.scr.get_height() - 100:
            self.y -= self.speed / 2.0

        if self.y + self.h / 2 >= self.scr.get_height():

            self.terminate = self.fail = True

    def randomC(self):

        self.c1, self.c2, self.c3 = self.color
        self.rclist = [0, 0, 0]

        rcolor = []
        color = self.color
        try:
            for i in range(len(color)):

                self.rclist[i] = random.randrange(-int(self.randomness) - 1,
                                                  int(self.randomness) + 1)
                tries = 50
                while color[i] + self.rclist[i] >= 255 or color[
                        i] + self.rclist[i] <= 0:

                    self.rclist[i] = random.randrange(-int(self.randomness),
                                                      int(self.randomness))
                    tries -= 1
                    if tries < 0:
                        self.rclist[i] = 0
                        continue

                rcolor.append(color[i] + self.rclist[i])
        except:
            return color

        return rcolor

    def invert(self, color):
        rcolor = []
        try:
            for c in color:
                rcolor.append(255 - c)
            return rcolor
        except:
            return color
示例#30
0
文件: slider.py 项目: xhalo32/advpy
class Slider(object):
    
    def __init__(self,
                 scr,
                 colour = (255, 255, 255),
                 secondary_colour = (200, 200, 200),
                 pos_size = [100, 100, 100, 20],
                 steps = 10):
        
        self.scr = scr
        self.pos_size = pos_size
        self.steps = steps
        self.color = colour
        self.secondary_color = secondary_colour
        self.dragging = False
        self.sliderpos = math.floor((steps)/2.0)
        
        self.steplen = pos_size[2] / float(steps)
        self.center = pos_size[0] + pos_size[2] / 2, \
                      pos_size[1] + pos_size[3] / 2
        
        self.button = self.center[0]
        
        self.msg = Messages(self.scr)
    
    def run(self, name=""):
        
        self.action()
        
        if self.dragging:
            pg.draw.rect(self.scr, self.secondary_color, self.pos_size)
            
            pg.draw.circle(self.scr, self.half(self.secondary_color),
                       [int(self.button), self.pos_size[1] + self.pos_size[3] / 2],
                       self.pos_size[3] / 2)
        else:
            pg.draw.rect(self.scr, self.color, self.pos_size)
            
            pg.draw.circle(self.scr, self.half(self.color),
                       [int(self.button), self.pos_size[1] + \
                            self.pos_size[3] / 2],
                       int(self.pos_size[3] / 2.2))
        
        self.msg.message(name,
                         [self.button,
                         self.pos_size[1] + self.pos_size[3] / 2],
                         self.invert(self.color), 30)
        
        return self.sliderpos
        
    def action(self):
        
        self.rel = pg.mouse.get_rel()[0]
        
        mclick = pg.mouse.get_pressed()
        mpos = pg.mouse.get_pos()
        
        if mclick[0]:
            if mpos[0] < self.pos_size[0] + self.pos_size[2] and\
               mpos[0] > self.pos_size[0]:
               
                if mpos[1] > self.pos_size[1] and\
                  mpos[1] < self.pos_size[1] + self.pos_size[3]:
                   
                    self.dragging = True
                    
        else: 
            self.dragging = False
        
        if self.dragging:
            
            for i in range(self.steps):
                
                if mpos[0] > self.pos_size[0] + (i) * self.steplen and \
                   mpos[0] < self.pos_size[0] + (i + 1) * self.steplen:
                    
                    self.sliderpos = i
                    
                    self.button = self.pos_size[0] + (i + 1) \
                     * self.steplen - self.steplen / 2
            
    def invert(self, color):
        rcolor = []
        try:
            for c in color:
                rcolor.append(255 - c)
            return rcolor
        except:
            return color
    
    def half(self, color):
        rcolor = []
        try:
            for c in color:
                rcolor.append( int( c**(math.sqrt(0.7)) ) )
            return rcolor
        except:
            return color