def start_time(self, t):
     # get start time and set current CB objects (and their change times)
     Screen.start_time(self, t)
     self._last_CB_change_time_left = t
     self._last_CB_change_time_right = t
     self._current_CB_left = self.CB_cycle_left.next()
     self._current_CB_right = self.CB_cycle_right.next()
Пример #2
0
    def __init__(self, game, materials, newMaterials, money):
        
        self.money = money
        
        self.game = game

        
        self.materials = materials
        self.newMaterials = newMaterials
        
        self.constantLabels = []
        self.shownItems = []

        self.mixScreenButton = MatSciGame.MixScreenButton("mixScreen","img/MixingButton.png", pygame.Rect(900, 300, 300, 75),MatSciGame.ForceScreenButton.clicked, self.game)
        
        self.constantLabels.append(ScreenText("moneyText", "Money = " + str(self.money), pygame.Rect(900, 0, 300, 75), pygame.font.SysFont("Arial", 40)))               
        
        self.Notificationlabels = []
        self.infoLabels = []
        
        self.actors = self.constantLabels + self.shownItems
        
        self.buttons = [self.mixScreenButton]
        
        Screen.__init__(self, self.buttons, self.actors, "img/bookOpen.png")
Пример #3
0
 def do(self):
     self.done = False
     Screen.do(self)
     areavars2conf = {'nrounds':'NUMBER OF ROUNDS', 'maxt':'TIMER', 'ailevel':'AI DIFFICULTY', 
                 'musicvol':'MUSIC VOLUME', 'sfxvol':'SFX VOLUME'}
     for k, v in areavars2conf:
         self.area.__dict__[k] = self.setting(v)
Пример #4
0
 def clear(self, color, i=None):
     """ Clear the subscreen at index i.
     """
     if i != None:
         pygame.draw.rect(self.screen, color, self.rect(i))
     else:
         Screen.clear(self, color)
 def render(self):
     # do general OpenGL stuff as well as FixationCross and Vsync Patch if needed
     Screen.render(self)
     # translate to position of left board and render
     gl.glLoadIdentity()
     gl.glTranslatef(self.xC, self.yC, 0.0)
     self._current_CB.render()
Пример #6
0
    def __init__(self, game, materials, newMaterials, money):
        
        self.dropTest = ItemMakeZone('makeItems', pygame.Rect(300, 200, 450, 450), self, game)
        self.dropMats = HoldZone('holdMats', pygame.Rect(730, 100, 90, 550), game)
        self.dropNewMats = HoldZone('holdsNewMaterials', pygame.Rect(150/2,100, 180, 550), game)
        self.dropItems = HoldZone('holdsItems', pygame.Rect(650,625, 300, WINDOWHEIGHT/2), game)
        self.money = money
        
        self.game = game

        
        self.materials = materials
        self.newMaterials = newMaterials
        self.items = []
        
        self.items.append(MatSciGame.Item("cup", pygame.Rect(300, 600, 85, 93), 60, 50, 70, .3, .1, .6, (0,0,0)))
        self.items.append(MatSciGame.Item("hammer", pygame.Rect(400, 600, 90, 90), 100, 60, 40, .6, .3, .1, (0,0,0)))
        self.items.append(MatSciGame.Item("table", pygame.Rect(650, 600, 85, 70), 80, 40, 60, .5, .2, .3, (0,0,0)))
        self.items.append(MatSciGame.Item("poker", pygame.Rect(500, 600, 34, 90), 40, 100, 30, .2, .7, .1, (0,0,0)))
        self.items.append(MatSciGame.Item("decor", pygame.Rect(550, 600, 80, 90), 20, 40, 100, .2, .1, .7, (0,0,0)))
        
        self.constantLabels = []
        self.dropZones = [self.dropTest, self.dropMats, self.dropNewMats]
        self.mixScreenButton = MatSciGame.MixScreenButton("mixScreen","img/MixingButton.png", pygame.Rect(900, 300, 300, 75),MatSciGame.ForceScreenButton.clicked, self.game)
        
        self.constantLabels.append(ScreenText("moneyText", "Money = " + str(self.money), pygame.Rect(900, 0, 300, 75), pygame.font.SysFont("Arial", 40)))               
        
        self.Notificationlabels = []
        self.infoLabels = []
        
        self.actors = self.constantLabels + self.dropZones+ self.materials+self.newMaterials + self.items
        self.buttons = [self.mixScreenButton]
        
        Screen.__init__(self, self.buttons, self.actors, "img/kitchenBackground.png")
Пример #7
0
    def __init__(self, game, tools, parts):
        self.game = game
        self.tools = tools
        self.parts = parts
        

        Screen.__init__(self, self.buttons, self.actors, (0,128,0))
Пример #8
0
def main():
    s = Screen(fg='white', bg='black')
    s.cls('green')
    w = Window(s, 5, 5, 45, 30)
    w.cls()

    # for i in range(10):
    #     print >>w, i

    w2 = Window(s, 66, 5, 120, 10)
    w2.cls()

    # for i in range(31):
    #     print >>w, 'a' * i
    #     time.sleep(0.4)
    #
    # print >>w, 'abcdefghi\njklmnopqrstuvwxyz'
    # print >>w, 'abcdefghijklmnopqrstuvwxyz'
    # print >>w, 'HI'

    print >>w, open(__file__).read()

    # print >>w2, 'world'
    # print >>w2, 'YO'

    s.gotoxy(s.left, s.bottom)
Пример #9
0
    def __init__(self, game, materials, newMaterials, money):
        
        self.dropTest = MeltingTestZone('dropTest', pygame.Rect(290, 200, 300, 300), self)
        self.dropMats = HoldZone('holdMats', pygame.Rect(730, 100, 90, 550), game)
        self.dropNewMats = HoldZone('holdsNewMaterials', pygame.Rect(150/2,100, 180, 550), game)
        self.money = money
        
        self.game = game

        
        self.materials = materials
        self.newMaterials = newMaterials

        
        
        self.constantLabels = []
        self.dropZones = [self.dropTest, self.dropMats, self.dropNewMats]
        self.mixScreenButton = MatSciGame.MixScreenButton("mixScreen","img/MixingButton.png", pygame.Rect(900, 300, 300, 75),MatSciGame.ForceScreenButton.clicked, self.game)
        
        self.constantLabels.append(ScreenText("moneyText", "Money = " + str(self.money), pygame.Rect(900, 0, 300, 75), pygame.font.SysFont("Arial", 40)))               
        
        
        
        self.Notificationlabels = []
        self.infoLabels = []
        
        self.actors = self.constantLabels + self.dropZones+ self.materials+self.newMaterials
        self.buttons = [self.mixScreenButton]
        
        Screen.__init__(self, self.buttons, self.actors, "img/kitchenBackground.png")
Пример #10
0
class GameBoy(object):
    def __init__(self, ROM):
        self.memory = Memory(ROM)
        self.Z80 = Z80(self.memory)
        self.screen = Screen(self.memory)

    def get_ROM_name(self):
        chars = self.memory.ROM[0x0134:0x0143]  # The ROM's name is simply written at this address
        return "".join([chr(x) for x in chars])

    def run(self):
        a = 0
        while True:
            if self.Z80.PC == 0x100 and self.memory.BIOS_has_run == False:
                print "BIOS has been executed"
                self.memory.BIOS_has_run = (
                    True
                )  # BIOS starts at 0 and goes to 0x100, once there it has to be removed from the memory
            self.Z80.next_instruction()
            self.screen.sync_clock(self.Z80.t)

            # Interrupts handling
            for i in xrange(5):
                if (
                    self.Z80.ime
                    and self.memory.read_byte(0xFFFF) & (1 << i)
                    and self.memory.read_byte(0xFF0F) & (1 << i)
                ):  # interrupts enabled && specific interrupt enabled && interrupt requested
                    self.memory.write_byte(0xFF0F, self.memory.read_byte(0xFF0F) & ~(1 << i))
                    self.Z80.ime = False  # Prevents other interrupts
                    self.Z80.registers["SP"] -= 2
                    self.memory.write_word(self.Z80.SP, self.Z80)
                    self.Z80.registers["PC"] = INTERRUPTS_ADDRESSES[i]
                    self.screen.sync_clock(12)  # Every interrupt takes 12 CPU cycles
Пример #11
0
class ScreenTest(unittest.TestCase):
    SCREEN_W = 64
    SCREEN_H = 32

    def setUp(self):
        self.screen = Screen(self.SCREEN_W, self.SCREEN_H)

    def tearDown(self):
        pass

    def testShouldHaveCorrectSize(self):
        self.assertEqual(self.screen.width, self.SCREEN_W)
        self.assertEqual(self.screen.height, self.SCREEN_H)

    def testShouldChangeCorrectPixel(self):
        self.screen.setPixel(1, 1, True)
        pixel1 = self.screen.getPixel(1, 1)
        self.assertTrue(pixel1)

        self.screen.setPixel(1, 1, False)
        pixel2 = self.screen.getPixel(1, 1)
        self.assertFalse(pixel2)

    def testShouldBeClearedAfterInit(self):
        self.assertTrue(self.screen.screen == [0] * len(self.screen.screen))

    def testShouldFullyClearScreen(self):
        self.screen.setPixel(1, 1, True)
        self.screen.clear()
        self.assertTrue(self.screen.screen == [0] * len(self.screen.screen))
Пример #12
0
    def toolClicked(self,tools,parts):
        self.tools.database = database
        self.screen.Notificationlabels.append(ScreenText("text1", database, pygame.Rect(100, 3*WINDOWHEIGHT/4, 200, 50), font1))
        passn


        Screen.__init__(self, self.buttons, self.actors, (128,0,0))
Пример #13
0
    def __init__(self):
        Screen.__init__(self,"fieldNumberScreen")

        self.screen.fill([0,0,0])             # just black, no graphic background image

        self.buttonHeight = self.height/3
        self.buttonPadding = self.width/25

        self.matchImage, self.autoImage, self.teleopImage, self.endGameImage = self.numberImages(self.buttonHeight)
        self.buttonWidth = self.matchImage.get_width()
        self.matchPos, self.autoPos, self.teleopPos, self.endGamePos = self.numberPositions(self.buttonHeight,
                                                                                            self.buttonWidth,
                                                                                            self.buttonPadding)
        
        self.matchButton = self.buttons((self.buttonWidth,self.buttonHeight),self.matchPos,
                                        graphic=self.matchImage, callback=self.editMatchNumber)
        self.autoButton = self.buttons((self.buttonWidth,self.buttonHeight),self.autoPos,
                                       graphic=self.autoImage, callback=self.editAutoNumber)
        self.teleopButton = self.buttons((self.buttonWidth,self.buttonHeight),self.teleopPos,
                                         graphic=self.teleopImage, callback=self.editTeleopNumber)
        self.endGameButton = self.buttons((self.buttonWidth,self.buttonHeight),self.endGamePos,
                                          graphic=self.endGameImage, callback=self.editEndGameNumber)

        self.ButtonS = self.buttons(bgcolor = (0,0,255), callback=self.done,
                                     **Button.standardButton("S","Done",self.screen))
Пример #14
0
    def __init__(self,name):
        Screen.__init__(self,name)

        self.screen.fill([0,0,0])             # just black, no graphic background image

        # go ahead and calculate the time display/buttons

        self.buttonHeight = self.height/3
        self.buttonPadding = self.width/25

        self.matchImage, self.autoImage, self.teleopImage, self.endGameImage = self.numberImages(self.buttonHeight)
        self.buttonWidth = self.matchImage.get_width()
        self.matchPos, self.autoPos, self.teleopPos, self.endGamePos = self.numberPositions(self.buttonHeight,
                                                                                            self.buttonWidth,
                                                                                            self.buttonPadding)
        
        self.matchButton = self.buttons((self.buttonWidth,self.buttonHeight),self.matchPos,
                                        graphic=self.matchImage, callback=self.editMatchNumber,gpio=HARDWARE.button.NW)
        self.autoButton = self.buttons((self.buttonWidth,self.buttonHeight),self.autoPos,
                                       graphic=self.autoImage, callback=self.editAutoNumber,gpio=HARDWARE.button.SW)
        self.teleopButton = self.buttons((self.buttonWidth,self.buttonHeight),self.teleopPos,
                                         graphic=self.teleopImage, callback=self.editTeleopNumber,gpio=HARDWARE.button.NE)
        self.endGameButton = self.buttons((self.buttonWidth,self.buttonHeight),self.endGamePos,
                                          graphic=self.endGameImage, callback=self.editEndGameNumber,gpio=HARDWARE.button.SE)

        self.ButtonS = self.buttons(bgcolor = (0,0,255), callback=self.done,
                                     **Button.standardButton("S","Done",self.screen))
Пример #15
0
	def __init__(self, **args):
		self.choice = self.nextchoice = 0
		self.choices = [i.upper() for i in ['Arcade', 'VS Mode', 'Training', 'Options', 'Exit']]
		self.done = False
		keycond = lambda: not self.done
		Screen.__init__(self, 'system/title', keycond=keycond, **args)
		self.incx = 0
Пример #16
0
 def setup(self,
           nrows,
           check_width = None,
           check_color1 = 'white',
           check_color2 = 'black',
           screen_background_color = 'neutral-gray',
           fixation_dot_color = False,
           pos_x = None, 
           pos_y = None,
           vsync_value = None,
           vsync_patch = "bottom-right",
          ):
     Screen.setup(self,
                  background_color = screen_background_color,
                  vsync_value = vsync_value,
                  vsync_patch = vsync_patch,
                  )
     
     self.CB = CheckerBoard(nrows = nrows,
                            check_width = check_width,
                            color1 = check_color1,
                            color2 = check_color2,
                            fixation_dot_color = fixation_dot_color
                           )
                          
     if pos_x is None:
         pos_x = -0.5*self.CB.board_width
     if pos_y is None:
         pos_y = -0.5*self.CB.board_width
         
     self.pos_x = pos_x
     self.pos_y = pos_y
Пример #17
0
    def __init__(self,name,globalName,mode,title,color):
        Screen.__init__(self,name)

        self.ButtonS = self.buttons(bgcolor = (0,0,255), callback=self.done,
                                     **Button.standardButton("S","Done",self.screen))
        self.ButtonNW = self.buttons(bgcolor = (0,0,255), callback=self.cancel,
                                     **Button.standardButton("NW","Cancel",self.screen))

        self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.up, upCallback=self.release,
                                     holdCallback = self.holdCountUp, rotation = 180,
                                     **removeKey(Button.standardButton("NE","V",self.screen),'rotation'))

        self.ButtonSE = self.buttons(bgcolor = (0,0,255), callback=self.down, upCallback=self.release,
                                     holdCallback = self.holdCountDown,
                                     **Button.standardButton("SE","V",self.screen))
        self.ButtonSW = self.buttons(bgcolor = (255,0,0), callback=self.permenance,
                                     **Button.standardButton("SW","Permenance",self.screen))

        self.globalName = globalName
        self.mode = mode
        self.color = color
        self.title = title
        self.heldCountUp = False
        self.heldCountDown = False
        self.heldLastTime = datetime.datetime.now()
        self.needsUpdate = True
        self.PT = True
Пример #18
0
    def __init__(self,name):
        Screen.__init__(self,name)
        self.titleImage = pygame.image.load("Media/ChapFCS-title.gif").convert()
        self.titlePosition = ((self.screen.get_width()-self.titleImage.get_width())/2,
                              (self.screen.get_height()/4))
        self.tablePosition = (100,175)

        self.screen.fill([0,0,0])             # just black, no graphic background image

        self.ButtonNW = self.buttons(bgcolor = (0,0,255), callback=self.systemOptions,
                                     **Button.standardButton("NW",["System","Options"],self.screen))
        self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.matchOptions,
                                     **Button.standardButton("NE",["Field","Options"],self.screen))
        self.ButtonSE = self.buttons(bgcolor = (0,0,255), callback=self.about,
                                     **Button.standardButton("SE","About",self.screen))
        self.ButtonS = self.buttons(bgcolor = (255,255,255), callback=self.nextMatch, lcolor = (0,0,0),
                                     **Button.standardButton("S",["Next","Match"],self.screen))


        self.dataTable = self.tables(fontsize=20,font="monospace")

        self.dataTable.addData("Field Name: ",align="right")
        self.dataTable.addData(Settings.fieldName, bold=True, name="fieldName",bgcolor=(50,50,50),callback=self.setFieldName)
        self.dataTable.endRow()
        self.dataTable.addData("Next Match: ", align="right")
        self.dataTable.addData(Settings.matchNumber,name="match",callback=self.setMatchNumber,bold=True)
        self.dataTable.endRow()

        # put out the title
        self.screen.blit(self.titleImage,self.titlePosition)
        self.dataTable.position = self.tablePosition
Пример #19
0
 def __init__(self, shell, filename, **kwds):
     text = get_text(filename)
     text_pages = text.split("\nPAGE\n")
     pages = []
     page_size = (0, 0)
     for text_page in text_pages:
         lines = text_page.strip().split("\n")
         page = Page(self, lines[0], lines[1:])
         pages.append(page)
         page_size = maximum(page_size, page.size)
     self.pages = pages
     bf = self.button_font
     b1 = Button("Prev Page", font=bf, action=self.prev_page)
     b2 = Button("Menu", font=bf, action=self.go_back)
     b3 = Button("Next Page", font=bf, action=self.next_page)
     b = self.margin
     page_rect = Rect((b, b), page_size)
     gap = (0, 18)
     b1.topleft = add(page_rect.bottomleft, gap)
     b2.midtop = add(page_rect.midbottom, gap)
     b3.topright = add(page_rect.bottomright, gap)
     Screen.__init__(self, shell, **kwds)
     self.size = add(b3.bottomright, (b, b))
     self.add(b1)
     self.add(b2)
     self.add(b3)
     self.prev_button = b1
     self.next_button = b3
     self.set_current_page(0)
Пример #20
0
    def __init__(self, robot, game):
        self.robot = robot
        self.game = game
        self.startPosition = (400,400)
        start = BuildButton("tobuildscreen", pygame.Rect(scrright-200, scrbottom-100, 200, 100), "img/back_button_big.png", BuildButton.clicked, self)
        buy = BuyButton("buythings", pygame.Rect(500, scrbottom-140, 400,150), "img/buy_button.png", BuyButton.clicked, self)
        font1 = pygame.font.SysFont("Arial", 40)
        self.moneyLabel = ScreenText("moneytext", "Money: "+str(self.robot.money), pygame.Rect(WINDOWWIDTH-225, 0, 200, 50), font1)
        motorLabel = planes.Plane("motorLabel", pygame.Rect(scrleft,scrtop,170,50), draggable=False, grab=False)
        motorLabel.image = pygame.image.load("img/motorupgrade_label.png")
        mu1 = MotorUpgrade("mu1", pygame.Rect(scrleft,scrtop+60,50,50), "img/motorupgrade_1.png", 100, 0.3, 1, self)
        mu2 = MotorUpgrade("mu2", pygame.Rect(scrleft+60,scrtop+60,50,50), "img/motorupgrade_2.png", 200, 0.2, 2, self)
        mu3 = MotorUpgrade("mu3", pygame.Rect(scrleft+120,scrtop+60,50,50), "img/motorupgrade_3.png", 300, 0.1, 3, self)
        self.shoppingcart = ShoppingCart("shoppingcart", pygame.Rect(350,50,800,600), self)
        self.shoppingcart.image = pygame.image.load("img/shoppingcart.png")

        bumperLabel = planes.Plane("bumperLabel", pygame.Rect(scrleft, mu3.rect.bottom + 30, 170, 50), draggable=False, grab=False)
        bumperLabel.image = pygame.image.load("img/bumperupgrade_label.png")
        bu1 = BumperUpgrade("bu1", pygame.Rect(scrleft, bumperLabel.rect.bottom + 10, 50, 50), "img/bumperupgrade_1.png", 100, 7, 1, self)
        bu2 = BumperUpgrade("bu2", pygame.Rect(scrleft+60, bumperLabel.rect.bottom + 10, 50, 50), "img/bumperupgrade_2.png", 200, 5, 2, self)
        bu3 = BumperUpgrade("bu3", pygame.Rect(scrleft+120, bumperLabel.rect.bottom + 10, 50, 50), "img/bumperupgrade_3.png", 300, 3, 3, self)
        self.costInCartlabel = ScreenText("costincart", "Cost in Cart: 0", pygame.Rect(500, 50, 400, 50), font1)

        buttons = [start, buy]
        self.upgrades = [mu1, mu2, mu3, bu1, bu2, bu3]
        self.actorsWithoutDesc = [self.shoppingcart, motorLabel, bumperLabel, self.moneyLabel, self.costInCartlabel] + self.upgrades
        self.actors = self.actorsWithoutDesc
        Screen.__init__(self,buttons,self.actors,BLACK)
Пример #21
0
 def __init__(self, **args):
     self.choices = ['RETURN', 'P1 CONTROLS', 'P2 CONTROLS', 'MUSIC VOLUME', 'SFX VOLUME', 'AI DIFFICULTY', 
                     'SHOW HITBOXES', 'NUMBER OF ROUNDS', 'TIMER']
     self.extra = {}
     self.extra['MUSIC VOLUME'] = self.extra['SFX VOLUME'] = [0, 25, 50, 75 ,100]
     self.extra['NUMBER OF ROUNDS'] = [1, 3, 5]
     self.extra['SHOW HITBOXES'] = ['YES', 'NO']
     self.extra['AI DIFFICULTY'] = ['GIANCARLO', 'VERY EASY', 'EASY', 'NORMAL', 'HARD', 'VERY HARD']
     self.extra['TIMER'] = [20, 30, 45, 99]
     self.config = {}
     self.config['MUSIC VOLUME'] = 2
     self.config['SHOW HITBOXES'] = 0
     self.config['SFX VOLUME'] = 2
     self.config['NUMBER OF ROUNDS'] = 2
     self.config['AI DIFFICULTY'] = 3
     self.config['TIMER'] = 2
     self.volume = 50
     self.nrounds = 2
     keycond = lambda: not self.done
     Screen.__init__(self, 'system/title', keycond=keycond, **args)
     self.f = self.area.font['metal']
     self.incx = 0
     self.x, self.y = 8, 8
     self.choice = 0
     self.setting = lambda configname: self.extra[configname][self.config[configname]]
    def setup(self,
              nrows,
              nrows_center = 1,
              check_width = None,
              check_width_center = 0.5,
              check_color1 = 'white',
              check_color2 = 'black',
              screen_background_color = 'neutral-gray',
              show_fixation_dot = False,
              flash_rate_left = DEFAULT_FLASH_RATE,
              flash_rate_right = DEFAULT_FLASH_RATE,
              flash_rate_center = DEFAULT_FLASH_RATE,
              #rate_compensation = None,
              vsync_patch = None,
             ):
        Screen.setup(self,
                     background_color = screen_background_color,
                     vsync_patch = vsync_patch,
                     )

        #run colors through filter to catch names and convert to RGB
        check_color1 = COLORS.get(check_color1, check_color1)
        check_color2 = COLORS.get(check_color2, check_color2)

        # set checkerboard-related attributes
        if check_width is None:
            check_width = 2.0/nrows #fill whole screen
        self.board_width = check_width*nrows
        self.board_width_center = check_width_center * nrows_center
        self.nrows = nrows
        self.CB1 = CheckerBoard(nrows, check_width, color1 = check_color1, color2 = check_color2, show_fixation_dot = show_fixation_dot)
        self.CB2 = CheckerBoard(nrows, check_width, color1 = check_color2, color2 = check_color1, show_fixation_dot = show_fixation_dot) #reversed pattern
        self.CB1_center = CheckerBoard(nrows_center, check_width_center, color1 = check_color1, color2 = check_color2, show_fixation_dot = False)#show_fixation_dot)
        self.CB2_center = CheckerBoard(nrows_center, check_width_center, color1 = check_color2, color2 = check_color1, show_fixation_dot = False)#show_fixation_dot)
        self.CB_cycle_left = itertools.cycle((self.CB1,self.CB2))
        self.CB_cycle_right = itertools.cycle((self.CB1,self.CB2))
        self.CB_cycle_center = itertools.cycle((self.CB1_center,self.CB2_center))

        # set time-related attributes
        self._last_CB_change_time_left = None
        self._last_CB_change_time_right = None
        self._last_CB_change_time_center = None
        self.flash_rate_left  = flash_rate_left
        self.flash_interval_left = 1.0/flash_rate_left
        self.flash_rate_right = flash_rate_right
        self.flash_interval_right = 1.0/flash_rate_right
        self.flash_rate_center = flash_rate_center
        self.flash_interval_center = 1.0/flash_rate_center
        #self.rate_compensation = rate_compensation

        # get useful coordinate values for checkerboard rendering locations
        self.xC, self.yC = (-0.5*self.board_width,-0.5*self.board_width)
        self.xL, self.yL = (self.xC - 0.7*self.screen_right, self.yC)
        self.xR, self.yR = (self.xC + 0.7*self.screen_right, self.yC)

        # some lists for checking things
        self.vals = itertools.cycle((1,0))
        self.t_list = []
        self.val_list = []
        self.vals_current = self.vals.next()
Пример #23
0
    def __init__(self,gamemodel):

        self.win = 0
        self.gamemodel = gamemodel
        self.buttons = []
        self.actors = []
        self.howManyRays = 0
        self.howManySharks = 0
        self.howManyScallops = 0



        self.rayOffset = 0
        self.sharkOffset = 0
        self.scallopOffset = 0

        self.rayX = 0
        self.sharkX = 0
        self.scallopX = 0

        self.timesteps = 0

        font1 = pygame.font.SysFont("Arial", 20)
        font2 = pygame.font.SysFont("Arial", 70)
        self.timeLabel = ScreenText("timetext", "Timestep: "+str(self.timesteps), pygame.Rect(WINDOWWIDTH-270,0,250,40), font1)
        self.numrayLabel = ScreenText("raytext", "Rays: "+str(self.howManyRays), pygame.Rect(70,0,150,30), font1)
        self.changerayLabel = ScreenText("changeraytext", "Change: "+str(self.howManyRays), pygame.Rect(70,40,150,30), font1)
        self.numsharkLabel = ScreenText("sharktext", "Sharks: "+str(self.howManySharks), pygame.Rect(300,0,150,30), font1)
        self.changesharkLabel = ScreenText("changesharktext", "Change: "+str(self.howManySharks), pygame.Rect(300,40,150,30), font1)
        self.numscallopLabel = ScreenText("scalloptext", "Scallops: "+str(self.howManyScallops), pygame.Rect(530,0,150,30), font1)
        self.changescallopLabel = ScreenText("changescalloptext", "Change: "+str(self.howManyScallops), pygame.Rect(530,40,150,30), font1)

        self.winLabel = ScreenText("wintext", "YOU WIN!", pygame.Rect(0,0,1200,750), font2)
        buttonReset = ResetButton("reset", "img/reset_button.png", pygame.Rect(8*WINDOWWIDTH/10-40,8*WINDOWHEIGHT/10-30, 2*WINDOWWIDTH/10, WINDOWHEIGHT/10), ResetButton.clicked, self)
        button0 = TimeStepButton("time", "img/timestep_button.png", pygame.Rect(8*WINDOWWIDTH/10-40,7*WINDOWHEIGHT/10-40, 2*WINDOWWIDTH/10, WINDOWHEIGHT/10), TimeStepButton.clicked, self)
        button1 = RayButton("ray","img/ray.png",pygame.Rect(8.5*WINDOWWIDTH/10-30,WINDOWHEIGHT/10,WINDOWWIDTH/10,WINDOWHEIGHT/10),RayButton.clicked, self)
        button2 = SharkButton("shark","img/shark.png",pygame.Rect(8.5*WINDOWWIDTH/10-30,2*WINDOWHEIGHT/10 + 10,WINDOWWIDTH/10,WINDOWHEIGHT/10),SharkButton.clicked, self)
        button3 = ScallopButton("scallop", "img/scallop.png", pygame.Rect(8.5*WINDOWWIDTH/10-30,3*WINDOWHEIGHT/10 + 20, WINDOWWIDTH/10, WINDOWHEIGHT/10), ScallopButton.clicked, self)
        
        ###########
        buttonback = GBackButton("back", "img/back_button_ingame.png", pygame.Rect(8*WINDOWWIDTH/10-40, 9*WINDOWHEIGHT/10-20, 2*WINDOWWIDTH/10, WINDOWHEIGHT/10), BackButton.clicked, self)
        self.buttons.append(buttonback)
        ##########
        self.buttons.append(buttonReset)
        self.buttons.append(button0)
        self.buttons.append(button1)
        self.buttons.append(button2)
        self.buttons.append(button3)
        #self.buttons.append(button4)

        self.actors.append(self.timeLabel)
        self.actors.append(self.numrayLabel)
        self.actors.append(self.changerayLabel)
        self.actors.append(self.numsharkLabel)
        self.actors.append(self.changesharkLabel)
        self.actors.append(self.numscallopLabel)
        self.actors.append(self.changescallopLabel)

        Screen.__init__(self, self.buttons, self.actors, "img/Background_modsim.png")
Пример #24
0
class Canossa(tff.DefaultHandler,
              CSIHandlerTrait,
              ESCHandlerTrait):

    __cpr = False
    dirty = True

    def __init__(self,
                 screen=None,
                 termenc="UTF-8",
                 termprop=None,
                 visibility=False,
                 resized=True):
        """
        >>> from screen import MockScreenWithCursor
        >>> screen = MockScreenWithCursor()
        >>> screen.getyx()
        (0, 0)
        >>> canossa = Canossa(screen=screen, resized=False)
        """

        if screen:
            self.screen = screen
        else:
            import sys
            from screen import Screen
            # make screen
            # get current position
            result = _get_pos_and_size(sys.stdin, sys.stdout)
            if result:
                row, col, y, x = result
                self.screen = Screen(row, col, y, x, termenc, termprop)

        self._visibility = visibility
        self.__cpr = False
        self._resized = resized

        CSIHandlerTrait.__init__(self)
        ESCHandlerTrait.__init__(self)


    def handle_csi(self, context, parameter, intermediate, final):
        """
        >>> from screen import MockScreenWithCursor
        >>> screen = MockScreenWithCursor()
        >>> parser = _generate_mock_parser(screen)
        """

        if self._resized:
            self._resized = False
            self.screen.adjust_cursor()
        try:
            return self.dispatch_csi(context, parameter, intermediate, final)

        except Exception, e:
            mnemonic = 'CSI %s %s %s' % (' '.join(map(chr, parameter)), ' '.join(map(chr, intermediate)), chr(final)) 
            logging.error("handle_csi: %s" % mnemonic)
            logging.error("handle_csi: %s" % repr(e))
        return True
Пример #25
0
    def __init__(self, parent=None, width=800, height=800):
        """ initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope")
        # Modelethreading.Thread(None, affiche, None, (200,), {'nom':'thread a'}) 
        self.time = 0
        self.signal = None
        # # Vues
        # self.menuBar         = MenuBar(parent=self)
        # self.screen          = Screen(parent=self)
        # self.frame = Frame(master=self)
        # # Controleurs
        # self.time_control = TimeBase(parent=self)
        # self.signal_controlX = Generator(parent=self, name="X", color="red")
        # self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        # # Affichage Vues, Controleurs
        # self.menuBar.pack()
        # self.screen.pack()

        # self.signal_controlX.pack(side="left")
        # self.signal_controlY.pack(side="left")
        # self.time_control.pack()

        # Vues
        self.menuBar          = MenuBar(parent=self)
        self.screenT          = Screen(parent=self)
        self.screenXY         = Screen(parent=self)
        # Controleurs
        self.signal_controlX = Generator(parent=self, name="X", color="red")
        self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        self.signal_controlXY = Generator(parent=self, name="XY", color="blue")
        self.time_control = TimeBase(parent=self)
        self.varX  = IntVar()
        self.varY  = IntVar()
        self.varXY = IntVar()
        self.showX = Checkbutton(parent, text="X", variable=self.varX, command=lambda: self.update_show("X"))
        self.showY = Checkbutton(parent, text="Y", variable=self.varY, command=lambda: self.update_show("Y"))
        self.showXY = Checkbutton(parent, text="XY", variable=self.varXY, command=lambda: self.update_show("XY"))
        self.varX.set(1)
        self.varY.set(1)
        self.varXY.set(1)

        # Affichage Vues, Controleurs
        self.menuBar.grid(column=0, row=0)
        self.screenT.grid(column=0,row=1)
        self.screenXY.grid(column=1,row=1)
        self.signal_controlX.grid(column=0, row=2)
        self.signal_controlY.grid(column=0, row=3)
        self.time_control.grid(column=0, row=4)

        self.showX.grid(column=1, row=2)
        self.showY.grid(column=1, row=3)
        self.showXY.grid(column=1, row=4)

        self.configure(width=width, height=height)
Пример #26
0
 def __init__(self):
     dropBig = DropZone('bigDrop', pygame.Rect(200, 300, 200, 200))
     self.materials = []
     for i in range(0,3):
         self.materials.append(Material("mat"+str(i), pygame.Rect((400, 600/(len(self.materials)+1) * i, 20, 20))))
     self.dropZones = [dropBig]
     self.actors = self.dropZones + self.materials
     Screen.__init__(self, [], self.actors, (0,128,0))
Пример #27
0
 def __init__(self, main):
     Screen.__init__(self, main)
     self.introtheme = pygame.mixer.music.load("../sound/lifdoff.ogg")
     self.logo = pygame.image.load("../img/lifdofflogo.png")
     self.overlay = pygame.Surface((1280, 800), pygame.SRCALPHA)
     self.overlay.fill((0xFF, 0xFF, 0xFF, 192))
     self.yloc = 500-62
     self.playing = 0
Пример #28
0
	def __init__(self, p1, p2, **args):
		cond = lambda: not self.done
		Screen.__init__(self, 'system/vs', keycond=cond, **args)
		self.p1, self.p2 = p1, p2
		self.c = [RGB(255,0,0,32), RGB(0,255,0,32), RGB(0,0,255,32)]
		self.f = self.area.font['menuwhite']
		self.barmax = p1.totalframes + p2.totalframes
		self.bar = 0
Пример #29
0
 def __init__(self, screen):
     Screen.__init__(self, screen)
     self.font = pygame.font.Font("assets/fonts/blogger-sans.ttf", 32)
     self.text = self.font.render("Pygame Snake", True, (0, 0, 0))
     self.fontbtn = pygame.font.Font("assets/fonts/blogger-sans.ttf", 22)
     self.textnew = self.fontbtn.render("New Game", True, (0, 0, 0))
     self.textquit = self.fontbtn.render("Quit", True, (0, 0, 0))
     self.choice = 0
Пример #30
0
    def __init__(self, main):
        Screen.__init__(self, main)
        self.waves = Waves()
        self.smallerfont = pygame.font.Font(None, 50)  # font for menu items

        def go_back(mpos):
            self.main.change_screen("main")
        self.clickbox.append((30, 650, 102, 50), go_back)
Пример #31
0
 def __init__(self, asteroids_amount):
     """
     creates a new game with the given amount if asteroids
     :param asteroids_amount:
     """
     self.__screen = Screen()
     self.__player_score = 0
     self.__screen_max_x = Screen.SCREEN_MAX_X
     self.__screen_max_y = Screen.SCREEN_MAX_Y
     self.__screen_min_x = Screen.SCREEN_MIN_X
     self.__screen_min_y = Screen.SCREEN_MIN_Y
     self.__screen_min = Vector(self.__screen_min_x, self.__screen_min_y)
     self.__screen_max = Vector(self.__screen_max_x, self.__screen_max_y)
     # generating ship and placing on screen
     self.__ship = self.gen_ship()
     self.__ship_life = 3
     #  creating and registering all asteroids
     self.__astroids_list = self.__generate_asteroids(asteroids_amount)
     self.__torpedos_list = list()
     self.__game_length = 0
Пример #32
0
def main():
    oled = get_oled()
    screen = Screen(oled)
    wait_for_networking()
    conf = get_conf()
    APPID = conf['APPID']
    button = Pin(BUTTON_A_PIN, Pin.IN, Pin.PULL_UP)
    show_random_weather(screen, APPID)
    while True:
        if not button.value():
            show_random_weather(screen, APPID)
Пример #33
0
def writeScreen():
    screen = Screen()
    print str(screen)
    fil = open("out2.bin", "wb")
    msg = bytearray()
    msg.extend(struct.pack("BB", screen.height, screen.width))
    for row in screen.screen:
        for asciipixel in row:
            msg.extend(struct.pack("BB", asciipixel.ascii, asciipixel.color))
    fil.write(msg)
    fil.close()
Пример #34
0
    def __init__(self, DHT22_pin, lightsensor_pin, re_data, re_clock,
                 re_switch, API_key, db_file, base_path):
        """ Setup of all the components """

        self.screen = Screen()
        # Show info on screen to inform Pi is booting
        self.screen.display_text("BOOTING")

        self.db = Database(db_file, base_path)
        # self.excel = Excel(excel_file_name)

        self.climate = ClimateData(DHT22_pin, API_key)

        self.lightsensor = LightSensor(lightsensor_pin)
        # Setup interrupt for when light changes
        GPIO.add_event_detect(lightsensor_pin,
                              GPIO.RISING,
                              callback=self.light_changed,
                              bouncetime=200)

        self.rotary = RotaryEncoder(re_data, re_clock, re_switch)
        # setup interrupts for rotary encoder is turned
        GPIO.add_event_detect(re_data,
                              GPIO.RISING,
                              callback=self.rotary_encoder_changed)
        GPIO.add_event_detect(re_clock,
                              GPIO.RISING,
                              callback=self.rotary_encoder_changed)
        GPIO.add_event_detect(re_switch,
                              GPIO.FALLING,
                              callback=self.rotary_encoder_clicked,
                              bouncetime=200)

        # setup different pages
        self.pages = []
        self.pages.append(PAGES.CurrentWeatherPage(self, base_path))
        self.pages.append(PAGES.MinMaxTemperaturePage(self))
        self.pages.append(PAGES.SettingsPage(self, base_path))

        # index of the current page
        self.current_page = 0
Пример #35
0
 def __init__(self):
     sys.path.append(os.path.abspath('.'))
     config = data_make.load()
     self.screen = Screen(config)
     try:
         self.modules = Modules('Games', self.screen)
     except:
         pass
     #self.interface = Interface(self.screen)
     self.clock = pygame.time.Clock()
     pygame.mouse.set_visible(True)
     self.mouse_focus = False
     self._pause = False
     self._fps = 120 #2*2*2*3*5
     self._running = True
     self.timers = Timers(self._fps)
     self.timers.add_new("ta_move", self.screen.textareas.move, 10, type='s')
     self.timers.add_new("pause", lambda:self.screen.indicators.state('pause'), 2, None, 's')
     #self.timers.add_new("focus_test", self.focusTest, 2, type='s')
     #print self.timers.listType('s')
     sys_keys = {
         #(key, KEYUP/KEYDOWN): (func, modifiers expected, modifiers allowed)
         (K_p, KEYDOWN): (self.pause, KMOD_CTRL),
         (K_i, KEYDOWN): (self.edit, KMOD_CTRL),
         #(K_e, KEYDOWN): (lambda:self.screen.textareas[0].edit(not bool(self.screen.textareas[0].edit())), KMOD_CTRL),
         (K_q, KEYDOWN): (self.stop, KMOD_CTRL),
         (K_r, KEYDOWN): (lambda:self.screen.displays.main.fill((random.randint(0,8), random.randint(0, 18), random.randint(1,10), random.randint(1, 20)), 0x81, random.randint(0, 0xffffff), 0), None),
         (K_t, KEYDOWN): (lambda:self.screen.displays.main.put_text((random.randint(0,8), random.randint(0, 18), random.randint(1,10), random.randint(1, 20)), 'test', random.randint(0, 0xffffff), 0), None),
         (K_l, KEYDOWN): (self.test, KMOD_CTRL),
         (K_c, KEYDOWN): (self.compile_conf, KMOD_CTRL),
     }
     self.keyboard = Keyboard(sys_keys, {})
     self.rects = (
     #    (self.screen.textarea1, Rect(self.screen.textarea1)),
     )
     self.clicked = -1
     self.pos = [0,0]
     self.editing = False # <<<<<<<<<<<
     #self.test()
     self.ui = UI(self.screen)
     self.run()
Пример #36
0
def main_page(login, password):
    """Loads main page of the user"""

    main_header = """
            ACCOUNT_________________
            Welcome to your page
            What do you want to do?
            """

    choice = namedtuple('Choice', ['desc', 'func'])

    main_choices = (
        choice('Search for a book', ac.search_for_books),
        choice('Check your books', ac.check_my_books),  # LOGIN?
        choice('Rent a book', ac.rent_book),  # LOGIN?
        choice('Change your account data', ac.change_account_details),
        choice('Log out', exit.exit_to_intro))

    main_page = Screen(main_header, main_choices, login, password)
    while True:
        main_page.activate()
Пример #37
0
    def __init__(self, screen = None,  level = 1, score = 0):
        self.audio = Audio()   # Runs sounds/music
        self.level = level
        self.score = score

        if screen:
            self.screen = screen
        else:
            self.screen = Screen(setup = False) # Don't go into curses mode yet

        # Board on which we will be playing
        self.board = Board(screen = self.screen, level = self.level, score = self.score, game = self)

        self.menus   = {}  # Map strings like 'main-menu' to menu objects
        self.config  = {}  # Map strings like 'sleep-time' to config options
        self.actions = {}  # Map strings like 'apple' to actions 

        self.handle = void  # An empty function

        # Hard Coded Presets -- should be handled by config dictionary
        self.sleeptime = 0.17
Пример #38
0
    def __init__(self, asteroids_amnt):
        """
        The init of the Game Runner class

        :param asteroids_amnt: the number of asteroid we want in the game
        """

        # Init the attribute
        self._screen = Screen()
        self.ship = Ship(INITIAL_SHIP_X, INITIAL_SHIP_Y, INITIAL_SHIP_SPEED_X,
                         INITIAL_SHIP_SPEED_Y)
        self.screen_max_x = Screen.SCREEN_MAX_X
        self.screen_max_y = Screen.SCREEN_MAX_Y
        self.screen_min_x = Screen.SCREEN_MIN_X
        self.screen_min_y = Screen.SCREEN_MIN_Y
        self.asteroids_list = []
        self.torpedos_list = []
        self.score = 0

        # Creating the wanted amount of asteroid
        self.create_asteroids(asteroids_amnt)
Пример #39
0
def perform_action(p: Player, card_name: str, scr: Screen) -> None:
    """
    Plays a card in the player's hand.
    Once a card is successfully played, the card gets put on the player's discard pile.
    """
    for card in p.current_hand:

        # Found the card that we want to play
        if "action" in load_card(card).cardtype and card == card_name:
            # try:
            p.current_hand.remove(card)

            scr.log("Played card: {0}".format(card_name))
            action_performed: bool = globals()[load_card(card).action](p, scr)

            if action_performed:
                p.cards_played.append(card)
                p.actions_left -= 1
            else:
                p.current_hand.append(card)
            break
Пример #40
0
 def __init__(self, asteroids_amnt=DEFAULT_ASTEROIDS_NUM):
     """
     A constructor for asteroids game object.
     :param asteroids_amnt: the starting number of asteroids on the board.
     if there was no input the value will be DEFAULT_ASTEROIDS_NUM .
     """
     self._screen = Screen()
     # the borders of the screen. The maximum and minimum points
     # possible for movement on the screen.
     self.screen_max_x = Screen.SCREEN_MAX_X
     self.screen_max_y = Screen.SCREEN_MAX_Y
     self.screen_min_x = Screen.SCREEN_MIN_X
     self.screen_min_y = Screen.SCREEN_MIN_Y
     self.__ship = Ship()  # create a ship object.
     self.__asteroid_amount = asteroids_amnt
     # the starting amount of asteroids in the game.
     self.__asteroids = self._add_asteroids_to_game()
     # list of all the asteroids that are in the game.
     self.__torpedos = list()
     # a list of all the torpedo objects. starts empty.
     self.__sum_points = SUM_POINTS
Пример #41
0
def main():
    s = Screen(fg='white', bg='black')
    s.cls('green')
    w = Window(s, 5, 5, 45, 30)
    w.cls()

    # for i in range(10):
    #     print >>w, i

    w2 = Window(s, 66, 5, 120, 10)
    w2.cls()

    # for i in range(31):
    #     print >>w, 'a' * i
    #     time.sleep(0.4)
    #
    # print >>w, 'abcdefghi\njklmnopqrstuvwxyz'
    # print >>w, 'abcdefghijklmnopqrstuvwxyz'
    # print >>w, 'HI'

    print >> w, open(__file__).read()

    # print >>w2, 'world'
    # print >>w2, 'YO'

    s.gotoxy(s.left, s.bottom)
Пример #42
0
class AVE:
    def __init__(self, folder="games"):
        from screen import Screen
        self.screen = Screen()
        self.character = Character(self.screen)
        self.games = Games(folder, self.screen, self.character)

    def start(self):
        self.screen.print_titles()
        game_to_load = self.screen.menu(self.games.titles(), 8, titles=True)
        self.games[game_to_load].load()
        again = True
        while again:
            again = False
            try:
                self.games[game_to_load].begin()
            except AVEGameOver:
                next = self.screen.gameover()
                self.character.reset()
                if next == 0:
                    again = True
                if next == 2:
                    raise AVEQuit
            except AVEToMenu:
                pass

    def exit(self):
        self.screen.close()
Пример #43
0
class GameRunner:
    def __init__(self, asteroids_amount):
        self.__screen = Screen()

        self.__screen_max_x = Screen.SCREEN_MAX_X
        self.__screen_max_y = Screen.SCREEN_MAX_Y
        self.__screen_min_x = Screen.SCREEN_MIN_X
        self.__screen_min_y = Screen.SCREEN_MIN_Y

        x = random.randint(self.__screen_min_x, self.__screen_max_x)
        y = random.randint(self.__screen_min_y, self.__screen_max_y)
        Screen.draw_ship(x, y, INIT_DEGREE)

    def run(self):
        self._do_loop()
        self.__screen.start_screen()

    def _do_loop(self):
        # You don't need to change this method!
        self._game_loop()

        # Set the timer to go off again
        self.__screen.update()
        self.__screen.ontimer(self._do_loop, 5)

    def _game_loop(self):
        # Your code goes here
        pass
Пример #44
0
def phoneStart():

    logger = Logger()

    logger.pushLogMsg("Starting GSM main process")

    bus = BusDriver(logger)

    while bus.isBusInitialized() == False:

        if bus.isBusInErrorState() == True:
            #Well, this was unexpected... We should return
            #from the app. Or maybe attempt a reset?
            logger.pushLogMsg("Init: Bus error!")
            return

    modem = SIM900(bus, logger)  #Constructor starts the Chip init

    while modem.isChipInitialized() == False:

        if modem.isChipInErrorState() == True:
            #Well, this was unexpected... We should return
            #from the app. Or maybe attempt a reset?
            logger.pushLogMsg("Init: Chip error!")
            return

    keypad = Keypad(logger)
    if keypad.isInErrorState() == True:
        logger.pushLogMsg("Init: Keypad error!")
        return

    screen = Screen(logger)
    if screen.isInErrorState() == True:
        logger.pushLogMsg("Init: Screen error!")
        return

    #Init is complete, turn into the main part of the app
    #This call will be blocking for the lifetime of the app
    #and return only after an error was detected
    mainPhoneProcess(screen, keypad, bus, modem, logger)
Пример #45
0
    def __init__(self, asteroids_amount):
        """
        Game contains
        :param asteroids_amount:
        """
        self.__screen = Screen()

        # Dimensions of the space in which the game is played
        self.__screen_max_x = Screen.SCREEN_MAX_X
        self.__screen_max_y = Screen.SCREEN_MAX_Y
        self.__screen_min_x = Screen.SCREEN_MIN_X
        self.__screen_min_y = Screen.SCREEN_MIN_Y

        # Initialization of ship
        ship_x = random.randint(Screen.SCREEN_MIN_X, Screen.SCREEN_MAX_X)
        ship_y = random.randint(Screen.SCREEN_MIN_Y, Screen.SCREEN_MAX_Y)
        self.__screen.draw_ship(ship_x, ship_y, 0)
        self.__player = Ship(ship_x, ship_y, 0, 0, 0)

        # Initialisation of asteroids.
        ast_speeds = list(range(-4, 0)) + list(range(1, 5))
        ast_xs, ast_ys = self.non_colliding_start(self.__player,
                                                  asteroids_amount)
        self.__ast_size = 3
        self.__ast_ls = []
        for i in range(asteroids_amount):
            as_x_sp = random.choice(ast_speeds)
            as_y_sp = random.choice(ast_speeds)
            asteroid = Asteroid(ast_xs[i], ast_ys[i], as_x_sp, as_y_sp,
                                self.__ast_size)
            self.__ast_ls.append(asteroid)
            self.__screen.register_asteroid(asteroid, self.__ast_size)
            self.__screen.draw_asteroid(asteroid, ast_xs[i], ast_ys[i])

        self.__life_count = 3  #Life count of ship
        self.__score = 0  # Game score

        #Lists of torpedos and special torpedos in play
        self.__torpedo_ls = []
        self.__sp_torpedo_ls = []
Пример #46
0
def purchase_card(p: Player, card: str, scr: Screen) -> bool:
    """
    The transaction method. Buys a card for a player using their balance.
    The purchased card gets taken out of the shop, and placed into the player's discard pile.
    """
    # Card doesn't exist in the store
    if card not in s_store:
        scr.log("This card doesn't exist in the store!", 2)
        return False

    # Card has 0 left in the store
    elif s_store.get(card) == 0:
        scr.log("This card cannot be bought anymore!", 2)
        return False

    # Player can't purchase any more cards
    elif p.purchases_left == 0:
        scr.log("You can't buy any more cards this turn!", 2)
        return False

    else:
        # Load in the card
        card_bought = load_card(card)

        if card_bought.cost > (p.current_hand_balance + p.bonus_coins -
                               p.amount_spent):
            scr.log("Insufficient funds!", 2)
            return False

        # Confirm purchase
        p.purchases_left -= 1
        scr.log("Bought card: {0}".format(card), 1)

        p.add_discardpile_card(card_bought.name)

        # Subtract cost from balance
        p.amount_spent += card_bought.cost

        remove_card(card, scr)
        return True
Пример #47
0
class ScreenTest(unittest.TestCase):
    def setUp(self):
        win_api = MagicMock()
        screen_grabber = MagicMock()
        screen_grabber.grab.return_value = None
        self.res_return = 500
        win_api.GetSystemMetrics.return_value = self.res_return
        self.screen = Screen(1, win_api, screen_grabber)

    def test_setup_sets_resolution(self):
        self.assertEqual(self.screen.res, (self.res_return, self.res_return))

    def test_setup_sets_x_offset(self):
        self.assertEqual(self.screen.x_offset, 0)

    def test_setup_sets_y_offset(self):
        self.assertEqual(self.screen.y_offset, 0)

    def test_get_screen(self):
        self.screen.get_screen(self.screen.number)
        self.screen.image_grabber.grab.assert_called()

    def test_invalid_screen_number(self):
        with self.assertRaises(ValueError):
            self.screen.get_screen(5)

    def test_build_locations(self):
        with patch('screen.Screen._get_card_locations',
                   return_value=[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0),
                                 (0, 0, 0, 0)]):
            self.screen.build_locations("img")
            self.screen._get_card_locations.assert_called()
Пример #48
0
def main():
    """
    Entry point
    """

    def game_update(pit_info):
        """
        Boucle principale du jeu
        """
        if not core.update(event_loop.get()):
            return False
        screen.update(core.render(screen.get_size(), screen.g_pos(), pit_info))
        return True

    try:
        # Ecran
        screen = Screen()
        #Coeur du jeu
        core = Core()
        # boucle d'evenements
        event_loop = MyEventLoop()
        event_loop.start()

        timer = Pit(0.1, game_update)
        timer.start()

        screen.stop()
        print("Votre score : {}$".format(core.player.money))
        return True

    finally:
        # Stop secu
        screen.stop()
Пример #49
0
 def __init__(self, asteroids_amount):
     """
     :param asteroids_amount: the number of asteroids that are in the start
     of the game by user input or defult if there is no input
     :initializing: the parameters to the game
     """
     self._screen = Screen()
     self.ship = Ship()
     self.screen_max_x = Screen.SCREEN_MAX_X
     self.screen_max_y = Screen.SCREEN_MAX_Y
     self.screen_min_x = Screen.SCREEN_MIN_X
     self.screen_min_y = Screen.SCREEN_MIN_Y
     self.asteroids_amount = asteroids_amount
     self.torpedo_lst = []
     self.asteroid_lst = []
     for i in range(self.asteroids_amount):
         # update asteroids
         asteroid = Asteroid(self.ship)
         self.asteroid_lst.append(asteroid)
         self._screen.register_asteroid(asteroid, asteroid.get_size())
     self.score = 0
     self.rotation = random.random() * 5
Пример #50
0
def main():
    automataDict = automata_IO.dfa_json_importer("./resources/automata.json")

    alphabet = automataDict["alphabet"]
    initialState = automataDict["initial_state"]
    transitions = automataDict["transitions"]
    acceptingStates = automataDict["accepting_states"]

    automata_IO.dfa_to_dot(automataDict, "automata", "./resources")

    automata = Automata(alphabet, initialState, transitions, acceptingStates)

    _ = Screen("./resources/automata.dot.svg", automata)
Пример #51
0
 def __init__(self, asteroids_amount=DEFAULT_ASTEROIDS_NUM):
     """This is the init of GameRunner."""
     self.__screen = Screen()
     self.__screen_max_x = Screen.SCREEN_MAX_X
     self.__screen_max_y = Screen.SCREEN_MAX_Y
     self.__screen_min_x = Screen.SCREEN_MIN_X
     self.__screen_min_y = Screen.SCREEN_MIN_Y
     self.__screen_ship = Ship(INIT_X, INIT_Y, 0, 0, 0)
     self.__screen_asteroids = []
     self.__screen_asteroids_amount = asteroids_amount
     for i in range(asteroids_amount):
         x_coordinate = INIT_ASTEROID_X
         y_coordinate = INIT_ASTEROID_Y
         x_velocity = random.choice(ASTEROID_VELOCITIES)
         y_velocity = random.choice(ASTEROID_VELOCITIES)
         size = INIT_ASTEROID_SIZE
         new_asteroid = Asteroid(x_coordinate, y_coordinate, x_velocity, y_velocity, size)
         self.__screen.register_asteroid(new_asteroid, size)
         self.__screen_asteroids.append(new_asteroid)
     self.__screen_torpedoes = []
     self.__screen_special_torpedoes = []
     self.__score = INIT_SCORES
Пример #52
0
def player_ship_place_test():
    while True:
        player_own_board = board_image.BoardImage()
        stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        stdscr.keypad(True)
        screen = Screen(stdscr, ".\screen_layout.txt")
        screen.print_screen_layout()
        game = Game(screen)
        for decks_number in [1, 2, 3, 4]:
            is_break, is_restart = game.place_player_ship(
                player_own_board, decks_number)
            if is_break or is_restart: break
        if is_break: break
        if is_restart: continue
        break
    curses.endwin()
    for i in range(10):
        print('\n')
        for j in range(10):
            print('{:>10}'.format(player_own_board.board[j][i]), end=" ")
Пример #53
0
 def __init__(self,player = None, initial_board = None, game_type = USER,size = 4, _cubes = 4, screen_h = 500, max_moves = -1, screen_w = 500,_debug = False,replay_history = None,store_in_db = True):
     if replay_history is None:
         self.board = Board(size,debug=_debug,cubes= _cubes,initial_board = initial_board)
     else:
         self.board = Board(size = len(replay_history[HISTORY[0]]),initial_board= replay_history[HISTORY[0]],history= replay_history)
     self.player = player
     self.store_in_db = store_in_db
     try:
         self.player_name = player.name
     except:
         self.player_name = 'user'
     if game_type!=NO_SCREEN:
         self.screen = Screen(screen_h,screen_w,self.board)
     self.history = {HISTORY[0] :[ row[:] for row in self.board.board],HISTORY[1]:[],HISTORY[2]:-1,HISTORY[3]: False,HISTORY[4]: -1,HISTORY[5]:self.player_name}
     self.finished = False
     if game_type == USER:
         self.run_game = self.run_game_user
     elif game_type== NO_SCREEN:
         self.run_game = self.run_game_no_screen
     elif game_type == SCREEN:
         self.run_game = self.run_game_screen
     self.max_moves = max_moves
Пример #54
0
def main():
    automataDict = automata_IO.dfa_json_importer("./resources/AFD.json")

    alphabet = automataDict["alphabet"]
    initialState = automataDict["initial_state"]
    transitions = automataDict["transitions"]
    acceptingStates = automataDict["accepting_states"]
    '''Monta a imagem a partir do Json passado'''
    automata_IO.dfa_to_dot(automataDict, "AFD", "./resources")

    automata = Automata(alphabet, initialState, transitions, acceptingStates)
    '''Screen recebe como parametro o caminho da imagem e também o objeto automato'''
    _ = Screen("./resources/AFD.dot.svg", automata)
Пример #55
0
def output(x, y):
    global screen
    if screen is None:
        from screen import Screen
        screen = Screen()
        screen.start()

    screen.plot(x, screen.height - y)
Пример #56
0
def main():
    oled = get_oled()
    screen = Screen(oled)
    screen.write('hello')

    for i in range(10):
        print(i)
        screen.write(MESSAGE % i)
Пример #57
0
class Terminal(IOBase):
    def __init__(self):
        super().__init__()

        self.keyboard = Keyboard()
        self.screen = Screen()

        self.poller = Timer(-1)

        self.poll_ref = self.poll
        self.schedule_poll_ref = self.schedule_poll
        self.screen_write_ref = self.screen.write

    def readinto(self, buf):
        return self.keyboard.readinto(buf)

    def write(self, byteslike):
        self.screen.write(byteslike)

    def poll(self, ignore=None):
        if self.keyboard.poll():
            uos.dupterm_notify(self)

        if self.screen.last_change:
            if time.ticks_diff(time.ticks_ms(),
                               self.screen.last_change) > DEBOUNCE_PERIOD:
                self.screen.update_screen()

        self.poller.init(period=10,
                         mode=Timer.ONE_SHOT,
                         callback=self.schedule_poll_ref)

    def schedule_poll(self, ignore=None):
        micropython.schedule(self.poll_ref, 0)

    def install(self):
        micropython.alloc_emergency_exception_buf(100)
        self.screen.running = True
        uos.dupterm(self)
        self.poller.init(period=10,
                         mode=Timer.ONE_SHOT,
                         callback=self.schedule_poll_ref)

    def uninstall(self):
        self.screen.running = False
        uos.dupterm(None)
        self.screen.clear_screen()
        self.screen.clear()
Пример #58
0
class GameMain:
    def __init__(self, myApp, screenSize):
        pygame.init()
        self.serverClient = ServerClient(self)
        self.serverClient.start(1/2.5)

        self.screen = Screen(*screenSize)
        self.screen.background = dark_gray

        self.myApp = myApp(self)
        self.keyEventHandeler = []

        self.exit = self.stop

    def start(self):
        self.sync = Sync(self.mainLoop, 1.0/60)
        self.sync.sync()

    def stop(self):
        self.myApp.close()
        self.sync.stop()
        self.serverClient.stop()
        sys.exit()

    def mainLoop(self):
        self.eventHandeler()
        self.myApp.update()
        self.render()

    def eventHandeler(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT: self.stop()
            self.myApp.eventAction(event)

    def render(self):
        self.screen.clear()
        self.myApp.render(self.screen)
        pygame.display.flip()
Пример #59
0
def computer_ship_place_test():
    computer_own_board = board_image.BoardImage()
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    screen = Screen(stdscr, ".\screen_layout.txt")
    game = Game(screen)
    for decks_number in [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]:
        game.random_place_ship(computer_own_board, decks_number)
    for i in range(10):
        print('\n')
        for j in range(10):
            print('{:>10}'.format(computer_own_board.board[j][i]), end=" ")
Пример #60
0
    def __init__(self):

        self.words_generator = WordGenerator('word.yml')
        self.layout = BoxLayout(orientation="vertical")
        self.keyboard = None
        self.control_panel = ControlPanel(self.start_timer, self.stop_ev,
                                          self.change_difficulty)
        self.timer = None
        self.stop_event = None
        self.tick_event = None
        self.ticks = MAX_TIME
        self.screen = Screen()
        self.difficulty = "Easy"
        super(TouchKeyboard, self).__init__()