Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I Have a program where it has a list of names. I want to be able to list each of these names onto a rectangle. I want each name to create its own rectangle. This example create a rectangle for each title in the list i put '' at the start of the list as I got an error saying I couldn't divide by zero in python by adding '' fixed that.

import pygame

width,height = 800,600

screen = pygame.display.set_mode((width,height))

mover = 0

games = ['','Space Invaders','Snake']

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            pygame.quit()

            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:

            if event.button == 4:

                if mover > 0:

                    mover -= 15

            if event.button == 5:

                if mover < (height-120)-60:

                    mover += 15

    screen.fill((47,79,79))

    for game in games:

        for num in range(len(games)):

            if num != 0:

                pygame.draw.rect(screen, (0,51,51), (100,((height-120)/num)-mover,width-200,20))

    pygame.draw.rect(screen, (0,51,51), (width-30,100,25,height-120)) #SCROLL BAR

    pygame.draw.rect(screen, (0,0,0), (width-29,mover+100,23,60)) #SCROLLING BAR

    pygame.draw.line(screen, (0,0,0), (0,100),(width,100), 4)

    pygame.display.flip()

I am not sure in how I can get the rectangles closer together so that there is only 5 to 10 pixels between each rectangle. I also feel like there is a better way in doing this.

1 Answer

0 votes
by (25.1k points)

You need to define the distance from the top of the screen and then define a distance between the lines. The height of a line is 20. If the gap between the lines should be 10, the the distance is 30. So the start of a line is 110 + num*30 - mover. you can use enumerate, to get tuples of list index and list element.

for num, game in enumerate(games):

    pygame.draw.rect(screen, (0,51,51), (100, 110 + num*30 + mover, width-200, 20))

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...