Exemplo n.º 1
0
def start(screen):
    """
    Blits the start-menu.
    """
    title = pygame.font.Font('BebasNeue.ttf',72)
    instruct = pygame.font.Font('BebasNeue.ttf',26)
    color = getrgb("#FFFFFF")
    screen.fill(getrgb("#000000"))
    lines = ['Hit ENTER to play',"ESC to quit","P to pause",
             "N for new game", "L to change starting level",
             "M for main menu", "Arrow keys and space to move"]

    tetris = title.render("TETRIS",1,color)
    whitelines = [instruct.render(i,1,color) for i in lines]
    posns = [(93,246),(121,293),(124,340),(102,387),(50,481),(98,434),(34,528)]
    screen.blit(tetris,(95,139))
    for i in range(len(posns)):
        screen.blit(whitelines[i],posns[i])
    pygame.display.flip()
    while True:
        # keystroke handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                exit(0)
            if event.type == pygame.KEYDOWN:
                if (event.key == pygame.K_RETURN) or (event.key == pygame.K_n):
                    return 0
                elif event.key == pygame.K_l:
                    return getlevel(screen,color,instruct)
                elif event.key == pygame.K_ESCAPE:
                    exit(0)
Exemplo n.º 2
0
def getlevel(screen,color,typeface):
    """
    Blits the getlevel menu, and returns the level the user selects.
    """
    highlight = getrgb("#3CFF2D")
    screen.fill(getrgb("#000000"))
    levels = range(1,101)
    lines = [typeface.render(str(i),1,color) for i in levels]
    # each range is for a column. Five columns of 20 levels each.
    ranges = [range(a,b) for (a,b) in [(0,20),(20,40),(40,60),(60,80),(80,100)]]
    locs = []
    rectangles = {}
    # the list [57..285] represents the y-locations of each column.
    for j in zip(ranges,[57,114,171,228,285]):
        for k in j[0]:
            # center the text on the column
            w = lines[k].get_rect().width/2
            h = 32
            x = j[1]-w
            # %20 to divide the 100 levels into 5 columns. 34 is vertical px
            # distance between entries.
            y = (34*(k%20))+10
            screen.blit(lines[k],(x,y))
            # locs: map every level to (x,y) coord denoting start of rectangle
            locs.append((x,y))
            # rectangles: map every rectangle to its level.
            rectangles[(x,y,x+(2*w),y+h)] = k
    pygame.display.flip()
    # active: the level the user has moved their cursor over
    active = []
    while True:
        for event in pygame.event.get():
            x,y = pygame.mouse.get_pos()
            # could make this faster, but this is small-scale.
            for (x1,y1,x2,y2) in rectangles:
                # finds the rectangle the cursor is in
                if (x1 <= x <= x2) and (y1 <= y <= y2):
                    current = rectangles[(x1,y1,x2,y2)]
                    if current not in active: 
                        active.append(current)
                        # makes the text in the current rectangle green
                        screen.blit(typeface.render(str(levels[current]),1,highlight),(x1,y1))
                        pygame.display.flip()
            if len(active) > 1:
                # if the user has moved the cursor to another rectangle: make
                # the text in the previous rectangle white again.
                delete = active[0]
                pygame.draw.rect(screen,getrgb("#000000"),
                                 (locs[delete][0],locs[delete][1],35,32))
                screen.blit(lines[delete],locs[delete])
                pygame.display.flip()
                del active[0]
            if any(x==1 for x in pygame.mouse.get_pressed()):
                # if user clicks in rectangle: return the corresponding level
                return active[0]
            if event.type == pygame.QUIT: 
                exit(0)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    exit(0)
Exemplo n.º 3
0
 def states2img(self):
     vColor = [getrgb(SketchView.getColor(None, a)) for a in self.states]
     vGray = [getrgb('white') for a in self.states]
     imgColor = vector2rgb(vColor)
     imgGray = vector2rgb(vGray)
     self.hBloc = 30
     h = self.hBloc
     z = h / imgGray.height
     self.statesGray = imgGray.resize((int(imgGray.width * z), h))
     self.statesColor = imgColor.resize((int(imgColor.width * z), h))
Exemplo n.º 4
0
def makelines():
    """
    Makes lines for the gameover and pause screens. This runs just once in the
    start, to prevent unneccessary repeated executions.
    """
    global GOblacklines, GOwhitelines, Pblacklines, Pwhitelines
    GOlines = ['Game Over','Hit ENTER to play again','ESC to quit', 'M for main menu']
    Plines = ['Paused',"Hit p to resume"]
    typeface = pygame.font.Font('BebasNeue.ttf',32)
    GOblacklines = [typeface.render(i,1,getrgb("#000000")) for i in GOlines]
    GOwhitelines = [typeface.render(i,1,getrgb("#FFFFFF")) for i in GOlines]
    Pblacklines = [typeface.render(i,1,getrgb("#000000")) for i in Plines]
    Pwhitelines = [typeface.render(i,1,getrgb("#FFFFFF")) for i in Plines]
    return 
Exemplo n.º 5
0
	def tint(self, tint='#ffffff'):
		self.open()
		src = self.img
		if src.mode not in ['RGB', 'RGBA']:
			raise TypeError('Unsupported source image mode: {}'.format(src.mode))
		src.load()

		if type(tint) in [str, unicode]:
			tr, tg, tb = getrgb(tint)
			tl = getcolor(tint, "L")  # tint color's overall luminosity
		else:
			tr, tg, tb = tint
			tl = sum([tr,tg,tb])/3

		if not tl: tl = 1  # avoid division by zero
		tl = float(tl)  # compute luminosity preserving tint factors
		sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component adjustments

		# create look-up tables to map luminosity to adjusted tint
		# (using floating-point math only to compute table)
		luts = (map(lambda lr: int(lr*sr + 0.5), range(256)) +
				map(lambda lg: int(lg*sg + 0.5), range(256)) +
				map(lambda lb: int(lb*sb + 0.5), range(256)))
		l = grayscale(src)  # 8-bit luminosity version of whole image
		if Image.getmodebands(src.mode) < 4:
			merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
		else:  # include copy of src image's alpha layer
			a = Image.new("L", src.size)
			a.putdata(src.getdata(3))
			merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
			luts += range(256)  # for 1:1 mapping of copied alpha values

		self.img = Image.merge(*merge_args).point(luts)
		self.save()
		self.close()
Exemplo n.º 6
0
    def weights2img(self, i, prevLayer):
        # for neuron i build an image of the weights of height h and width tbd
        v1 = self.weights.T[i]
        w, h, pos = self.inputLayout
        z = self.hBloc / h

        v = self.autoscale(v1)
        tempPil = PILImage.new('L', [w, h])
        for k in range(len(v)):
            x1, y1 = pos[k]
            tempPil.putpixel([x1, y1], v[k])
        tempPil = tempPil.resize((int(w * z), int(h * z)))
        imgGray = tempPil.convert('RGB')

        v2 = prevLayer.states
        v2 = [v2[k] * v1[k] for k in range(len(v2))]
        v = self.autoscale2(v2)
        tempColor = PILImage.new('RGB', [w, h])
        tempPil = PILImage.new('L', [w, h])
        for k in range(len(v)):
            x1, y1 = pos[k]
            tempPil.putpixel([x1, y1], v[k])
            tempColor.putpixel([x1, y1], getrgb(getColor2(v2[k])))
        tempPil = tempPil.resize((int(w * z), int(h * z)))
        tempColor = tempColor.resize((int(w * z), int(h * z)))
        imgColor = tempPil.convert('RGB')
        imgColor = chops.multiply(tempColor, imgColor)
        return imgGray, imgColor
Exemplo n.º 7
0
def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv / tl,
                     (tr, tg, tb))  # per component adjustments

    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (map(lambda lr: int(lr * sr + 0.5), range(256)) +
            map(lambda lg: int(lg * sg + 0.5), range(256)) +
            map(lambda lb: int(lb * sb + 0.5), range(256)))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += range(256)  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)
Exemplo n.º 8
0
def makeblockimages():
    """
    Takes the size and colors of the blocks to make images of them.
    This is run just once in the start of the game.
    """
    for c in colors:
        newblock = pygame.Surface((blocksize,blocksize))
        newblock.fill(getrgb(c))
        blockimages[c] = newblock
    return
Exemplo n.º 9
0
def game(screen,startinglevel):
    """
    The tetris-game itself. Handles user input to move, etc.
    """
    cleared = 0
    tetrimino = newtetrimino()
    bestscore = int(getmaxlines())

    # allows for [x][y] indexing, but is actually a list of columns. A
    # bit unintuitive.
    board = [['']*20 for n in range(10)]
    
    background = pygame.image.load("Grid.PNG")
    backgroundcolor = getrgb(gridline)
    timestep = time.time()
    
    bottom = pygame.font.Font('BebasNeue.ttf',20)
    white = getrgb("#FFFFFF")
    
    while True:
        level = cleared/10 + startinglevel
        # amount of time in-between automatic block movements down
        timeinterval = 0.75*(0.95**level)
        for event in pygame.event.get():
            # keystroke handling
            if event.type == pygame.QUIT: 
                exit(0)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    shapemove(tetrimino,board,0,1)
                elif event.key == pygame.K_LEFT:
                    shapemove(tetrimino,board,-1,0)
                elif event.key == pygame.K_RIGHT:
                    shapemove(tetrimino,board,1,0)
                elif event.key == pygame.K_UP:
                    shaperotate(tetrimino,board)
                elif event.key == pygame.K_ESCAPE:
                    exit(0)
                elif event.key == pygame.K_n:
                    return 1
                elif event.key == pygame.K_m:
                    return 9
                elif event.key == pygame.K_p:
                    pause(screen)
                elif event.key == pygame.K_SPACE:
                    drop(tetrimino,board)

        # check for full lines and clears them 
        x = 0
        x = check(board,screen)
        cleared += x
        newpiece = False
        # update the score
        if cleared > bestscore:
            writemaxlines(cleared)
            bestscore = cleared
        coords = tetrimino.getcoords()
        # check if a new piece should be spawned
        for c in coords:
            if c[1]==19:
                newpiece=True
                break
            try:
                if board[c[0]][c[1]+1]!='':
                    newpiece=True
                    break
            except:
                print "Unexpected Error"
        if newpiece:
            # if a new piece is spawned, then we write the current piece
            # to the board.
            for t in tetrimino.blocks():
                board[t.x][t.y] = t
            tetrimino = newtetrimino()
            coords = tetrimino.getcoords()
            # check if the new piece has space to be spawned. else: gameover
            for (x,y) in coords:
                if board[x][y]!='':
                    returnstatus = gameover(screen)
                    return returnstatus
        else:
            # check if the piece should be moved down
            newt = time.time()
            if timestep+timeinterval < newt:
                # move current block down
                shapemove(tetrimino,board,0,1)
                timestep = newt        

        # unsure if this use of .blit() is the most efficient I could do
        # on this scale, that probably does not matter

        screen.fill(backgroundcolor)
        screen.blit(background,(5,5))

        # update the information at the bottom of the screen

        leveltext = bottom.render("Level: " + str(level+1),1,white)
        clearedtext = bottom.render("Lines: " + str(cleared),1,white)
        besttext = bottom.render("Best: " + str(bestscore),1,white)
    
        screen.blit(leveltext,(10,675))
        screen.blit(clearedtext,((341-clearedtext.get_rect().width)/2,675))
        screen.blit(besttext,(331-(besttext.get_rect().width),675))

        # blit the known blocks
        blitboard(board,screen)
        
        # update screen
        for block in tetrimino.blocks():
            screen.blit(getimg(block), block.getposn())
        pygame.display.flip()