简体   繁体   中英

Pygame Text Rectangles Overlapping

this is my code:

import pygame
import time
pygame.init()

display_width = 800
display_height = 600
window = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Draw')
clock = pygame.time.Clock()
p1Img = pygame.image.load('player.png')
p2Img = pygame.image.load('player2.png')
bullet = pygame.image.load('bullet.png')
id = 1

white = (255,255,255)
black = (0,0,0)






def player(x,y):
    window.blit(p1Img,(p1x,p1y))

def player2(x,y):
    window.blit(p2Img,(p2x,p2y))

def text_objects(text,font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()



def messageDisplay(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text,largeText)
    TextRect.center = (display_width/2, display_height/2)
    window.blit(TextSurf,TextRect)

    pygame.display.update()

def countDown(drawTime):
    while drawTime <= 5:
        time.sleep(1)
        pygame.display.update()
        messageDisplay(str(drawTime))
        drawTime += 1
    else:
        pygame.display.update()
        messageDisplay('Draw')



p1x = -5
p1y = 500
b1x = 56
b1y = 510

p2x = 740
p2y = 500
b2x = 740
b2y = 500

while(id != 0):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            id = 0
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                window.blit(bullet,(b1x, b1y))
                pygame.display.update()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_q:
                window.blit(bullet,(b1x, b1y))


    window.fill(white)
    player(p1x,p1y)
    player2(p2x,p2y)
    pygame.display.update()
    countDown(1)
    clock.tick(120)

pygame.quit()

The problem is that the text draws over itself. I've read countless things about how I need to redraw the surface but I'm not entirely sure what they mean? I did window.fill(white) but that doesn't seem to do it.

You draw in while loop and you don't clear this place before you draw new text. You have to fill this place with background color or background image before you draw new text. Probably you could use fill(white, TextRect) to fill (clear) only part of screen.

You use window.fill(white) but not inside of while loop in countDown so it clears text (and all screen) after you finish counting.

redraw means "clear screen and draw everything again". To clear screen you use fill(white)


I don't know what you are trying to do - but sleep and while (in countDown ) probably is not good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM