【问题标题】:Pygame Text Rectangles OverlappingPygame 文本矩形重叠
【发布时间】:2016-01-20 22:43:14
【问题描述】:

这是我的代码:

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()

问题在于文本会覆盖自身。我已经阅读了无数关于如何重绘表面的内容,但我不完全确定它们是什么意思?我做了 window.fill(white) 但这似乎没有做到。

【问题讨论】:

  • time.sleepwhile in countDown 不是一个好主意。它停止mainloop,此时程序将不会响应按键。

标签: python pygame


【解决方案1】:

您在while 循环中绘制,并且在绘制新文本之前没有清除此位置。在绘制新文本之前,您必须使用背景颜色或背景图像填充此位置。或许您可以使用fill(white, TextRect) 仅填充(清除)屏幕的一部分。

您使用window.fill(white),但不在countDown 中的while 循环内,因此它会在您完成计数后清除文本(和所有屏幕)。

redraw 表示“清除屏幕并重新绘制所有内容”。要清除屏幕,请使用fill(white)


我不知道你想做什么 - 但 sleepwhile(在 countDown 中)可能不是个好主意。

【讨论】:

  • 我只是想在比赛开始前倒计时:1 2 3 4 5 Draw 比赛开始但是数字重叠
  • 在绘制新文本之前,您必须先绘制矩形以“删除”旧文本。新文本没有自己的背景。
猜你喜欢
  • 1970-01-01
  • 2021-09-19
  • 2018-11-02
  • 2021-09-22
  • 2023-04-01
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 2017-03-14
相关资源
最近更新 更多