Example #1
0
class DanceCV():
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input, speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)

        
        
    def run(self):
        while True:
            for events in pygame.event.get():
                if events.type == QUIT:
                    sys.exit(0)
            self.input.run()
            self.scene.run()
            pygame.display.update()
            self.clock.tick(30)
Example #2
0
def ocr(caminho_imagem=config.caminho_imagem_entrada):
    seg = Segmentar()
    array_texto = seg.segmentar_imagem(caminho_imagem=caminho_imagem,
                                       inverter_imagem=config.letra_cor_preta)
    texto = ''

    inp = Input()
    iterator = inp.pegar_batch(pasta_dados='./Data/Letra/')
    imagens = iterator.get_next()

    cnn = RedeNeural()
    logits = cnn.construir_arquitetura(imagens)
    id_letra = _decode_one_hot(logits)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(iterator.initializer)
        saver = tf.train.Saver()
        saver.restore(sess, './Output/model.ckpt')
        for linha in array_texto:
            for palavra in linha:
                for _ in palavra:
                    saida = sess.run(id_letra)
                    letra_predicao = retornar_letra(saida[0])
                    texto += letra_predicao
                texto += ' '
            texto += '\n'

    _criar_arquivo_text(texto)
Example #3
0
def inputProcessor(listOfTraitsForEachFile, listOfFiles, firstRunFlag,
                   dictToImplement):
    for attr in listOfTraitsForEachFile:  # This part will generate input files for reactants and products
        filename = attr[0]
        template = attr[2]
        basename = attr[1]

        # =(self.filename, self.basename, inCounter, self.template, newDict)

        ## newDict is the dictionary we want to implement.
        ## self.template is a string of the lines of the user input file untill the first **** line.
        if firstRunFlag:
            listOfFiles.append(filename)
        else:
            inp = Input(filename, basename, inCounter, template,
                        dictToImplement)
            rvalues = inp.modify()
            """ This meathod creates a new input file and return a list of 3 or 2 organs:
                1) The dictionary that pulled to the new file.
                2) The name of the new file.
                3) String of the lines of the user input file untill the first **** line.
                * If it is not the first run, organ 3 dissmissed.
            """
            listOfFiles.append(rvalues[1])
            return (inp)
Example #4
0
class DanceCV():
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode(
            (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input,
                               speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)

    def run(self):
        while True:
            for events in pygame.event.get():
                if events.type == QUIT:
                    sys.exit(0)
            self.input.run()
            self.scene.run()
            pygame.display.update()
            self.clock.tick(30)
    def update(self):
        self.__update__()
        w = HeaderCustomize(self.titulo)
        w.slider = self.slider
        w._atras = self._atras
        w._screen = self._screen
        self.add(w)
        w = MediaManager("Logo")
        w.btn2 = "Elegir logo"
        w.btn1 = "Eliminar logo"
        w.Media = self.Media
        w.placeholder = "No se a elegido un logo"
        self.add(w)

        w = Input("Titulo del sitio")
        self.add(w)
        w = Input("Descripción corta")
        self.add(w)
        w = CheckBox("Muestra el título y descripción del sitio")
        self.add(w)

        w = MediaManager("Icono del sitio")
        w.descripcion = """
		El icono del sitio lo usa el navegador 
		como icono de la aplicación para tu sitio. 
		Los iconos deben ser cuadrados y al menos de 512 píxeles de ancho y alto.
		"""
        w.placeholder = "No se a elegido un logo"
        w.Media = self.Media
        self.add(w)
        self.css({
            "padding-left": "20px",
            "padding-right": "20px"
        }, None, ">div:nth-child(n+2)")
Example #6
0
 def __init__(self, toSort = None):
     input = Input(toSort)
     self.toSort = list(input.getArray())
     self.sorted = list(input.getArray())
     self.newPositions = []
     for i in range(len(self.toSort)):
         self.newPositions.append(i)
Example #7
0
def avaliar():
    inp = Input()
    iterator = inp.pegar_batch(tamanho_batch=config.batch_size,
                               pasta_dados="./Data/Testar")
    imagens, labels = iterator.get_next()

    print("shape img: {}".format(imagens.get_shape().as_list()))

    cnn = RedeNeural()

    logits = cnn.construir_arquitetura(imagens)

    accuracy = cnn.accuracy(logits, labels)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(iterator.initializer)
        total_batch = 128 // config.batch_size
        avg_acc = 0.
        saver = tf.train.Saver()
        sess.run(tf.global_variables_initializer())
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        saver.restore(
            sess,
            './Output/model.ckpt')  # /home/samuelehp04/TCC/Output/model.ckpt
        for batch in range(total_batch):
            acc = sess.run(accuracy)
            avg_acc += acc / total_batch
        print("Precisao: {:.5f}".format(avg_acc))
        coord.request_stop()
        coord.join(threads)
Example #8
0
class Game():
    def __init__(self):
        random.seed()
        self.input = Input()
        self.notemanager = NoteManager()
        self.zither = Zither()
        self.timer = 0
        self.font = pygame.font.Font(None, 64)
        self.score = 0

    def render(self, screen):
        score_ = self.font.render("Score: " + str(self.score), 0,
                                  pygame.Color(255, 255, 255))
        screen.blit(score_, (0, 0))
        self.zither.render(screen)
        self.notemanager.render(screen)

    def update(self, dt):
        self.timer += dt
        if (self.timer >= 1000):
            random_ = random.randint(0, 10)
            if (random_ < 7):
                button = self.zither.getBigButton(random_)
            else:
                button = self.zither.getSmallButton(random_)
            self.notemanager.spawn(button.getX(), button.getColor(), random_)
            self.timer = 0
        self.input.update()
        self.zither.update(dt, self.input)
        self.score += self.notemanager.update(dt, self.zither)
Example #9
0
def handleFile0(filename):
    print filename,'\n'
    basename = ".".join(filename.split('/')[-1].split('.')[:-1])
    inp = Input(filename, basename, inCounter) # Initializing an object of Input module
    rvalues = inp.modify();del inp

    #return structure:  ([name of new file(filename),basename,template of file, dictionary of this file])
    return ([rvalues[1],basename,rvalues[2],rvalues[0]])
 def __init__(self):
     self._window = None
     self._graphics = None
     self._sprite = None 
     self._running = True
     self._renderer = SDL_Renderer()
     self._player = None
     self._input = Input() 
Example #11
0
 def __init__(self):
     random.seed()
     self.input = Input()
     self.notemanager = NoteManager()
     self.zither = Zither()
     self.timer = 0
     self.font = pygame.font.Font(None, 64)
     self.score = 0
Example #12
0
 def __init__(self):
     self.input = Input()
     pygame.init()
     pygame.display.set_mode(
         (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
     pygame.display.set_caption("color-based-multi-person-id-tracker")
     screen = pygame.display.get_surface()
     self.output = Output(screen, self.input)
Example #13
0
 def __init__(self):
     self.input = Input()
     pygame.init()
     pygame.display.set_mode(
         (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
     pygame.display.set_caption("Twister!")
     screen = pygame.display.get_surface()
     self.scene = Scene(screen, self.input)
Example #14
0
 def __init__(self):
     """
     creates a new program
     """
     self.input = Input()
     self.output = Output()
     self.inventory = Inventory()
     self.choice = None
def runTest():
    """runTest creates an Input object and Retangle object and runs the test"""
    data = Input()  #create Input obj
    length = data.getNumber(
        'Enter length of rectangle: ')  #Use Input obj to get data with prompt
    width = data.getNumber(
        'Enter width of rectangle: ')  #Use Input obj to get data with prompt
    rec = Retangle(length,
                   width)  #Create a Rectangle obj with length and width
    print('The area of the retangle is {}'.format(rec.computeArea()))
Example #16
0
 def __init__(self):
     pygame.init()
     pygame.display.set_icon(
         pygame.transform.scale(functions.load_image(GAME_ICON), (32, 32)))
     pygame.display.set_caption('Python-Game')
     self.playerObj = Player.Player()
     self.audioObj = Audio.GameAudio()
     self.inputObj = Input()
     self._log = logging.getLogger(__name__)
     self._log.debug('Initialized Game')
Example #17
0
 def benchmark(self, path, content, benchmarks, sample, maxTokens, filters):
     self._resetFile(path)
     logFile = Logger.logFile('log')
     wordList = self._parse(path, content, False)
     lines = self._getLines(content)
     lineIndex = 0
     tokensTested = 0
     for index, (word, loc, node) in enumerate(wordList):
         # Go backwards so we can use last prediction and input in subsequent
         # logging code
         if tokensTested >= maxTokens:
             return tokensTested
         while (loc > lines[lineIndex][1] + len(lines[lineIndex][0])):
             lineIndex += 1
         lineStart = lines[lineIndex][1]
         linePrefix = content[lineStart:loc]
         if self.benchmarkCounter % sample == 0 and \
            (not filters.onlySeen or word in self.words) and \
            len(word) >= filters.minWordLength and \
            not ('#' in linePrefix or '//' in linePrefix) and \
            (not filters.onlyIdentifiers or tokenizer.isIdentifier(word)):
             prediction = []
             for prefixSize in range(PREFIX_SIZE, -1, -1):
                 input = AnnotatedInput(
                     Input(path, content, loc, word[:prefixSize], -1),
                     wordList, index, lines, lineIndex)
                 prediction = self._predictAnnotated(input)
                 for benchmark in benchmarks:
                     benchmark.update(prediction, word, prefixSize)
             doLogging = True
             if filters.inFirst != -1:
                 predictedWords = [
                     w for (w, p) in prediction[:filters.inFirst]
                 ]
                 if word not in predictedWords:
                     doLogging = False
             if filters.notInFirst != -1:
                 predictedWords = [
                     w for (w, p) in prediction[:filters.notInFirst]
                 ]
                 if word in predictedWords:
                     doLogging = False
             if doLogging:
                 self._logPrediction(input, prediction, word)
                 tokensTested += 1
         else:
             input = AnnotatedInput(Input(path, content, loc, '', -1),
                                    wordList, index, lines, lineIndex)
         self.words.add(word)
         self._trainOneWord(input, word, False, True)
         self.tokensTrained += 1
         self.benchmarkCounter += 1
     return tokensTested
Example #18
0
class PoseTracking():
    def __init__(self, mode):
        if mode == 'local' or mode == 'Local' or mode =='LOCAL':
            print("Running in a local video...")
            self.input = Input()
            self.mode = 1

        elif mode == 'reatime' or mode == 'RealTime' or mode =='realTime' or mode =='Realtime' or mode =='REALTIME':
            self.input = Input()
            pygame.init()
            pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
            pygame.display.set_caption("PoseTracking!")
            screen = pygame.display.get_surface()
            self.scene = Scene(screen, self.input)
            self.mode = 0

    def run(self):
        
        while True:
            # To run the algorithm
            self.input.run()

            # Showing the scene
            self.scene.run()

    def run_local(self, data_input, data_output, speed = 30):
        # Opens the Video file
        cap = cv2.VideoCapture(data_input)

        # Abrindo o video e passando cada frame como parametro
        frames_array = []
        get_par = 0
        while(cap.isOpened()):
            ret, frame = cap.read()
            if ret == False:
                break
            # Getting video parameters
            if get_par == 0:
                height, width, layers = frame.shape
                size = (width,height)
                get_par = 1

            self.input.run_local(ret, frame, frames_array)
            if ret == False:
                break
        
        # Saving all frames as a video
        out = cv2.VideoWriter(data_output,cv2.VideoWriter_fourcc(*'DIVX'), speed, size)
 
        for i in range(len(frames_array)):
            out.write(frames_array[i])
        out.release()
Example #19
0
class Twister():
    # Define uma janela onde os videos serao colocados como input
    # Verificar se ele usa o opencv para fazer isso
    def __init__(self):
        self.input = Input()
        pygame.init()

    #    pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
    #    pygame.display.set_caption("Twister!")
    #    screen = pygame.display.get_surface()
    #    self.scene = Scene(screen, self.input)

    def run(self):

        while True:
            # Aqui no input.run() que o algoritmo começa a funcionar de verdade
            self.input.run()

            # Aqui eu renderizo o resultado da cena
            self.scene.run()

    def run_local(self):
        # Opens the Video file
        cap = cv2.VideoCapture('./data/input/v1_small.mp4')

        # Abrindo o video e passando cada frame como parametro
        frames_array = []
        get_par = 0
        while (cap.isOpened()):
            ret, frame = cap.read()
            if ret == False:
                break

            # Getting video parameters
            if get_par == 0:
                height, width, layers = frame.shape
                size = (width, height)
                get_par = 1

            self.input.run_local(ret, frame, frames_array)
            if ret == False:
                break

        # Saving all frames as a video
        out = cv2.VideoWriter('./data/output/result_small.avi',
                              cv2.VideoWriter_fourcc(*'DIVX'), 30, size)

        for i in range(len(frames_array)):
            out.write(frames_array[i])
        out.release()
Example #20
0
    def __init__(self, mode):
        if mode == 'local' or mode == 'Local' or mode =='LOCAL':
            print("Running in a local video...")
            self.input = Input()
            self.mode = 1

        elif mode == 'reatime' or mode == 'RealTime' or mode =='realTime' or mode =='Realtime' or mode =='REALTIME':
            self.input = Input()
            pygame.init()
            pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
            pygame.display.set_caption("PoseTracking!")
            screen = pygame.display.get_surface()
            self.scene = Scene(screen, self.input)
            self.mode = 0
Example #21
0
    def use(self, name=None):

        Input.bind(name) if name else Input.bind(self.name)


# Functions implementing key actions should contain:
# 1. an action:
# press or release    e.g pressKeyA or releaseKeyA

# 2. an identifier:
# KeyA ... KeyZ  For alphabetic keys    e.g pressKeyA(self, mods)
# Num0 ... Num9  For Numpad keys        e.g pressNum0(self, mods)
# Key0 ... Key9                         e.g pressKey0(self, mods)
# Enter, Esc, Space
Example #22
0
def transactionFromByteArray(trans_data):
    offset = 0
    in_arr = []
    out_arr = []
    no_of_input = int.from_bytes(trans_data[:4], 'big')
    offset += 4
    for i in range(no_of_input):
        trans_ID = trans_data[offset:offset + 32].hex()
        offset += 32
        index = int.from_bytes(trans_data[offset:offset + 4], 'big')
        offset += 4
        sign_len = int.from_bytes(trans_data[offset:offset + 4], 'big')
        offset += 4
        sign = trans_data[offset:offset + sign_len].hex()
        offset += sign_len
        inp_obj = Input(trans_ID, index, sign)
        in_arr.append(inp_obj)

    no_of_output = int.from_bytes(trans_data[offset:offset + 4], 'big')
    offset += 4
    for i in range(no_of_output):
        coins = int.from_bytes(trans_data[offset:offset + 8], 'big')
        offset += 8
        key_len = int.from_bytes(trans_data[offset:offset + 4], 'big')
        offset += 4
        key = trans_data[offset:offset + key_len].decode()
        offset += key_len
        out_obj = Output(coins, key)
        out_arr.append(out_obj)
    return [in_arr, out_arr]
Example #23
0
    def train(self,
              path,
              content,
              maxTokens=sys.maxint,
              weightTraining=False,
              sample=1):
        # FixMe: [usability] Add file name as suggestion
        wordList = self._parse(path, content, not weightTraining)
        lines = self._getLines(content)
        self.tokensTrained += min(len(wordList), maxTokens)

        self._resetFile(path)
        lineIndex = 0
        tokensTrained = 0
        for index, (word, loc, node) in enumerate(wordList):
            if tokensTrained >= maxTokens:
                return tokensTrained
            while (loc > lines[lineIndex][1] + len(lines[lineIndex][0])):
                lineIndex += 1
            input = AnnotatedInput(Input(path, content, loc, "", -1), wordList,
                                   index, lines, lineIndex)
            weightTrain = False
            if self.trainingCounter % sample == 0:
                tokensTrained += 1
                weightTrain = weightTraining
            self._trainOneWord(input, word, weightTrain, False)
            self.trainingCounter += 1
        return tokensTrained
Example #24
0
 def test_decline_card(self):
     self.decliner = Input([
         'Add Tom 4111111111111111 $1000', 'Charge Tom $650',
         'Charge Tom $800'
     ])
     val = self.decliner.card_book['Tom'].get_balance()
     self.assertEqual(val, 650)
Example #25
0
 def test_charge_credit_account(self):
     self.inputter = Input([
         'Add Lisa 5454545454545454 $3000', 'Charge Lisa $8',
         'Credit Lisa $100'
     ], )
     value = self.inputter.card_book['Lisa'].get_balance()
     self.assertEqual(value, -92)
Example #26
0
 def test_same_input(self):
     input_line = [
         'Add Kshitij 79927398713 $6000', 'Add Kshitij 79927398713 $6000'
     ]
     processor = Input(input_line)
     output = processor.card_book
     self.assertEqual(len(processor.card_book), 1)
Example #27
0
 def radio(self, **kwds):
     from Input import Input
     control = Input(type="radio", **kwds)
     from FormField import FormField
     field = FormField(control)
     self.contents.append(field)
     return control
Example #28
0
	def done(self):

		self.BasicTabs.width="100%"
		self.BasicTabs.tabWidth="100%"
		self.BasicTabs.update()
		i=Input("Titulo:")
		t=TinyMCE("Contenido:")
		t.data=self.dataChildren[1]


		if "value" in self.dataChildren[1]:
			t.value=self.dataChildren[1]["value"]

		



		s.when(self.target3.html(self.BasicTabs.target)).then(self.BasicTabs.done)
		self.BasicTabs.appendToTab(0,i)
		self.BasicTabs.appendToTab(0,t)
		

		
		
		
		self.target.find(">button").on("click",self.insertar)
		self.target2.find(">button").find(">.titulo").text("prueba")
		self.target2.find(">button").on("click",self.open)
		
		
		self.__titulo=self.target.find(">button").find(">.titulo")
		self.titulo(self._titulo)

		t.reconectar()
Example #29
0
    def load_input(self, assignment, input_conf):
        if self._03_prob_type == AgGlobals.PROBLEM_TYPE_PROG and AgGlobals.is_flags_set(
                self._99_state, AgGlobals.PROBLEM_STATE_LOADED):
            # Check whether the input configuration file exists.
            self._99_state = AgGlobals.clear_flags(
                self._99_state, AgGlobals.PROBLEM_STATE_INPUTS_LOADED)
            if not os.path.exists(input_conf):
                print '\Input configuration file {} does not exist, exit...'.format(
                    input_conf)
                sys.exit()

            self._99_inputs = {}

            for io in sorted(self._07_inp_outps):
                self._99_inputs[io] = Input(self._07_inp_outps[io][0],
                                            self._07_inp_outps[io][1])

                section = AgGlobals.get_input_section(assignment,
                                                      self._01_prob_no, io)
                self._99_inputs[io].load_input(input_conf, section)

            self._99_state = AgGlobals.set_flags(
                self._99_state, AgGlobals.PROBLEM_STATE_INPUTS_LOADED)

            return True

        return False
 def predict(self,newData):
     self.NLP_.logger_.debug("Starting Model prediction ")
     import pandas as pd
     import numpy as np
     self.predictionReport_=Report()
     self.newInput_=Input(self.input_.databaseName_,newData,self.input_.dependentVariableName_)
     self.newDataSet_=self.newInput_.readMongoData()
     self.NLP_.Header_.remove(self.input_.dependentVariableName_)     
     self.newData_=self.newDataSet_[self.NLP_.Header_].copy()
     self.newData_ = pd.get_dummies(self.newData_,drop_first=False)
     self.newData_=self.newData_.reindex(columns=list(self.NLP_.X_train_.columns),fill_value=0)
     
     for key in self.bestModels_:
         self.predictionReport_.insertPredictionResults([key,int(self.bestModels_[key].predict(self.newData_)),int(np.round(self.bestModels_[key].predict_proba(self.newData_)[0][0],2)*100),int(np.round(self.bestModels_[key].predict_proba(self.newData_)[0][1],2)*100)])              
     print(self.predictionReport_.predictionReport_)
     self.NLP_.logger_.debug("Ending Model prediction. Good Bye")
Example #31
0
    def generate_input_config(self, assignment, in_out_dir, cfg):
        if self._03_prob_type == AgGlobals.PROBLEM_TYPE_PROG and AgGlobals.is_flags_set(
                self._99_state, AgGlobals.PROBLEM_STATE_LOADED):
            for io in sorted(self._07_inp_outps):
                # print io, self._07_inp_outps[io]
                section = AgGlobals.get_input_section(assignment,
                                                      self._01_prob_no, io)

                # if "['{}']".format( section ) in cfg.sections():
                #    print 'Error: Input configuration section: {} already exists. Did not overwrite'.format( section )
                #    return
                cfg.add_section(section)

                temp_in = Input(self._07_inp_outps[io][0],
                                self._07_inp_outps[io][1])
                for key in sorted(temp_in.__dict__.keys()):
                    # Filter only the instances variables that are necessary for the configuration file
                    if key[0:4] != '_99_':
                        cfg.set(section, key[3:],
                                ' {}'.format(temp_in.__dict__[key]))

                if self._07_inp_outps[io][0] == AgGlobals.INPUT_NATURE_LONG:
                    input_file_path = os.path.join(
                        in_out_dir,
                        AgGlobals.get_input_file_name(assignment,
                                                      self._01_prob_no, io))
                    cfg.set(section, 'input_file', input_file_path)
                    fo = open(input_file_path, 'a')
                    fo.close()
Example #32
0
 def testEraseBug(self):
     self.input=Input([["param","c3","x4"]])
     gen=self.input.populate()
     try:
         gen.next()
     except StopIteration:
         pass
     assert self.input.name=="c3",self.input.name
Example #33
0
 def getC1(self):
     test1="""\
     param <%ArrayList<point>%> c1:
         valid 0:
                 <% %c1%=null;%>
         valid 1:
                  <% %c1%=null;%>
         invalid 0:
            c1 < 5
            c1 > 3
     """
     c1=Input(tokens=self.parser.input.parseString(test1)[0])
     try:
         c1.populate().next()
     except StopIteration:
         pass
     else:
         self.fail('Why has execution stopped')
     return c1
Example #34
0
 def __init__(self, question, parent, answer_var):
     self.width = 400
     self.height = 200
     self.parent = parent
     self.x = (parent.get_width() - self.width) / 2.0
     self.y = (parent.get_height() - self.height) / 2.0
     self.text = question
     answer_var = "LOL"
     Window.__init__(self, self.x, self.y, self.width, self.height, parent, "Ask", True)
     self.q_label = Button(20, 50, self.text, self.surface, (255, 255, 255), hpad=0)
     self.a_input = Input(20, 80, 360)
Example #35
0
class Ask(Window):
    def __init__(self, question, parent, answer_var):
        self.width = 400
        self.height = 200
        self.parent = parent
        self.x = (parent.get_width() - self.width) / 2.0
        self.y = (parent.get_height() - self.height) / 2.0
        self.text = question
        answer_var = "LOL"
        Window.__init__(self, self.x, self.y, self.width, self.height, parent, "Ask", True)
        self.q_label = Button(20, 50, self.text, self.surface, (255, 255, 255), hpad=0)
        self.a_input = Input(20, 80, 360)

    def draw(self):
        self.q_label.draw(self.surface)
        self.a_input.draw(self.surface)
        Window.draw(self)

    def update(self, mouseclick, scrolldown=False, scrollup=False, keypressed=""):
        self.a_input.update(self.x + self.a_input.x, self.y + self.a_input.y, mouseclick, keypressed)
        Window.update(self, mouseclick, scrolldown=False, scrollup=False, keypressed="")
Example #36
0
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input, speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)
Example #37
0
 def setUp(self):
     """Call before every test case."""
     self.parser = Parser()
     self.input = None
     self.input = Input()
Example #38
0
'''
Created on Sep 23, 2015

@author: daleinen
'''

from Input import Input
from Game import Game
    
#printing a welcome message
welcome_message = "\nWelcome to JackBlack's BlackSnake BlackJack Simulator 1.0!\n"
print(welcome_message)

#instance of input class
my_input = Input()

#while true loop to gather user inputs
while True:
    #getting and setting user variables
    deck_num = my_input.getNumDecks()
    table_min = my_input.getTableMin()
    start_amount = my_input.getStrAmnt()
    stop_amount = my_input.getStpAmnt(start_amount)
    my_sessions = my_input.getSess()
    
    print "\nAre these amounts correct?"
    print "Deck number: %s" % (deck_num)
    print "Table min: %s" % (table_min)
    print "Start amount: %s" % (start_amount)
    print "Stop amount: %s" % (stop_amount)
    print "Sessions: %s" % (my_sessions)
Example #39
0
def main():

    # Determine assets
    sprite_asset, bullet_sound_asset = DetermineAssets()

    # Load sprite assets
    IMAGESDICT, animObjs = LoadSpriteAssets(sprite_asset)

    # Main game surface
    DISPLAYSURF = pygame.display.set_mode((SCREEN_X, SCREEN_Y)) #Make the screen

    # Colors
    BLACK = (0,0,0)

    # Calculate starting position of player
    startX = SCREEN_X - LEN_SPRT_X
    startY = SCREEN_Y - LEN_SPRT_Y

    # Hold info on keys pressed, held, released
    keyinput = Input()

    # Initialize gamemap and Player
    player = Player(IMAGESDICT, animObjs, bullet_sound_asset)
    player.rect.topleft = startX, startY

    # Add tiles
    startx = 0
    starty = SCREEN_Y - LEN_SPRT_Y/2
    tile = Tile(IMAGESDICT['ground'])
    tile.rect.topleft = startx, starty

    # Sprite Groups
    allsprites = pygame.sprite.RenderPlain(player)
    environment = pygame.sprite.RenderPlain(tile)

    # Start game loop
    while True:
        # Clear key info
        keyinput.clearKeys()

        # Draw screen black
        DISPLAYSURF.fill(BLACK)

        # Check for game events
        for event in pygame.event.get():
            # Reset player direction
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # Handle key presses
                keyinput.keyDownEvent(event.key)
            elif event.type == KEYUP:
                keyinput.keyUpEvent(event.key)

        # Player horizontal logic
        if keyinput.isKeyHeld(K_LEFT) and keyinput.isKeyHeld(K_RIGHT):
            player.stopMoving()
        elif keyinput.isKeyHeld(K_LEFT):
            player.moveLeft()
        elif keyinput.isKeyHeld(K_RIGHT):
            player.moveRight()
        elif keyinput.wasKeyPressed(K_SPACE):
            # Play player shooting animation
            player.shoot()
        elif keyinput.wasKeyPressed(K_ESCAPE):
            pygame.quit()
            sys.exit()
        elif not player.shooting:
            player.stopMoving()

        # Vertical logic
        if keyinput.wasKeyPressed(K_UP):
            player.jump()

        # Check for collisions between player and environment
        collision_list = pygame.sprite.spritecollide(player, environment, False)

        # Update
        allsprites.update()
        environment.update()

        # Draw
        allsprites.draw(DISPLAYSURF)
        environment.draw(DISPLAYSURF)

        pygame.display.update()
        fpsClock.tick(FPS)
Example #40
0
class GameEngine(Engine):
    """The main game engine."""
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
                # evilynux - With self.audio.close(), calling self.quit() results in
                #            a crash. Calling the parent directly as a workaround.
            Engine.quit(self)

    def quit(self):
        self.audio.close()
        Engine.quit(self)

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.img.setGeometry((0, 0, width, height))

    def isServerRunning(self):
        return bool(self.server)

    def startServer(self):
        """Start the game server."""
        if not self.server:
            Log.debug("Starting server.")
            self.server = Server(self)
            self.addTask(self.server, synchronized = False)

    def connect(self, host):
        """
        Connect to a game server.

        @param host:  Name of host to connect to
        @return:      L{Session} connected to remote server
        """
        Log.debug("Connecting to host %s." % host)
        session = ClientSession(self)
        session.connect(host)
        self.addTask(session, synchronized = False)
        self.sessions.append(session)
        return session

    def stopServer(self):
        """Stop the game server."""
        if self.server:
            Log.debug("Stopping server.")
            self.removeTask(self.server)
            self.server = None

    def disconnect(self, session):
        """
        Disconnect a L{Session}

        param session:    L{Session} to disconnect
        """
        if session in self.sessions:
            Log.debug("Disconnecting.")
            self.removeTask(session)
            self.sessions.remove(session)

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize  Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""
        done = Engine.run(self)
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.img.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        # Tune the scheduler priority so that transitions are as smooth as possible
        if self.view.isTransitionInProgress():
            self.boostBackgroundThreads(False)
        else:
            self.boostBackgroundThreads(True)

        done = Engine.run(self)
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        return done

    def run(self):
        try:
            return self.mainloop()
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            Log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
Example #41
0
class GameEngine(object):
    """The main game engine."""
    def __init__(self, config = None):

        Log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None    #placeholder for main menu object - to prevent reinstantiation

        self.createdGuitarScene = False   #MFH - so we only create ONE guitarscene...!
        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        Log.debug(self.versionString + " starting up...")
        Log.debug("Python version: " + sys.version.split(' ')[0])
        Log.debug("Pygame version: " + str(pygame.version.ver) )
        Log.debug("PyOpenGL version: " + OpenGL.__version__)
        Log.debug("Numpy version: " + np.__version__)
        Log.debug("PIL version: " + Image.VERSION)
        Log.debug("sys.argv: " + repr(sys.argv))
        Log.debug("os.name: " + os.name)
        Log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            Log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            Log.debug("os.uname(): " + repr(os.uname()))

        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")

        self.tasks = []
        self.frameTasks = []
        self.fps = fps
        self.currentTask = None
        self.paused = []
        self.running = True
        self.clock = pygame.time.Clock()

        self.title             = self.versionString
        self.restartRequested  = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename, "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video             = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio             = Audio()
        self.frames            = 0
        self.fpsEstimate       = 0
        self.priority          = self.config.get("engine", "highpriority")
        self.show_fps          = self.config.get("video", "show_fps")
        self.advSettings       = self.config.get("game", "adv_settings")
        self.restartRequired   = False
        self.quicksetRestart   = False
        self.quicksetPerf      = self.config.get("quickset", "performance")
        self.scrollRate        = self.config.get("game", "scroll_rate")
        self.scrollDelay       = self.config.get("game", "scroll_delay")

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        self.cmdPlay           = 0
        self.cmdMode           = None
        self.cmdDiff           = None
        self.cmdPart           = None

        self.gameStarted       = False
        self.world             = None

        self.audioSpeedFactor  = 1.0

        Log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)
        Log.debug("OpenGL version: " + glGetString(GL_VERSION))
        Log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        Log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        Log.debug("OpenGL extensions: " + ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            Log.debug("Enabling high priority timer.")
            self.fps = 0 # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.startupMessages   = self.video.error
        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.mainloop  = self.loading
        self.menuMusic = False

        self.setlistMsg = None


        # Load game modifications
        Mod.init(self)
        self.addTask(self.input, synchronized = False)

        self.addTask(self.view, synchronized = False)

        self.addTask(self.resource, synchronized = False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme, "backgrounds")
        themepath  = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(stagespath)   #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(os.path.join(stagespath,name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(aniFile)[1] == ".png" or os.path.splitext(aniFile)[1] ==  ".jpg" or os.path.splitext(aniFile)[1] == ".jpeg":  #we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)


            i = len(self.stageFolders)
            if i > 0: #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            Log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),self.stageFolders[n]) for n in range(0, i)])
            aniStageOptions.update({"Normal":_("Slideshow")})
            if i > 1:   #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random":_("Random")})
            Config.define("game", "animated_stage_folder", str, defaultAniStage, text = _("Animated Stage"), options = aniStageOptions )

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game","last_theme")
            if lastTheme == "" or lastTheme != currentTheme:   #MFH - no last theme, and theme just changed:
                self.config.set("game","animated_stage_folder",defaultAniStage)   #force defaultAniStage
            self.config.set("game","last_theme",currentTheme)

            selectedAnimatedStage = self.config.get("game", "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(os.path.join(stagespath,selectedAnimatedStage)):
                    Log.warn("Selected animated stage folder " + selectedAnimatedStage + " does not exist, forcing Normal.")
                    self.config.set("game","animated_stage_folder","Normal") #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game", "animated_stage_folder", str, "None", text = _("Animated Stage"), options = ["None",_("None")])
            Log.warn("No stages\ folder found, forcing None setting for Animated Stage.")
            self.config.set("game","animated_stage_folder", "None") #MFH: force "None" when Stages folder can't be found



        try:
            fp, pathname, description = imp.find_module("CustomTheme",[themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.addTask(self.theme)


        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False
        self.graphicMenuShown   = False

        Log.debug("Ready.")


    # evilynux - This stops the crowd cheers if they're still playing (issue 317).
    def quit(self):
        # evilynux - self.audio.close() crashes when we attempt to restart
        if not self.restartRequested:
            self.audio.close()
        Player.savePlayers()
        for t in list(self.tasks + self.frameTasks):
            self.removeTask(t)
        self.running = False

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
            self.quit()

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.svg.setGeometry((0, 0, width, height))

    def startWorld(self, players, maxplayers = None, gameMode = 0, multiMode = 0, allowGuitar = True, allowDrum = True, allowMic = False, tutorial = False):
        self.world = World(self, players, maxplayers, gameMode, multiMode, allowGuitar, allowDrum, allowMic, tutorial)

    def finishGame(self):
        if not self.world:
            Log.notice("GameEngine.finishGame called before World created.")
            return
        self.world.finishGame()
        self.world = None
        self.gameStarted = False
        self.view.pushLayer(self.mainMenu)

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize: Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    #volshebnyi
    def drawStarScore(self, screenwidth, screenheight, xpos, ypos, stars, scale = None, horiz_spacing = 1.2, space = 1.0, hqStar = False, align = LEFT):
        minScale = 0.02
        w = screenwidth
        h = screenheight
        if not scale:
            scale = minScale
        elif scale < minScale:
            scale = minScale
        if self.data.fcStars and stars == 7:
            star = self.data.starFC
        else:
            star = self.data.starPerfect
        wide = scale * horiz_spacing
        if align == CENTER: #center - akedrou (simplifying the alignment...)
            xpos  -= (2 * wide)
        elif align == RIGHT: #right
            xpos  -= (4 * wide)
        if stars > 5:
            for j in range(5):

                if self.data.maskStars:
                    if self.data.theme == 2:
                        self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), color = (1, 1, 0, 1), stretched=11)
                    else:
                        self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), color = (0, 1, 0, 1), stretched=11)
                else:
                    self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), stretched=11)
        else:
            for j in range(5):
                if j < stars:
                    if hqStar:
                        star = self.data.star4
                    else:
                        star = self.data.star2
                else:
                    if hqStar:
                        star = self.data.star3
                    else:
                        star = self.data.star1
                self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), stretched=11)

    def drawImage(self, image, scale = (1.0, -1.0), coord = (0, 0), rot = 0, \
                  color = (1,1,1,1), rect = (0,1,0,1), stretched = 0, fit = 0, \
                  alignment = CENTER, valignment = 1):
        """
        Draws the image/surface to screen

        @param image:        The openGL surface
        @param scale:        Scale factor (between 0.0 and 1.0, second value must be negative due to texture flipping)
        @param coord:        Where the image will be translated to on the screen
        @param rot:          How many degrees it will be rotated
        @param color:        The color of the image
                                 (values are between 0.0 and 1.0)
                                 (can have 3 values or 4, if 3 are given the alpha is automatically set to 1.0)
        @param rect:         The surface rectangle, this is used for cropping the texture
        @param stretched:    Stretches the image in one of 5 ways according to following passed values
                                 1) fits it to the width of the viewport
                                 2) fits it to the height of the viewport
                                11) fits it to the width of the viewport and scales the height while keeping the aspect ratio
                                12) fits it to the heigh of the viewport and scales the width while keeping the aspect ratio
                                 0) stretches it so it fits the whole viewport
                             Any other values will have the image maintain its size passed by scale
        @param fit:          Adjusts the texture so the coordinate for the y-axis placement can be
                             on the top side (1), bottom side (2), or center point (any other value) of the image
        @param alignment:    Adjusts the texture so the coordinate for x-axis placement can either be
                             on the left side (0), center point (1), or right(2) side of the image
        @param valignment:   Adjusts the texture so the coordinate for y-axis placement can either be
                             on the bottom side (0), center point (1), or top(2) side of the image
        """

        if not isinstance(image, ImgDrawing):
            return

        width, height = scale
        x, y = coord
        if stretched == 1: # fit to width
            width  = width  / image.pixelSize[0] * self.view.geometry[2]
        elif stretched == 2: # fit to height
            height = height / image.pixelSize[1] * self.view.geometry[3]
        elif stretched == 11: # fit to width and keep ratio
            width  = width  / image.pixelSize[0] * self.view.geometry[2]
            height = height / image.pixelSize[0] * self.view.geometry[2]
        elif stretched == 12: # fit to height and keep ratio
            width  = width  / image.pixelSize[1] * self.view.geometry[3]
            height = height / image.pixelSize[1] * self.view.geometry[3]
        elif not stretched == 0: # fit to screen
            width  = width  / image.pixelSize[0] * self.view.geometry[2]
            height = height / image.pixelSize[1] * self.view.geometry[3]

        if fit == 1: #y is on top (not center)
            y = y - ((image.pixelSize[1] * abs(scale[1]))*.5*(self.view.geometry[3]/480.0))
        elif fit == 2: #y is on bottom
            y = y + ((image.pixelSize[1] * abs(scale[1]))*.5*(self.view.geometry[3]/480.0))

        image.setRect(rect)
        image.setScale(width, height)
        image.setPosition(x, y)
        image.setAlignment(alignment)
        image.setVAlignment(valignment)
        image.setAngle(rot)
        image.setColor(color)
        image.draw()

    #blazingamer
    def draw3Dtex(self, image, vertex, texcoord, coord = None, scale = None, rot = None, color = (1,1,1), multiples = False, alpha = False, depth = False, vertscale = 0):
        '''
        Simplifies tex rendering

        @param image: self.xxx - tells the system which image/resource should be mapped to the plane
        @param vertex: (Left, Top, Right, Bottom) - sets the points that define where the plane will be drawn
        @param texcoord: (Left, Top, Right, Bottom) - sets where the texture should be drawn on the plane
        @param coord: (x,y,z) - where on the screen the plane will be rendered within the 3d field
        @param scale: (x,y,z) - scales an glplane how far in each direction

        @param rot: (degrees, x-axis, y-axis, z-axis)
        a digit in the axis is how many times you want to rotate degrees around that axis

        @param color: (r,g,b) - sets the color of the image when rendered
        0 = No Color, 1 = Full color

        @param multiples: True/False
        defines whether or not there should be multiples of the plane drawn at the same time
        only really used with the rendering of the notes, keys, and flames

        @param alpha: True/False - defines whether or not the image should have black turned into transparent
        only really used with hitglows and flames

        @param depth: True/False - sets the depth by which the object is rendered
        only really used by keys and notes

        @param vertscale: # - changes the yscale when setting vertex points
        only really used by notes
        '''


        if not isinstance(image, ImgDrawing):
            return

        if alpha == True:
            glBlendFunc(GL_SRC_ALPHA, GL_ONE)

        if len(color) == 4:
            col_array  = np.array([[color[0],color[1],color[2], color[3]],
                               [color[0],color[1],color[2], color[3]],
                               [color[0],color[1],color[2], color[3]],
                               [color[0],color[1],color[2], color[3]]], dtype=np.float32)
        else:
            col_array  = np.array([[color[0],color[1],color[2], 1],
                               [color[0],color[1],color[2], 1],
                               [color[0],color[1],color[2], 1],
                               [color[0],color[1],color[2], 1]], dtype=np.float32)

        glEnable(GL_TEXTURE_2D)
        image.texture.bind()

        if multiples == True:
            glPushMatrix()

        if coord != None:
            glTranslate(coord[0], coord[1], coord[2])
        if rot != None:
            glRotate(rot[0], rot[1], rot[2], rot[3])
        if scale != None:
            glScalef(scale[0], scale[1], scale[2])

        if depth == True:
            glDepthMask(1)

        if not isinstance(vertex, np.ndarray):
            vertex = np.array(
              [[ vertex[0],  vertscale, vertex[1]],
               [ vertex[2],  vertscale, vertex[1]],
               [ vertex[0], -vertscale, vertex[3]],
               [ vertex[2], -vertscale, vertex[3]]], dtype=np.float32)

        if not isinstance(texcoord, np.ndarray):
            texcoord = np.array(
              [[texcoord[0], texcoord[1]],
               [texcoord[2], texcoord[1]],
               [texcoord[0], texcoord[3]],
               [texcoord[2], texcoord[3]]], dtype=np.float32)

        cmgl.drawArrays(GL_TRIANGLE_STRIP, vertices=vertex, colors=col_array, texcoords=texcoord)

        if depth == True:
            glDepthMask(0)

        if multiples == True:
            glPopMatrix()

        glDisable(GL_TEXTURE_2D)

        if alpha == True:
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    #glorandwarf: renamed to retrieve the path of the file
    def fileExists(self, fileName):
        return self.data.fileExists(fileName)

    def getPath(self, fileName):
        return self.data.getPath(fileName)

    def loading(self):
        """Loading state loop."""
        done = self.doRun()
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.svg.clear(*self.theme.backgroundColor)

    def addTask(self, task, synchronized = True):
        """
        Add a task to the engine.

        @param task:          L{Task} to add
        @type  synchronized:  bool
        @param synchronized:  If True, the task will be run with small
                              timesteps tied to the engine clock.
                              Otherwise the task will be run once per frame.
        """
        if synchronized:
            queue = self.tasks
        else:
            queue = self.frameTasks

        if not task in queue:
            queue.append(task)
            task.started()

    def removeTask(self, task):
        """
        Remove a task from the engine.

        @param task:    L{Task} to remove
        """
        queues = self._getTaskQueues(task)
        for q in queues:
            q.remove(task)
        if queues:
            task.stopped()

    def _getTaskQueues(self, task):
        queues = []
        for queue in [self.tasks, self.frameTasks]:
            if task in queue:
                queues.append(queue)
        return queues

    def pauseTask(self, task):
        """
        Pause a task.

        @param task:  L{Task} to pause
        """
        self.paused.append(task)

    def resumeTask(self, task):
        """
        Resume a paused task.

        @param task:  L{Task} to resume
        """
        self.paused.remove(task)

    def enableGarbageCollection(self, enabled):
        """
        Enable or disable garbage collection whenever a random garbage
        collection run would be undesirable. Disabling the garbage collector
        has the unfortunate side-effect that your memory usage will skyrocket.
        """
        if enabled:
            gc.enable()
        else:
            gc.disable()

    def collectGarbage(self):
        """
        Run a garbage collection run.
        """
        gc.collect()

    def _runTask(self, task, ticks = 0):
        if not task in self.paused:
            self.currentTask = task
            task.run(ticks)
            self.currentTask = None

    def main(self):
        """Main state loop."""
        done = self.doRun()
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        # evilynux - Estimate the rendered frames per second.
        self.frames = self.frames+1
        # Estimate every 120 frames when highpriority is True.
        # Estimate every 2*config.fps when highpriority is False,
        # if you are on target, that should be every 2 seconds.
        if( not self.priority and self.frames == (self.fps << 1) ) or ( self.priority and self.frames == 120 ):
            self.fpsEstimate = self.clock.get_fps()
            # evilynux - Printing on the console with a frozen binary may cause a crash.
            if self.show_fps and not Version.isWindowsExe():
                print("%.2f fps" % self.fpsEstimate)
            self.frames = 0
        return done

    def doRun(self):
        """Run one cycle of the task scheduler engine."""
        if not self.frameTasks and not self.tasks:
            return False

        for task in self.frameTasks:
            self._runTask(task)
        tick = self.clock.get_time()
        for task in self.tasks:
            self._runTask(task, tick)
        self.clock.tick(self.fps)
        return True

    def run(self):
        return self.mainloop()
Example #42
0
    def __init__(self, config = None):

        Log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None    #placeholder for main menu object - to prevent reinstantiation

        self.createdGuitarScene = False   #MFH - so we only create ONE guitarscene...!
        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        Log.debug(self.versionString + " starting up...")
        Log.debug("Python version: " + sys.version.split(' ')[0])
        Log.debug("Pygame version: " + str(pygame.version.ver) )
        Log.debug("PyOpenGL version: " + OpenGL.__version__)
        Log.debug("Numpy version: " + np.__version__)
        Log.debug("PIL version: " + Image.VERSION)
        Log.debug("sys.argv: " + repr(sys.argv))
        Log.debug("os.name: " + os.name)
        Log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            Log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            Log.debug("os.uname(): " + repr(os.uname()))

        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")

        self.tasks = []
        self.frameTasks = []
        self.fps = fps
        self.currentTask = None
        self.paused = []
        self.running = True
        self.clock = pygame.time.Clock()

        self.title             = self.versionString
        self.restartRequested  = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename, "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video             = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio             = Audio()
        self.frames            = 0
        self.fpsEstimate       = 0
        self.priority          = self.config.get("engine", "highpriority")
        self.show_fps          = self.config.get("video", "show_fps")
        self.advSettings       = self.config.get("game", "adv_settings")
        self.restartRequired   = False
        self.quicksetRestart   = False
        self.quicksetPerf      = self.config.get("quickset", "performance")
        self.scrollRate        = self.config.get("game", "scroll_rate")
        self.scrollDelay       = self.config.get("game", "scroll_delay")

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        self.cmdPlay           = 0
        self.cmdMode           = None
        self.cmdDiff           = None
        self.cmdPart           = None

        self.gameStarted       = False
        self.world             = None

        self.audioSpeedFactor  = 1.0

        Log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)
        Log.debug("OpenGL version: " + glGetString(GL_VERSION))
        Log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        Log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        Log.debug("OpenGL extensions: " + ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            Log.debug("Enabling high priority timer.")
            self.fps = 0 # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.startupMessages   = self.video.error
        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.mainloop  = self.loading
        self.menuMusic = False

        self.setlistMsg = None


        # Load game modifications
        Mod.init(self)
        self.addTask(self.input, synchronized = False)

        self.addTask(self.view, synchronized = False)

        self.addTask(self.resource, synchronized = False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme, "backgrounds")
        themepath  = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(stagespath)   #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(os.path.join(stagespath,name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(aniFile)[1] == ".png" or os.path.splitext(aniFile)[1] ==  ".jpg" or os.path.splitext(aniFile)[1] == ".jpeg":  #we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)


            i = len(self.stageFolders)
            if i > 0: #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            Log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),self.stageFolders[n]) for n in range(0, i)])
            aniStageOptions.update({"Normal":_("Slideshow")})
            if i > 1:   #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random":_("Random")})
            Config.define("game", "animated_stage_folder", str, defaultAniStage, text = _("Animated Stage"), options = aniStageOptions )

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game","last_theme")
            if lastTheme == "" or lastTheme != currentTheme:   #MFH - no last theme, and theme just changed:
                self.config.set("game","animated_stage_folder",defaultAniStage)   #force defaultAniStage
            self.config.set("game","last_theme",currentTheme)

            selectedAnimatedStage = self.config.get("game", "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(os.path.join(stagespath,selectedAnimatedStage)):
                    Log.warn("Selected animated stage folder " + selectedAnimatedStage + " does not exist, forcing Normal.")
                    self.config.set("game","animated_stage_folder","Normal") #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game", "animated_stage_folder", str, "None", text = _("Animated Stage"), options = ["None",_("None")])
            Log.warn("No stages\ folder found, forcing None setting for Animated Stage.")
            self.config.set("game","animated_stage_folder", "None") #MFH: force "None" when Stages folder can't be found



        try:
            fp, pathname, description = imp.find_module("CustomTheme",[themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.addTask(self.theme)


        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False
        self.graphicMenuShown   = False

        Log.debug("Ready.")
Example #43
0
class GameEngine(object):
    """The main game engine."""
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        self.fps          = self.config.get("video", "fps")

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.running = True
        self.timer = FpsTimer()
        self.tickDelta = 0
        self.task = TaskEngine(self)

        self.task.addTask(self.input, synced = False)
        self.task.addTask(self.view)
        self.task.addTask(self.resource, synced = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        log.debug("Ready.")

    def enableGarbageCollection(self, enabled):
        """
        Enable or disable garbage collection whenever a random garbage
        collection run would be undesirable. Disabling the garbage collector
        has the unfortunate side-effect that your memory usage will skyrocket.
        """
        if enabled:
            gc.enable()
        else:
            gc.disable()

    def collectGarbage(self):
        """
        Run a garbage collection run.
        """
        gc.collect()

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
            self.quit()

    def quit(self):
        self.audio.close()
        self.task.exit()
        self.running = False

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.img.setGeometry((0, 0, width, height))

    def startWorld(self):
        self.world = World(self)

    def finishGame(self):
        self.world.finishGame()
        self.world = None
        self.view.pushLayer(MainMenu.MainMenu(self))

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize  Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()

    def clearScreen(self):
        self.img.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)

    def run(self):
        try:
            self.tickDelta = self.timer.tick()
            done = self.task.run()
            self.clearScreen()

            self.mainloop()

            self.video.flip()

            # Calculate FPS every 2 seconds
            if self.timer.fpsTime >= 2000:
                self.fpsEstimate = self.timer.get_fps()
                print ("%.2f fps" % self.fpsEstimate)

            self.timer.delay(self.fps)

            return done
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
Example #44
0
def main():

    # Determine assets
    sprite_asset, bullet_sound_asset = DetermineAssets()

    # Load sprite assets
    IMAGESDICT, animObjs = LoadSpriteAssets(sprite_asset)

    # Main game surface
    DISPLAYSURF = pygame.display.set_mode((SCREEN_X, SCREEN_Y)) #Make the screen

    # Colors
    BLACK = (0,0,0)

    # Calculate starting position of player
    startX, startY = SCREEN_X/2 - LEN_SPRT_X, SCREEN_Y - LEN_SPRT_Y

    # Hold info on keys pressed, held, released
    keyinput = Input()

    # Initialize gamemap and Player
    player = Player(IMAGESDICT, animObjs, bullet_sound_asset)
    player.rect.topleft = startX, 0

    # Create map sprite group
    environment = pygame.sprite.Group()

    # Open and parse map file
    parseMap(IMAGESDICT, environment)

    # Sprite group
    allsprites = pygame.sprite.RenderPlain(player)

    # Start game loop
    while True:
        # Clear key info
        keyinput.clearKeys()

        # Draw screen black
        DISPLAYSURF.fill(BLACK)

        # Check for game events
        for event in pygame.event.get():
            # Reset player direction
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # Handle key presses
                keyinput.keyDownEvent(event.key)
            elif event.type == KEYUP:
                keyinput.keyUpEvent(event.key)

        # Player horizontal logic
        if keyinput.isKeyHeld(K_LEFT) and keyinput.isKeyHeld(K_RIGHT):
            player.stopMoving()
        elif keyinput.isKeyHeld(K_LEFT):
            player.moveLeft()
        elif keyinput.isKeyHeld(K_RIGHT):
            player.moveRight()
        elif keyinput.wasKeyPressed(K_SPACE):
            # Play player shooting animation
            player.shoot()
        elif keyinput.wasKeyPressed(K_ESCAPE):
            pygame.quit()
            sys.exit()
        elif not player.shooting:
            player.stopMoving()

        # Toggle Blue/Red character
        if keyinput.wasKeyPressed(K_c):
            player.toggleColor()

        # Vertical logic
        if keyinput.wasKeyPressed(K_UP):
            player.jump()

        # Remove bullets that leave screen
        for sprite in allsprites:
            if isinstance(sprite, Bullet):
                if sprite.rect[0] > SCREEN_X or sprite.rect[0] < 0:
                    allsprites.remove(sprite)

        # Update
        allsprites.update(environment)
        environment.update(allsprites)

        # Draw
        allsprites.draw(DISPLAYSURF)
        environment.draw(DISPLAYSURF)

        pygame.display.update()
        fpsClock.tick(FPS)
Example #45
0
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")
Example #46
0
class SimpleTests(unittest.TestCase):
    def setUp(self):
        """Call before every test case."""
        self.parser = Parser()
        self.input = None
        self.input = Input()
        
    def testNormal1(self):       
        test="""\
        param <%ArrayList<point>%> c1:
                 dependsOn x1,x2,y1,y2:
                         <%
                         c1=new ArrayList();
                         c1.add(new Point(%x1%,%y1%));
                         c1.add(new Point(%x2%,%y2%));
                         %>
                 out:
                         returns >= (x1+y1) - (x2-y2)	
                 invalid 0:
                         <%c1=null;%>
                 out:
                         throws <%.GetType().Name==NullReferenceException%>"""
        self.input.tokens=self.parser.input.parseString(test)[0]
        gen=self.input.populate()
        try:
            gen.next()
        except StopIteration:
            pass
        name=self.input.name
        inherits=self.input.inherits
        dataType=self.input.dataType
        assert name=="c1",name
        assert len(inherits)==0,inherits
        assert dataType=="ArrayList<point>",returns
       
    def testNormal2(self):
        test="""\
        param c2(a,b)
        """
        self.input.tokens=self.parser.input.parseString(test)[0]
        gen=self.input.populate()
        try:
            gen.next()
        except StopIteration:
            pass
        name=self.input.name
        inherits=self.input.inherits
        assert name=="c2",name
        assert inherits[0]=='a',inherits
        dataType=self.input.dataType
        assert dataType is None, dataType
        
    def testNormal3(self):
        test="""\
        param <%ArrayList<point>%> c1:
                
            valid 0:
                    <%c1=null;%>
            out:
                    returns <%.GetType().Name==NullReferenceException%>
            invalid 0:
                     <%c1=null;%>
             out:
                     returns <%.GetType().Name==NullReferenceException%>
        """
        self.input.tokens=self.parser.input.parseString(test)[0]
        gen=self.input.populate()
        try:
            gen.next()
        except StopIteration:
            pass
        else:
            self.fail('Why has execution stopped')
        name=self.input.name
        assert name=="c1",name
        assert self.input.validPartitions
        assert self.input.invalidPartitions
 
    def testEraseBug(self):
        self.input=Input([["param","c3","x4"]])
        gen=self.input.populate()
        try:
            gen.next()
        except StopIteration:
            pass
        assert self.input.name=="c3",self.input.name
    
    def testDefective1(self):
        test="""\
        param <%ArrayList<point>%> c1:
                
            valid 0:
                    <%c1=null;%>
            out:
                    returns <%.GetType().Name==NullReferenceException%>
            valid 0:
                     <%c1=null;%>
             out:
                     returns <%.GetType().Name==NullReferenceException%>
        """
        self.input.tokens=self.parser.input.parseString(test)[0]
        gen=self.input.populate()
        self.assertRaises(DuplicateDefinitionException,gen.next)
        
    def testValueCount1(self):
        cut=self.input
        test="""\
        param <%ArrayList<point>%> c1:
            valid 0:
                    <%c1=null;%>
            valid 1:
                     <%c1=null;%> 
        """
        self.input.tokens=self.parser.input.parseString(test)[0]
        try:
            cut.populate().next()
        except StopIteration:
            pass
        else:
            self.fail('Why has execution stopped')
        assert cut.valueCount==(2,0), cut.valueCount
        assert cut.valueCount==(2,0), cut.valueCount

    def testValueCount2(self):
        cut=self.input
        test="""\
        param <%ArrayList<point>%> c1:
            valid 0:
                    <% %c1%=null;%>
            valid 1:
                     <% %c1%=null;%>
            invalid 0:
               c1 < 5
               c1 > 3
        """
        cut.tokens=self.parser.input.parseString(test)[0]
        try:
            cut.populate().next()
        except StopIteration:
            pass
        else:
            self.fail('Why has execution stopped')
        assert 5-sum(cut.valueCount)<=1
        assert 5-sum(cut.valueCount)<=1
    def getC1(self):
        test1="""\
        param <%ArrayList<point>%> c1:
            valid 0:
                    <% %c1%=null;%>
            valid 1:
                     <% %c1%=null;%>
            invalid 0:
               c1 < 5
               c1 > 3
        """
        c1=Input(tokens=self.parser.input.parseString(test1)[0])
        try:
            c1.populate().next()
        except StopIteration:
            pass
        else:
            self.fail('Why has execution stopped')
        return c1
    def testInheritOnly1(self):
        cut=self.input
        test2='''\
        param c2(c1)
        '''
        cut.tokens=self.parser.input.parseString(test2)[0]
        gen=cut.populate()
        c=True
        try:
            typ,ini = gen.next()
            assert typ=='ini',typ
            assert ini=='c1',ini
            c=False
            gen.send(self.getC1())
        except StopIteration:
            if c: self.fail("I haven't been asked any values")
        else:
            self.fail('Why has execution stopped')
        assert 5-sum(cut.valueCount)<=1
        assert 5-sum(cut.valueCount)<=1
    
    def testTransform1(self):
        cut=self.input
        cut.name='x'
        inh=InheritedPartition()
        s=SubPartition()
        inh.subPartitions.append(s)
        s.containsExternalCode=True
        s.code='hello %w% %w%'
        s.inputName='w'
        s=cut._Input__transformPartition(inh)[0]
        assert isinstance(s,SubPartition)
        assert s.code=='hello %x% %x%'
        assert s.inputName=='x'