Exemplo n.º 1
0
 def __init__(self, factor1='0', factor2='0', answer='0', operator='+'):
     #因子1
     self.factor1 = Factors(factor1)
     #因子2
     self.factor2 = Factors(factor2)
     #结果
     self.answer = Factors(answer)
     #符号
     self.operator = Operators(operator)
     #是否为等式
     if self.operator.val() == 1:
         if self.factor1.val() + self.factor2.val() == self.answer.val():
             self.equal = True
         else:
             self.equal = False
     elif self.operator.val() == 2:
         if self.factor1.val() - self.factor2.val() == self.answer.val():
             self.equal = True
         else:
             self.equal = False
     else:
         if self.factor1.val() * self.factor2.val() == self.answer.val():
             self.equal = True
         else:
             self.equal = False
Exemplo n.º 2
0
    def initialize(self):

        # Sets up the numbers and operators that move down the screen.

        self.answer_numbers = [4, 13, 21, 34, 48, 64, 85, 110] # possible answers for game, ideally will randomize in final game

        # Creates objects for each number
        self.number_objects = []

        for number in range(1,10):

            image = self.final_number_font.render(str(number), True, self.chosen_number_colors[number])
            new_number = Numbers(self.screen, image, number, False)
            self.number_objects.append(new_number)

        plus_image = pygame.image.load("plussymbol.png").convert_alpha()
        minus_image = pygame.image.load("minussymbol.png").convert_alpha()
        multiply_image = pygame.image.load("multiplysymbol.png").convert_alpha()
        divide_image = pygame.image.load("dividesymbol.png").convert_alpha()
        power_image = pygame.image.load("caret.png").convert_alpha()

        # Creates objects for each operator (may remove minus and divide)
        self.plus = Operators(self.screen, plus_image, '+', False)
        self.minus = Operators(self.screen, minus_image, '-', False)
        self.multiply = Operators(self.screen, multiply_image, '*', False)
        self.divide = Operators(self.screen, divide_image, '/', False)
        self.power = Operators(self.screen, power_image, '^', False)

        # A lot of initializations
        self.hit_number = False

        self.hit_operator = False

        self.points = 0

        self.temporary_operator = '+' # Initalizes the operator

        self.answer_numbers_index = 0 # Defines current answer player strives for. Increments everytime the correct answer is chosen

        self.accumulating_answer = 0 # Keeps track of current value user calculates after shooting the numbers and operators.

        self.number_operators_used = 0 # Keeps track of number of operators used (for points)

        self.random_operator_count = 0  # Determines when operator will appear, spaces them out with 

        self.random_number_count = 0

        self.x = 319
        self.y = 350

        self.player_ship = Ship(self.screen, self.avatar, self.x, self.y)

        self.ships = pygame.sprite.Group()
        self.ships.add(self.player_ship)

        self.moving_numbers = pygame.sprite.Group()
        self.moving_operators = pygame.sprite.Group()
        self.moving_laser = LaserFactory(self.screen, self.final_laser_choice)

        self.introMenu()
Exemplo n.º 3
0
    def IntermolecularIneffectiveCollision(self, mole, oldMol1, oldMol2,
                                           index1, index2):
        operator = Operators()
        newMol1, newMol2 = operator.Intermolecular(oldMol1, oldMol2)
        pe1 = CRO().CalculatePE(mole, newMol1)
        pe2 = CRO().CalculatePE(mole, newMol2)

        e_inter = 0
        gamma4 = random.uniform(0, 1)

        mole.numHit[index1] = mole.numHit[index1] + 1
        mole.numHit[index2] = mole.numHit[index2] + 1
        e_inter = (mole.PE1[index1] + mole.PE1[index2] + mole.KE1[index1] +
                   mole.KE1[index2]) - (pe1 + pe2)
        if (e_inter >= 0):
            mole.moleculeTable[index1] = newMol1
            mole.moleculeTable[index2] = newMol2
            mole.PE1[index1] = pe1
            mole.PE1[index2] = pe2
            mole.KE1[index1] = e_inter * gamma4
            mole.KE1[index2] = e_inter * (1 - gamma4)

            if (mole.PE1[index1] < mole.minPE[index1]):
                mole.minStruct[index1] = mole.moleculeTable[index1]
                mole.minPE[index1] = mole.PE1[index1]
                mole.minHit[index1] = mole.numHit[index1]
            # endif

            if (mole.PE1[index2] < mole.minPE[index2]):
                mole.minStruct[index2] = mole.moleculeTable[index2]
                mole.minPE[index2] = mole.PE1[index2]
                mole.minHit[index2] = mole.numHit[index2]
Exemplo n.º 4
0
    def __init__(self,param,grid):

        self.list_param=['forcing','noslip','timestepping','diffusion','Kdiff',
                         'forcing_module','gravity','isisland',
                         'customized','custom_module','additional_tracer']
        param.copy(self,self.list_param)

        # for potential energy
        self.list_param=['xr','yr','nh','Lx','msk','area','mpitools']
        grid.copy(self,self.list_param)

        # for variables
        param.varname_list=['vorticity','psi','u','v','buoyancy']
        param.tracer_list=['vorticity','buoyancy']
        param.whosetspsi=('vorticity')

        if hasattr(self,'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac=self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)
                print('Tracers are :',param.tracer_list)

        param.sizevar     =[grid.nyl,grid.nxl]
        self.var = Var(param)
        self.source = zeros(param.sizevar)

        # for operators
        self.ope = Operators(param,grid)

        # for timescheme
        self.tscheme = Timescheme(param,self.var.state)
        self.tscheme.set(self.dynamics, self.timestepping)

        if self.forcing:

            try:
                f = import_module(self.forcing_module)
            except:
                print('module %s for forcing cannot be found'%self.forcing_module)
                print('make sure file **%s.py** exists'%self.forcing_module)
                exit(0)

            self.forc = f.Forcing(param,grid)

        self.diags={}

        if self.customized:
            try:
                f = import_module(self.custom_module)
                print(f)
                self.extrastep = f.Step(param,grid)
            except:
                print('module %s for forcing cannot be found'%self.custom_module)
                print('make sure file **%s.py** exists'%self.custom_module)
                exit(0)
Exemplo n.º 5
0
    def __init__(self, param, grid):

        self.list_param = ['forcing', 'noslip', 'timestepping',
                           'forcing_module', 'additional_tracer',
                           'myrank',
                           'gravity', 'diffusion', 'Kdiff', 'f0']
        param.copy(self, self.list_param)

        # for potential energy
        self.list_param = ['xr', 'yr', 'nh',
                           'Lx', 'msk', 'area', 'mpitools', 'dx']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = ['vorticity', 'psi',
                              'u', 'v', 'buoyancy', 'V', 'qE']
        param.tracer_list = ['vorticity', 'buoyancy', 'V']
        param.whosetspsi = ('vorticity')

        if hasattr(self, 'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac = self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)

        # for operators
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)

        if self.forcing:
            if self.forcing_module == 'embedded':
                print('Warning: check that you have indeed added the forcing to the model')
                print('Right below the line    : model = f2d.model')
                print('you should have the line: model.forc = Forcing(param, grid)')

                pass
            else:
                try:
                    f = import_module(self.forcing_module)

                except ImportError:
                    print('module %s for forcing cannot be found'
                          % self.forcing_module)
                    print('make sure file **%s.py** exists' % self.forcing_module)
                    sys.exit(0)

                self.forc = f.Forcing(param, grid)


        self.diags = {}
Exemplo n.º 6
0
    def __init__(self, param, grid):
        self.list_param = [
            'forcing', 'diffusion', 'Kdiff', 'noslip', 'timestepping', 'beta',
            'Rd', 'forcing_module'
        ]
        param.copy(self, self.list_param)

        # for diagnostics
        self.list_param = ['yr', 'nh', 'msk', 'area', 'mpitools']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = ('pv1', 'psi1', 'u1', 'v1', 'pv2', 'psi2', 'u2',
                              'v2')
        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        self.source = zeros(param.sizevar)

        #        self.ipva = self.var.varname_list.index('pvanom')
        #        self.ipv  = self.var.varname_list.index('pv')
        #        self.ivor = self.var.varname_list.index('vorticity')
        #        self.ipsi = self.var.varname_list.index('psi')

        # background pv
        self.pvback = self.beta * (grid.yr - grid.Ly * .5) * grid.msk

        # for operators
        param.tracer_list = ['pv1', 'pv2']
        param.whosetspsi = ('pvanom')
        param.qgoperator = True
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.dx0 = self.tscheme.dx0

        self.kt = 0

        if self.forcing:

            try:
                f = import_module(self.forcing_module)
            except:
                print('module %s for forcing cannot be found' %
                      self.forcing_module)
                print('make sure file **%s.py** exists' % self.forcing_module)
                exit(0)

            self.forc = f.Forcing(param, grid)

        self.diags = {}

        self.tscheme.set(self.dynamics, self.timestepping)
Exemplo n.º 7
0
 def add_tile(self, input_name, loops, axis, output_name):
     layer = caffe_net.LayerParameter(name=output_name, type='Tile',
                                      bottom=[input_name], top=[output_name])
     layer.tile_param(axis, loops)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.tile(self.data_dict[input_name], loops, axis, output_name)
     return output_name
Exemplo n.º 8
0
 def add_expand_dims(self, input_name, axis, output_name):
     layer = caffe_net.LayerParameter(name=output_name, type='Unsqueeze',
                 bottom=[input_name], top=[output_name])
     layer.unsqueeze_param(axis)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.expand_dims(self.data_dict[input_name], axis, output_name)
     return output_name
Exemplo n.º 9
0
 def add_swish(self, input_name, output_name, beta=1.0):
     layer = caffe_net.LayerParameter(name=output_name, type='Swish',
                 bottom=[input_name],
                                   top=[output_name])
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.swish(self.data_dict[input_name], beta, output_name)
     return output_name
Exemplo n.º 10
0
 def add_sigmoid(self, input_name, output_name):
     layer = caffe_net.LayerParameter(name=output_name, type='Sigmoid',
                 bottom=[input_name],
                                   top=[output_name])
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.sigmoid(self.data_dict[input_name], output_name)
     return output_name
Exemplo n.º 11
0
 def add_relative_shift(self, input_name, output_name, axis, shift_length):
     layer = caffe_net.LayerParameter(name=output_name, type='RelativeShift',
                 bottom=[input_name], top=[output_name])
     layer.relative_shift_param(axis, shift_length)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.relative_shift(self.data_dict[input_name], axis, shift_length, output_name)
     return output_name
Exemplo n.º 12
0
 def add_power(self, input_name, output_name, scale=1, shift=0, power=1):
     layer = caffe_net.LayerParameter(name=output_name, type='Power',
                 bottom=[input_name], top=[output_name])
     layer.power_param(scale, shift, power)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.power(self.data_dict[input_name], scale, shift, power, output_name)
     return output_name
Exemplo n.º 13
0
 def add_transpose(self, input_name, output_name, dim):
     layer = caffe_net.LayerParameter(name=output_name, type='Permute',
                 bottom=[input_name], top=[output_name])
     layer.permute_param(dim)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.transpose(self.data_dict[input_name], dim, output_name)
     return output_name
Exemplo n.º 14
0
 def add_reshape(self, input_name, output_name, shape):
     layer = caffe_net.LayerParameter(name=output_name, type='Reshape',
                 bottom=[input_name], top=[output_name])
     layer.reshape_param(shape)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.reshape(self.data_dict[input_name], shape, output_name)
     return output_name
Exemplo n.º 15
0
 def add_argmax(self, input_name, axis, output_name):
     layer = caffe_net.LayerParameter(name=output_name, type='ArgMax',
                 bottom=[input_name], top=[output_name])
     layer.argmax_param(axis)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.argmax(self.data_dict[input_name], axis, output_name)
     return output_name
Exemplo n.º 16
0
    def add_copy(self, src_name, src_batch_stride, src_stride, src_offset,
            dst_name, dst_batch_stride, dst_stride, dst_offset,
            length,
            output_name,
            src_index_name=None, dst_index_name=None):
        src_index = None
        dst_index = None
        if (src_index_name is None):
            layer = caffe_net.LayerParameter(name=output_name, type='Copy',
                        bottom=[src_name, dst_name], top=[output_name])
        else:
            layer = caffe_net.LayerParameter(name=output_name, type='Copy',
                        bottom=[src_name, dst_name, src_index_name, dst_index_name], top=[output_name])
            src_index = self.data_dict[src_index_name]
            dst_index = self.data_dict[dst_index_name]
        layer.copy_param(src_batch_stride, src_stride, src_offset, dst_batch_stride, dst_stride, dst_offset, length)
        self.caffe_model.add_layer(layer)

        self.data_dict[dst_name] = Operators.copy(self.data_dict[src_name],
                                       src_batch_stride, src_stride, src_offset,
                                       self.data_dict[dst_name],
                                       dst_batch_stride, dst_stride, dst_offset,
                                       length,
                                       dst_name,
                                       src_index, dst_index)
        return dst_name
Exemplo n.º 17
0
 def add_l2norm(self, input_name, output_name):
     layer = caffe_net.LayerParameter(name=output_name, type='L2Norm',
                 bottom=[input_name],
                 top=[output_name])
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.l2_norm(self.data_dict[input_name], output_name)
     return output_name
Exemplo n.º 18
0
 def add_pad(self, input_name, output_name, padding_shapes, padding_values=None):
     layer = caffe_net.LayerParameter(name=output_name, type='Pad',
                 bottom=[input_name], top=[output_name])
     layer.padding_param(padding_shapes, padding_values)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.pad(self.data_dict[input_name], padding_shapes, padding_values, output_name)
     return output_name
Exemplo n.º 19
0
 def add_relu6(self, input_name, output_name):
     layer = caffe_net.LayerParameter(name=output_name, type='ReLU6',
                 bottom=[input_name],
                 top=[output_name])
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.relu(self.data_dict[input_name], output_name, max_value=6)
     return output_name
Exemplo n.º 20
0
 def add_memory(self, memory_name, memory_shapes, data_type):
     layer = caffe_net.LayerParameter(name=memory_name+"_mem", type='PreAllocatedMemory',
         top=[memory_name])
     layer.memory_param(memory_shapes, data_type)
     self.caffe_model.add_layer(layer)
     self.data_dict[memory_name] = Operators.zeros(memory_shapes, memory_name)
     return memory_name
Exemplo n.º 21
0
 def generate(self, input = None):
     #batch_seq_length = 16
     input_text_name = "input_text" 
     input_text_shape = [self.batch, 16]
     self.add_input(input_text_name, input_text_shape)
     self.set_input(input)
     #embedding
     x = self.extract_embedding(input_text_name, 0, "emb_table", "embedding_lookup")
     #bilstm
     x = self.extract_lstm(x, None, "BiLSTM", 0, steps = -2, scope_name = ["BiLSTM/fw/lstm_cell", "BiLSTM/bw/lstm_cell"])
     #FC
     weight = self.get_weight("W")
     bias = self.get_weight("b")
     layer = caffe_net.LayerParameter("wb_fc_output", type='InnerProduct',
                     bottom=[x], top=["wb_fc_output"])
     num_output = len(weight[0])
     weight = weight.transpose((1,0))
     layer.inner_product_param(num_output, bias_term=bias is not None)
     if len(bias) != num_output:
         print("[ERROR] extract_dense failed")
         exit(0)
     layer.add_data(weight, bias)
     self.caffe_model.add_layer(layer)
     self.data_dict["wb_fc_output"] = Operators.fully_connect(self.data_dict[x],
                                          weight.transpose((1, 0)), bias,
                                          "wb_fc_output")
     x = "wb_fc_output"
     #softmax
     x = self.add_softmax(x, "softmax_output", -1)
     #argmax
     x = self.add_argmax(x, -1, "output")
     self.save_caffe_model()
Exemplo n.º 22
0
 def extract_dense(self,
                   input_name,
                   output_name,
                   scope_id,
                   scope_name="dense"):
     if (isinstance(scope_name, str)):
         layer_names = [scope_name, "kernel", "bias"]
     elif (isinstance(scope_name, list)):
         layer_names = scope_name
     else:
         print("[ERROR] unsupported dense scope_name")
         exit(1)
     kernel, bias = self.get_weights(scope_id, layer_names)
     layer = caffe_net.LayerParameter(name=output_name,
                                      type='InnerProduct',
                                      bottom=[input_name],
                                      top=[output_name])
     num_output = len(kernel[0])
     kernel = kernel.transpose((1, 0))
     layer.inner_product_param(num_output, bias_term=bias is not None)
     if bias is not None:
         if len(bias) != num_output:
             print("[ERROR] extract_dense failed")
             exit(0)
         layer.add_data(kernel, bias)
     else:
         layer.add_data(kernel)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.fully_connect(
         self.data_dict[input_name], kernel.transpose((1, 0)), bias,
         output_name)
     return output_name
Exemplo n.º 23
0
 def extract_scale(self,
                   input_name,
                   output_name,
                   scope_id,
                   data_format="NCHW",
                   axis=1,
                   layer_names=["scale", "gamma", "beta"]):
     assert (data_format == "NCHW")
     gamma, beta = self.get_weights(scope_id, layer_names)
     layer = caffe_net.LayerParameter(name=output_name,
                                      type='Scale',
                                      bottom=[input_name],
                                      top=[output_name])
     if beta is not None:
         layer.scale_param(axis=axis, bias_term=True)
         layer.add_data(gamma, beta)
     else:
         layer.scale_param(axis=axis, bias_term=False)
         layer.add_data(gamma)
     self.caffe_model.add_layer(layer)
     if (self.data_dict[input_name] is not None):
         input_data, input_shape, inv_transpose_dims = self.preprocess_nchwc8_nchw_input(
             input_name, axis)
         output_data = Operators.scale(input_data, gamma, beta, output_name)
         self.data_dict[output_name] = self.postprocess_nchwc8_nchw_output(
             output_data, input_shape, inv_transpose_dims)
     else:
         self.data_dict[output_name] = None
     return output_name
Exemplo n.º 24
0
 def extract_batch_norm(
         self,
         input_name,
         output_name,
         scope_id,
         data_format="NCHW",
         axis=1,
         eps=1e-3,
         layer_names=["bn", "moving_mean", "moving_variance"]):
     assert (data_format == "NCHW")
     mean, var = self.get_weights(scope_id, layer_names)
     layer = caffe_net.LayerParameter(name=output_name,
                                      type='BatchNorm',
                                      bottom=[input_name],
                                      top=[output_name])
     layer.batch_norm_param(axis=axis, eps=eps)
     layer.add_data(mean, var)
     self.caffe_model.add_layer(layer)
     if (self.data_dict[input_name] is not None):
         input_data, input_shape, inv_transpose_dims = self.preprocess_nchwc8_nchw_input(
             input_name, axis)
         output_data = Operators.batch_norm(input_data, mean, var, eps,
                                            output_name)
         self.data_dict[output_name] = self.postprocess_nchwc8_nchw_output(
             output_data, input_shape, inv_transpose_dims)
     else:
         self.data_dict[output_name] = None
     gamma = self.get_weights(scope_id, [layer_names[0], "gamma"])
     if (gamma is not None):
         scale_name = self.extract_scale(output_name, output_name + "_s",
                                         scope_id, data_format, axis,
                                         [layer_names[0], "gamma", "beta"])
         self.data_dict[output_name] = self.data_dict[scale_name]
         output_name = scale_name
     return output_name
Exemplo n.º 25
0
 def extract_layer_norm(self,
                        input_name,
                        layer_norm_name,
                        scope_id,
                        layer_names=None):
     if (layer_names is None):
         self.scopes[scope_id] = "LayerNorm"
         self.scopes[scope_id + 1] = "gamma"
         gamma_name = self.generate_name(self.scopes, scope_id + 2)
         self.scopes[scope_id + 1] = "beta"
         beta_name = self.generate_name(self.scopes, scope_id + 2)
     else:
         self.scopes[scope_id] = layer_names[0]
         self.scopes[scope_id + 1] = layer_names[1]
         gamma_name = self.generate_name(self.scopes, scope_id + 2)
         self.scopes[scope_id + 1] = layer_names[2]
         beta_name = self.generate_name(self.scopes, scope_id + 2)
     gamma = self.get_tensor(gamma_name)
     beta = self.get_tensor(beta_name)
     layer = caffe_net.LayerParameter(name=layer_norm_name,
                                      type='LayerNorm',
                                      bottom=[input_name],
                                      top=[layer_norm_name])
     layer.add_data(gamma, beta)
     self.caffe_model.add_layer(layer)
     self.data_dict[layer_norm_name] = Operators.layer_norm(
         self.data_dict[input_name], gamma, beta, layer_norm_name)
     return layer_norm_name
Exemplo n.º 26
0
 def extract_group_norm(self,
                        input_name,
                        groups,
                        output_name,
                        scope_id,
                        data_format="NCHW",
                        axis=1,
                        layer_names=["GroupNorm", "gamma", "beta"]):
     assert (data_format == "NCHW")
     gamma, beta = self.get_weights(scope_id, layer_names)
     layer = caffe_net.LayerParameter(name=output_name,
                                      type='GroupNorm',
                                      bottom=[input_name],
                                      top=[output_name])
     layer.add_data(gamma, beta)
     layer.group_norm_param(groups)
     self.caffe_model.add_layer(layer)
     if (self.data_dict[input_name] is not None):
         input_data, input_shape, inv_transpose_dims = self.preprocess_nchwc8_nchw_input(
             input_name, axis)
         output_data = Operators.group_norm(input_data, groups, gamma, beta,
                                            output_name)
         self.data_dict[output_name] = self.postprocess_nchwc8_nchw_output(
             output_data, input_shape, inv_transpose_dims)
     else:
         self.data_dict[output_name] = None
     return output_name
Exemplo n.º 27
0
    def extract_lstm(self,
                     input_name,
                     state_name,
                     output_name,
                     scope_id,
                     steps=-1,
                     scope_name="basic_lstm_cell"):
        self.scopes[scope_id] = scope_name
        self.scopes[scope_id + 1] = "kernel"
        kernel_name = self.generate_name(self.scopes, scope_id + 2)
        kernel = self.get_tensor(kernel_name)
        self.scopes[scope_id + 1] = "bias"
        bias_name = self.generate_name(self.scopes, scope_id + 2)
        bias = self.get_tensor(bias_name)

        layer = caffe_net.LayerParameter(name=output_name,
                                         type='LSTM',
                                         bottom=[input_name, state_name],
                                         top=[output_name])

        num_output_4 = len(kernel[0])
        if (bias is not None):
            if (len(bias) != num_output_4):
                print("[ERROR] extract_lstm failed")
                exit(0)
        num_output = num_output_4 // 4
        layer.lstm_param(num_output, steps)
        layer.add_data(kernel.transpose([1, 0]), bias)
        self.caffe_model.add_layer(layer)
        self.data_dict[output_name], self.data_dict[
            state_name] = Operators.lstm(self.data_dict[input_name],
                                         self.data_dict[state_name], kernel,
                                         bias, output_name, state_name)
        return output_name
Exemplo n.º 28
0
 def extract_dense(self,
                   input_name,
                   dense_name,
                   scope_id,
                   scope_name="dense"):
     self.scopes[scope_id] = scope_name
     self.scopes[scope_id + 1] = "kernel"
     kernel_name = self.generate_name(self.scopes, scope_id + 2)
     kernel = self.get_tensor(kernel_name)
     self.scopes[scope_id + 1] = "bias"
     bias_name = self.generate_name(self.scopes, scope_id + 2)
     bias = self.get_tensor(bias_name)
     layer = caffe_net.LayerParameter(name=dense_name,
                                      type='InnerProduct',
                                      bottom=[input_name],
                                      top=[dense_name])
     num_output = len(kernel[0])
     kernel = kernel.transpose((1, 0))
     layer.inner_product_param(num_output, bias_term=bias is not None)
     if bias is not None:
         if len(bias) != num_output:
             print("[ERROR] extract_dense failed")
             exit(0)
         layer.add_data(kernel, bias)
     else:
         layer.add_data(kernel)
     self.caffe_model.add_layer(layer)
     self.data_dict[dense_name] = Operators.fully_connect(
         self.data_dict[input_name], kernel.transpose((1, 0)), bias,
         dense_name)
     return dense_name
Exemplo n.º 29
0
 def add_clip(self, input_name, output_name, min_value, max_value):
     layer = caffe_net.LayerParameter(name=output_name, type='Clip',
                 bottom=[input_name],
                 top=[output_name])
     layer.clip_param(min_value, max_value)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.clip(self.data_dict[input_name], min_value, max_value, output_name)
     return output_name
Exemplo n.º 30
0
 def add_matmul(self, input_a_name, input_b_name, output_name, transpose_a=False, transpose_b=False):
     layer = caffe_net.LayerParameter(name=output_name, type='MatMul',
                 bottom=[input_a_name, input_b_name], top=[output_name])
     layer.matmul_param(transpose_a, transpose_b)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.matmul(self.data_dict[input_a_name], transpose_a,
                                       self.data_dict[input_b_name], transpose_b, output_name)
     return output_name
Exemplo n.º 31
0
 def add_reduce_mean(self, input_name, axis, keep_dim, output_name):
     operation = 4 # MEAN
     layer = caffe_net.LayerParameter(name=output_name, type='Reduction',
                 bottom=[input_name], top=[output_name])
     layer.reduction_param(operation, axis, keep_dim)
     self.caffe_model.add_layer(layer)
     self.data_dict[output_name] = Operators.reduction(self.data_dict[input_name], None, operation, axis, output_name)
     return output_name
Exemplo n.º 32
0
 def __init__(self):
     self.tokens = None
     self.current = None
     self.operators_precendence = Operators()
Exemplo n.º 33
0
class Parser:
    def __init__(self):
        self.tokens = None
        self.current = None
        self.operators_precendence = Operators()

    def next(self):
        self.current = next(self.tokens)

    def parse_number_expression(self):
        """
        numberexpr ::= number
        """
        result = NumberExpression(self.current.value)
        self.next()
        return result

    def parse_parenthesis_expression(self):
        """
        parenexpr ::= '(' expression ')'
        """
        self.next()  # consume '('
        contents = self.parse_expression()
        if self.current != ClosedParenthesisToken():
            raise ParserException("Expected ')', got " + str(self.current))
        self.next()  # consume ')'
        return contents

    def parse_expression(self):
        """
        expression ::= primary binoprhs
        """
        left = self.parse_primary_expression()
        return self.parse_binary_op(left, 0)

    def parse_binary_op(self, left, left_precedence):
        """
        binoprhs ::= (operator primary)*
        """
        while True:
            precedence = self.operators_precendence.get(self.current)
            if precedence < left_precedence:
                return left
            operator = self.current.char
            self.next()
            right = self.parse_primary_expression()
            next_precedence = self.operators_precendence.get(self.current)
            if precedence < next_precedence:
                right = self.parse_binary_op(right, precedence + 1)
            left = BinaryOperatorExpression(operator, left, right)

    def parse_if_expression(self):
        """
        ifexpr ::= 'if' expression 'then' expression 'else' expression
        """
        self.next()
        condition = self.parse_expression()
        if not isinstance(self.current, ThenToken):
            raise ParserException("Expected 'then' after if, got " + str(self.current))
        self.next()
        then_expression = self.parse_expression()
        if not isinstance(self.current, ElseToken):
            raise ParserException("Expected 'else' after if, got " + str(self.current))
        self.next()
        else_expression = self.parse_expression()
        return IfExpression(condition, then_expression, else_expression)

    def parse_for_expression(self):
        """
        forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
        """
        self.next()
        if not isinstance(self.current, IdentifierToken):
            raise ParserException("Expected identifier after 'for', got " + str(self.current))

        loop_variable = self.current.name
        self.next()
        if self.current != AssignToken():
            raise ParserException("Expected '=' after variable in for, got " + str(self.current))
        self.next()
        start = self.parse_expression()

        if self.current != CommaToken():
            raise ParserException("Expected ',' after variable start value in for, got " + str(self.current))
        self.next()

        end = self.parse_expression()

        if self.current == CommaToken():
            self.next()
            step = self.parse_expression()
        else:
            step = None

        if not isinstance(self.current, InToken):
            raise ParserException("Expected 'in' after the loop, got " + str(self.current))
        self.next()

        body = self.parse_expression()
        return ForExpression(loop_variable, start, end, step, body)

    def parse_identifier_expression(self):
        """
        identifierexpr ::= identifier | identifier '(' expression* ')'
        """
        identifier_name = self.current.name
        self.next()
        if self.current != OpenParenthesisToken():
            return VariableExpression(identifier_name)

        self.next()  # consume '('
        arguments = []
        if self.current != ClosedParenthesisToken():
            while True:
                arguments.append(self.parse_expression())
                if self.current == ClosedParenthesisToken():
                    break
                if self.current != CommaToken():
                    raise ParserException("Expected ',' or ')' in the argument list")
                self.next()
        self.next()  # consume ')'
        return FunctionCallExpression(identifier_name, arguments)

    def parse_primary_expression(self):
        """
        primary ::= identifierexpr | numberexpr | parenexpr | ifexpression | forexpression
        """
        if isinstance(self.current, IdentifierToken):
            return self.parse_identifier_expression()
        elif isinstance(self.current, NumberToken):
            return self.parse_number_expression()
        elif isinstance(self.current, IfToken):
            return self.parse_if_expression()
        elif isinstance(self.current, ForToken):
            return self.parse_for_expression()
        elif self.current == OpenParenthesisToken():
            return self.parse_parenthesis_expression()
        else:
            raise ParserException("Unknown token when parsing primary: " + str(self.current))

    def parse_prototype_expression(self):
        """
        prototype ::= id '(' id* ')'
        """
        if not isinstance(self.current, IdentifierToken):
            raise ParserException("Expected function name in prototype")
        function_name = self.current.name
        self.next()
        if self.current != OpenParenthesisToken():
            raise ParserException("Expected '(' in function prototype")
        self.next()
        argument_names = []
        while isinstance(self.current, IdentifierToken):
            argument_names.append(self.current.name)
            self.next()
        if self.current != ClosedParenthesisToken():
            raise ParserException("Expected ')' in function prototype")
        self.next()
        return PrototypeNode(function_name, argument_names)

    def parse_definition(self):
        """
        definition ::= 'def' prototype expression
        """
        self.next()
        prototype = self.parse_prototype_expression()
        expression = self.parse_expression()
        return FunctionNode(prototype, expression)

    def parse_external(self):
        """
        external ::= 'extern' prototype
        """
        self.next()
        return self.parse_prototype_expression()

    def parse_toplevel_expression(self):
        """
        toplevelexpr ::= expression
        """
        expression = self.parse_expression()
        return FunctionNode.create_anonymous(expression)

    def parse(self, string):
        """
        top ::= definition | external | expression | EOF
        """

        lexer = Lexer()
        self.tokens = lexer.tokenize(string)
        self.next()

        if isinstance(self.current, EOFToken):
            pass
        elif isinstance(self.current, DefToken):
            print('Parsed a function definition.')
            return self.parse_definition()
        elif isinstance(self.current, ExternToken):
            print('Parsed an extern.')
            return self.parse_external()
        else:
            print('Parsed a top-level expression.')
            return self.parse_toplevel_expression()

    def _flatten(self, ast):
        if isinstance(ast, NumberExpression):
            return ['Number', ast.value]
        elif isinstance(ast, VariableExpression):
            return ['Variable', ast.name]
        elif isinstance(ast, BinaryOperatorExpression):
            return ['Binop', ast.operator,
                    self._flatten(ast.left), self._flatten(ast.right)]
        elif isinstance(ast, FunctionCallExpression):
            args = [self._flatten(arg) for arg in ast.arguments]
            return ['Call', ast.function, args]
        elif isinstance(ast, PrototypeNode):
            return ['Prototype', ast.name, ' '.join(ast.arguments)]
        elif isinstance(ast, FunctionNode):
            return ['Function',
                    self._flatten(ast.prototype), self._flatten(ast.body)]
        else:
            raise TypeError('unknown type in _flatten: {0}'.format(type(ast)))
Exemplo n.º 34
0
class GalagaVariant: # tentative title

    def __init__(self):

        pygame.init()

        pygame.mixer.init()

        pygame.display.set_caption("Arithiga")

        self.screen = pygame.display.set_mode((640,480),0,32)

        self.screen.fill([0, 0, 0]) # background will be black

    # Parameter testing, not used for now
    def Parameters(self):

        # self.background_color
        # self.number_font
        # self.chosen_number_colors (array)
        # self.avatar
        # self.final_laser_choice

        selection_font = pygame.font.SysFont('arial', 20)

        intro_directions = selection_font.render("Press the n key to cycle through the options", True, (250, 50, 0), (0, 0, 0))
        intro_directions2 = selection_font.render("Press the space key to select your choice or continue", True, (250, 50, 0), (0,0,0))
        intro_directions3 = selection_font.render("To the next screen", True, (250, 50, 0), (0,0,0))

        pygame.display.flip()

        while True:

            self.screen.blit(intro_directions, (125, 100))
            self.screen.blit(intro_directions2, (75, 150))
            self.screen.blit(intro_directions3, (220, 200))
            pygame.display.flip()

            event = pygame.event.wait()

            if event.type is pygame.QUIT:
                sys.exit()

            if event.type is pygame.KEYDOWN:

                if event.key is K_SPACE:
                    break

            self.screen.fill([0,0,0])

        self.screen.fill([0,0,0])

        selection_font = pygame.font.SysFont('arial', 20)

        background_colors = [(0,0,0), (255, 212, 0), (255, 157, 255), (106, 185, 132), (255, 255, 255), (255, 255, 0)]

        which_back_color = selection_font.render("Which background color would you like to use?", True, (250, 50, 0), (0, 0, 0))

        pygame.display.flip()
        locations = [100, 200, 300, 400, 500, 600]
        option = 0
        back_color_count = 0

        while True:

            self.screen.blit(which_back_color, (100, 100))

            count = 0
            
            for color in background_colors:
                count += 1
                pygame.draw.rect(self.screen, color, pygame.Rect(100 * count, 300, 30, 30))

            pygame.draw.circle(self.screen, (255, 255, 255), (locations[option], 300), 3)
            pygame.display.update()

            event = pygame.event.wait()

            if event.type is pygame.QUIT:
                sys.exit()

            if event.type is pygame.KEYDOWN:

                if event.key is K_n:
                    self.screen.fill([0,0,0])
                    back_color_count += 1

                    if back_color_count == 6:
                        option = 0
                        back_color_count = 0

                    else:
                        option += 1

                if event.key is K_SPACE:
                    self.background_color = background_colors[option]
                    break

        self.screen.fill([0,0,0])

        font_choices = ['impact', 'arial', 'silom', 'corbel', 'optima']

        option = 0
        font_count = 0

        while True:

            event = pygame.event.wait()

            if event.type is pygame.QUIT:
                sys.exit()

            if event.type is pygame.KEYDOWN:

                if event.key is K_n:
                    self.screen.fill([0,0,0])

                    font_count += 1

                    if font_count == 5:
                        option = 0
                        font_count = 0

                    else:
                        option += 1

                if event.key is K_SPACE:
                    self.number_font = font_choices[option]
                    break

            which_font = selection_font.render("Which font do you want to use for the numbers?", True, (200, 50, 0), (0, 0, 0))

            current_font = pygame.font.SysFont(font_choices[option], 20)

            number = current_font.render('5', True, (200, 50, 0), (0, 0, 0))

            self.screen.blit(which_font, (50, 100))

            self.screen.blit(number, (300, 300))
            
            pygame.display.update()

        number_colors = [(255, 255, 255), (255, 212, 0), (255, 157, 255), (106, 185, 132), (0,0,0), (255, 255, 0), (201, 103, 255), (233, 54, 0), (0, 247, 194), (216, 164, 95), (73, 133, 246)]

        self.chosen_number_colors = []

        self.final_number_font = pygame.font.SysFont(self.number_font, 20)

        number_color_counter = 0

        for number in range(0,10):

            self.screen.fill([0,0,0])
            option = 0

            while True:

                event = pygame.event.wait()

                if event.type is pygame.QUIT:
                    sys.exit()

                if event.type is pygame.KEYDOWN:

                    if event.key is K_n:
                        self.screen.fill([0,0,0])

                        number_color_counter += 1
                        

                        if number_color_counter == 11:
                            option = 0
                            number_color_counter = 0

                        else:
                            option += 1

                    if event.key is K_SPACE:
                        self.chosen_number_colors.append(number_colors[option])
                        break

                which_number_color = selection_font.render("For each number, what color do you want?", True, (200, 50, 0), (0, 0, 0))

                self.screen.blit(which_number_color, (50, 100))

                the_number = self.final_number_font.render(str(number), True, number_colors[option], self.background_color)
                self.screen.blit(the_number, (300, 300))
                pygame.display.update()

        self.screen.fill([0,0,0])
        # Select the type of ship you want

        ship_option = pygame.image.load("galaga-ship.jpg").convert_alpha()
        bug_option = pygame.image.load("bug.jpg").convert_alpha()
        ghost_option = pygame.image.load("ghost.jpg").convert_alpha()

        avatar_options = [ship_option, bug_option, ghost_option]

        locations = [150, 300, 450]
        option = 0
        avatar_count = 0

        while True:

            which_avatar = selection_font.render("Which avatar would you like to use?", True, (200, 50, 0), (0, 0, 0))

            self.screen.blit(which_avatar, (100, 100))

            count = 0
            for avatar in avatar_options:
                count += 1
                self.screen.blit(avatar_options[count - 1], (150 * count, 300))

            pygame.draw.circle(self.screen, (255, 255, 255), (locations[option], 300), 3)

            pygame.display.flip()

            event = pygame.event.wait()

            if event.type is pygame.QUIT:
                sys.exit()

            if event.type is pygame.KEYDOWN:

                if event.key is K_n:
                    avatar_count += 1
                    if avatar_count == 3:
                        option = 0
                        avatar_count = 0

                    else:
                        option += 1

                if event.key is K_SPACE:
                    self.avatar = avatar_options[option]
                    break

            self.screen.fill([0,0,0])

        self.screen.fill([0,0,0])

        square_green_option = pygame.image.load("squaregreenlaser.png").convert_alpha()

        long_green_option = pygame.image.load("longgreenlaser.png").convert_alpha()

        square_or_long = [square_green_option, long_green_option]

        locations = [200, 400]
        option = 0
        laser_count = 0

        while True:

            which_laser = selection_font.render("Which laser would you like to use?", True, (200, 50, 0), (0, 0, 0))

            self.screen.blit(which_laser, (100, 100))

            count = 0

            for laser in square_or_long:
                count += 1
                self.screen.blit(square_or_long[count - 1], (200 * count, 300))

            pygame.draw.circle(self.screen, (255, 255, 255), (locations[option], 300), 3)

            pygame.display.flip()

            event = pygame.event.wait()

            if event.type is pygame.QUIT:
                sys.exit()

            if event.type is pygame.KEYDOWN:

                if event.key is K_n:
                    laser_count += 1
                    if laser_count == 2:
                        option = 0
                        laser_count = 0

                    else:
                        option += 1

                if event.key is K_SPACE:
                    self.laser_choice = square_or_long[option]
                    break

            self.screen.fill([0,0,0])

        if self.laser_choice is square_green_option:
            
            square_blue_option = pygame.image.load("squarebluelaser.png").convert_alpha()
            square_yellow_option = pygame.image.load("squareyellowlaser.png").convert_alpha()
            square_red_option = pygame.image.load("squareredlaser.png").convert_alpha()

            square_lasers = [square_green_option, square_blue_option, square_red_option, square_yellow_option]

            self.screen.fill([0,0,0])

            locations = [100, 200, 300, 400]
            option = 0
            laser_count = 0

            while True:

                which_color = selection_font.render("Which color would you like to use?", True, (200, 50, 0), (0, 0, 0))

                self.screen.blit(which_color, (100, 100))

                count = 1
                for color in square_lasers:
                    self.screen.blit(color, (100 * count, 300))
                    count += 1

                pygame.draw.circle(self.screen, (255, 255, 255), (locations[option], 300), 3)

                pygame.display.flip()

                event = pygame.event.wait()

                if event.type is pygame.QUIT:
                    sys.exit()

                if event.type is pygame.KEYDOWN:

                    if event.key is K_n:
                        laser_count += 1
                        if laser_count == 4:
                            option = 0
                            laser_count = 0

                        else:
                            option += 1

                    if event.key is K_SPACE:
                        self.final_laser_choice = square_lasers[option]
                        break

                self.screen.fill([0,0,0])

        elif self.laser_choice is long_green_option:
            
            long_blue_option = pygame.image.load("longbluelaser.png").convert_alpha()
            long_red_option = pygame.image.load("longredlaser.png").convert_alpha()
            long_yellow_option = pygame.image.load("longyellowlaser.png").convert_alpha()

            long_lasers = [long_green_option, long_blue_option, long_red_option, long_yellow_option]

            self.screen.fill([0,0,0])

            locations = [100, 200, 300, 400]
            option = 0
            laser_count = 0

            while True:

                which_color = selection_font.render("Which color would you like to use?", True, (200, 50, 0), (0, 0, 0))

                self.screen.blit(which_color, (100, 100))

                count = 0
                for color in long_lasers:
                    count += 1
                    self.screen.blit(long_lasers[count - 1], (100 * count, 300))

                pygame.draw.circle(self.screen, (255, 255, 255), (locations[option], 300), 3)

                pygame.display.flip()

                event = pygame.event.wait()

                if event.type is pygame.QUIT:
                    sys.exit()

                if event.type is pygame.KEYDOWN:

                    if event.key is K_n:
                        laser_count += 1
                        if laser_count == 4:
                            option = 0
                            laser_count = 0

                        else:
                            option += 1

                    if event.key is K_SPACE:
                        self.final_laser_choice = long_lasers[option]
                        break

                self.screen.fill([0,0,0])

        self.initialize()

    def initialize(self):

        # Sets up the numbers and operators that move down the screen.

        self.answer_numbers = [4, 13, 21, 34, 48, 64, 85, 110] # possible answers for game, ideally will randomize in final game

        # Creates objects for each number
        self.number_objects = []

        for number in range(1,10):

            image = self.final_number_font.render(str(number), True, self.chosen_number_colors[number])
            new_number = Numbers(self.screen, image, number, False)
            self.number_objects.append(new_number)

        plus_image = pygame.image.load("plussymbol.png").convert_alpha()
        minus_image = pygame.image.load("minussymbol.png").convert_alpha()
        multiply_image = pygame.image.load("multiplysymbol.png").convert_alpha()
        divide_image = pygame.image.load("dividesymbol.png").convert_alpha()
        power_image = pygame.image.load("caret.png").convert_alpha()

        # Creates objects for each operator (may remove minus and divide)
        self.plus = Operators(self.screen, plus_image, '+', False)
        self.minus = Operators(self.screen, minus_image, '-', False)
        self.multiply = Operators(self.screen, multiply_image, '*', False)
        self.divide = Operators(self.screen, divide_image, '/', False)
        self.power = Operators(self.screen, power_image, '^', False)

        # A lot of initializations
        self.hit_number = False

        self.hit_operator = False

        self.points = 0

        self.temporary_operator = '+' # Initalizes the operator

        self.answer_numbers_index = 0 # Defines current answer player strives for. Increments everytime the correct answer is chosen

        self.accumulating_answer = 0 # Keeps track of current value user calculates after shooting the numbers and operators.

        self.number_operators_used = 0 # Keeps track of number of operators used (for points)

        self.random_operator_count = 0  # Determines when operator will appear, spaces them out with 

        self.random_number_count = 0

        self.x = 319
        self.y = 350

        self.player_ship = Ship(self.screen, self.avatar, self.x, self.y)

        self.ships = pygame.sprite.Group()
        self.ships.add(self.player_ship)

        self.moving_numbers = pygame.sprite.Group()
        self.moving_operators = pygame.sprite.Group()
        self.moving_laser = LaserFactory(self.screen, self.final_laser_choice)

        self.introMenu()

    # Conducts operation of inputed values
    def Operation(self, temporary_operator, temporary_number_one, temporary_number_two):

        if temporary_operator == '+':
            return (temporary_number_one + temporary_number_two)
        elif temporary_operator == '-':
            return (temporary_number_one - temporary_number_two)
        elif temporary_operator == '*':
            return (temporary_number_one * temporary_number_two)
        elif temporary_operator == '/':
            return (temporary_number_one / temporary_number_two)
        else:
            return (temporary_number_one ** temporary_number_two)

    def introMenu(self):

        self.screen.fill(self.background_color)

        font = pygame.font.SysFont('impact', 40)

        text = font.render("Arithiga", True, (200, 50, 0))

        self.screen.blit(text, (250, 50))

        font2 = pygame.font.SysFont('arial', 25)
        text2 = font2.render("Press the Space to Start", True, (200, 50, 0))

        self.screen.blit(text2, (250, 240))

        pygame.display.flip()

        while True:
    
            event = pygame.event.wait()

            if event.type == pygame.QUIT:
                sys.exit()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_SPACE:
                    self.Directions()

    def endGame(self):

        self.screen.fill(self.background_color)

        end_font = pygame.font.SysFont('arial', 25)
        end_text = end_font.render("Game Over", True, (200, 50, 0))

        continue_text = end_font.render("Press f to Continue", True, (200, 50, 0))
        quit_text = end_font.render("Press q to Quit", True, (200, 50, 0))

        self.screen.blit(end_text, (310, 180))

        pygame.display.flip()

        pygame.time.wait(1100)

        self.screen.blit(continue_text, (310, 211))

        self.screen.blit(quit_text, (310, 250))

        pygame.display.flip()

        while True:

            event = pygame.event.wait()

            if event.type is pygame.KEYDOWN:

                if event.key is pygame.K_f:
                    self.initialization()

                if event.key is pygame.K_q:
                    sys.exit()

            if event.type is pygame.QUIT:
                sys.exit()

    def Directions(self):

        self.screen.fill(self.background_color)

        directions_font = pygame.font.SysFont('arial', 15)
        
        direction_text = directions_font.render("Move the Mouse to Move the Ship, Press it To Shoot A Laser", True, (200,50,0))

        direction_text2 = directions_font.render("Shoot The Numbers and Operators to Get the Given Number!", True, (200, 50, 0))

        direction_text3 = directions_font.render("The Less Operators You Use, the More Points You'll Get", True, (200,50,0))

        direction_text4 = directions_font.render("You Have Three Lives", True, (200, 50, 0))

        self.screen.blit(direction_text, (100, 140))

        self.screen.blit(direction_text2, (100, 160))

        self.screen.blit(direction_text3, (100, 180))

        self.screen.blit(direction_text4, (100, 200))

        pygame.display.flip()

        while True:
    
            event = pygame.event.wait()

            if event.type == pygame.QUIT:
                sys.exit()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_SPACE:
                    self.run()

    # Updates info on top of the screen.
    def changeInfo(self):

        info_font = pygame.font.SysFont('arial', 18)
        answer_text = info_font.render("Current Number: " + str(self.answer_numbers[self.answer_numbers_index]), True, (200, 50, 0))

        self.screen.blit(answer_text, (325, 40))

        number_of_lives_text = info_font.render("Current Lives: " + str(self.player_ship.CurrentLives()), True, (200,50,0))
        self.screen.blit(number_of_lives_text, (180, 40))

        accumulating_text = info_font.render("Current Result: " + str(self.accumulating_answer), True, (200, 50, 0))

        self.screen.blit(accumulating_text, (25, 40))

        points_text = info_font.render("Current Points: " + str(self.points), True, (200,50,0))
        self.screen.blit(points_text, (490, 40))

    # Runs the game
    def run(self):

        pygame.time.set_timer(pygame.USEREVENT, 50)

        self.screen.fill(self.background_color)

        while True:

            event = pygame.event.wait()

            if event.type is pygame.QUIT:
                print 'quit'
                sys.exit()

            # Movement of mouse determines movement of spaceship
            if event.type is pygame.MOUSEMOTION:
                self.x, self.y = pygame.mouse.get_pos()
                self.player_ship.update(self.x, self.y)

            # Determines shooting the laser
            if event.type is pygame.MOUSEBUTTONDOWN:

                self.moving_laser.NewLaser(self.player_ship.XPosition(), self.player_ship.YPosition())
            
            if event.type is not pygame.USEREVENT:
                continue

            for laser in self.moving_laser.getLasers():

                if laser.YPosition() == 80:
                    self.moving_laser.getLasers().remove(laser)

                else:
                    laser.update()

            random_value = int(random() * 9.9)  # Randomizes what number appears at the top
            
            random_operator = random() * 5  # Randomizes what operator appears at the top

            start_position_operator = 610.0 * random() # Randomizes where the number will appear at the top

            start_position_number = 610.0 * random() # Randomizes where the operator will appear at the top

            # For loop instead?

            self.random_number_count += 1
                
            # Series of if-else statements to initalize movment of a number given the random value

            if self.random_number_count == 4:

                self.random_number_count = 0

                if (not self.number_objects[random_value].moving()):
                    self.number_objects[random_value].setXPosition(start_position_number)
                    self.moving_numbers.add(self.number_objects[random_value])
                    self.number_objects[random_value].toggle()

            for number in self.moving_numbers:

                if number.YPosition() > 480:
                    number.reset()
                    self.moving_numbers.remove(number)
                    number.toggle()
                    
                else:
                    number.update()

            self.random_operator_count += 1  # Increments count

            # Initalizes movement of an operator everytime random_operator_count is 3
            if self.random_operator_count == 6:

                self.random_operator_count = 0

                if (not self.plus.moving()) and random_operator > 0 and random_operator <= 1:
                    self.plus.setXPosition(start_position_operator)
                    self.moving_operators.add(self.plus)
                    self.plus.toggle()

                elif (not self.minus.moving()) and random_operator > 1 and random_operator <= 2:
                    self.minus.setXPosition(start_position_operator)
                    self.moving_operators.add(self.minus)
                    self.minus.toggle()

                elif (not self.multiply.moving()) and random_operator > 2 and random_operator <= 3:
                    self.multiply.setXPosition(start_position_operator)
                    self.moving_operators.add(self.multiply)
                    self.multiply.toggle()

                elif (not self.divide.moving()) and random_operator > 3 and random_operator <= 4:
                    self.divide.setXPosition(start_position_operator)
                    self.moving_operators.add(self.divide)
                    self.divide.toggle()

                elif (not self.power.moving()) and random_operator > 4 and random_operator <= 5:
                    self.power.setXPosition(start_position_operator)
                    self.moving_operators.add(self.power)
                    self.power.toggle()

            for operator in self.moving_operators:

                if operator.YPosition() > 480:
                    operator.reset()
                    self.moving_operators.remove(operator)
                    operator.toggle()

                else:
                    operator.update()


            # Take into account the first number that is shot, should only occur once
            # For every answer
            if ((not self.hit_number) and (not self.hit_operator)):

                for laser in self.moving_laser.getLasers():
                    
                   laser_number_collision = pygame.sprite.spritecollide(laser, self.moving_numbers, True)

                   for number in laser_number_collision:
                       self.moving_laser.getLasers().remove(laser)
                       self.accumulating_answer = number.getValue()
                       number.reset()
                       number.toggle()
                       self.hit_number = True

            # Shoots operator after hit the number
            elif self.hit_number:

                if not self.hit_operator:

                    for laser in self.moving_laser.getLasers():

                        laser_operator_collision = pygame.sprite.spritecollide(laser, self.moving_operators, True)
                          
                        for operator in laser_operator_collision:
                            operator.toggle()
                            operator.reset()
                            self.moving_laser.getLasers().remove(laser)
                            self.temporary_operator = operator.getOperator()
                            self.hit_operator = True
                            self.number_operators_used += 1

                # Shoot another number
                elif self.hit_operator:

                    for laser in self.moving_laser.getLasers():
                            
                        laser_number_collision = pygame.sprite.spritecollide(laser, self.moving_numbers, True)

                        for number in laser_number_collision:
                           self.moving_laser.getLasers().remove(laser)
                           self.accumulating_answer = self.Operation(self.temporary_operator, self.accumulating_answer, number.getValue())
                           number.reset()
                           number.toggle()
                           self.hit_operator = False  # Only changes operator to false so user can build upon the accumulating number

            # Moves on to the next number as an answer if the accumulating_answer equals to the given number.
            # Calculates points depending on how many operators are used.
            if self.accumulating_answer == self.answer_numbers[self.answer_numbers_index]:

                self.accumulating_answer = 0

                self.answer_numbers_index += 1

                self.hit_number = False

                if (self.number_operators_used > 0) and (self.number_operators_used <= 2):
                    self.points += 100

                elif (self.number_operators_used > 2) and (self.number_operators_used <= 5):
                    self.points += 50

                else:
                    self.points += 25

                # Reduce the number of lives everytime the ship hits a number or operator
            ship_number_collisions = pygame.sprite.spritecollide(self.player_ship, self.moving_numbers, True)

            for number in ship_number_collisions:

                print self.player_ship.CurrentLives()
                self.player_ship.ReduceLives()
                number.toggle()
                number.reset()
                self.moving_numbers.remove(number)
                self.accumulating_answer = 0
                self.hit_number = False
                self.hit_operator = False

                pygame.time.delay(1000)
                self.x = 319
                self.y = 350

                # Reduce the number of lives everytime the ship hits a number or operator
            ship_operator_collisions = pygame.sprite.spritecollide(self.player_ship, self.moving_operators, True)

            for operator in ship_operator_collisions:
                print self.player_ship.CurrentLives()
                self.player_ship.ReduceLives()
                self.accumulating_answer = 0
                operator.toggle()
                operator.reset()
                self.moving_operators.remove(operator)
                self.hit_number = False
                self.hit_operator = False

                pygame.time.delay(1000)
                self.x = 319
                self.y = 350

            # Ends game when the player runs out of lives
            if self.player_ship.CurrentLives() == 0:
                break

            self.ships.draw(self.screen)
            self.moving_numbers.draw(self.screen)
            self.moving_operators.draw(self.screen)
            self.moving_laser.getLasers().draw(self.screen)

            self.changeInfo()

            pygame.display.flip()

            self.screen.fill(self.background_color)

        self.endGame()