我在屏幕上绘制一个简单的矩形时遇到问题。我不知道为什么它无法绘制,我已经尝试了几件事:在背景表面上绘制它,改变函数调用的顺序等但它似乎并没有绘制任何东西。正如你所看到的,enemy()方法应该绘制一个红色矩形,而不是什么都不绘制。否则游戏运行正常。我确信它很简单,我忽略了......令人沮丧!
import pygame
from pygame.locals import *
from pygame.time import *
from pygame.font import *
from pygame.draw import *
import sys
pygame.font.init()
pygame.init()
screen = pygame.display.set_mode((700,300))
pygame.display.set_caption('something')
#--------------------------------------------------------------------
velX = 0
velY = 0
playerx = 20
player_filename = 'player.png'
player = pygame.image.load(player_filename)
playery = 150
clock = pygame.time.Clock()
#--------------------------------------------------------------------
def draw():
global velX
global velY
global playerx
global playery
red = pygame.Color(255,0,0)
black = pygame.Color(0,0,0)
level = "1"
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))
screen.blit(background, (0,0))
playerx = playerx + velX
playery = playery + velY
screen.blit(player, (playerx,playery))
font = pygame.font.Font(None, 36)
text = font.render(level, 1, black)
screen.blit(text, (670,10))
pygame.display.flip()
#--------------------------------------------------------------------
def enemySquares():
enemySurf = pygame.Surface(screen.get_size())
red = pygame.Color(255,0,0)
enemy = pygame.Rect(200,50,20,20)
pygame.draw.rect(enemySurf, red, enemy, 0)
#--------------------------------------------------------------------
def collisionWithBorder():
if playerx > 680 or playerx < 0:
pygame.quit()
sys.exit()
if playery > 280 or playery < 0:
pygame.quit()
sys.exit()
#--------------------------------------------------------------------
def playerFunc():
keys_down = pygame.key.get_pressed()
pygame.key.set_repeat(1,50)
time = 50/1000
global velX
global velY
direction = -1
if keys_down[K_d]:
direction = 0
if keys_down[K_a]:
direction = 3
if keys_down[K_w]:
direction = 1
if keys_down[K_s]:
direction = 2
if direction == 0:
velX = 50*time
velY = 0
if direction == 1:
velY = -50*time
velX = 0
if direction == 2:
velY = 50*time
velX = 0
if direction == 3:
velX = -50*time
velY = 0
#--------------------------------------------------------------------
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
clock.tick(50)
collisionWithBorder()
draw()
playerFunc()
enemySquares()
#--------------------------------------------------------------------
if __name__ == '__main__':
main()
答案 0 :(得分:2)
def enemySquares():
enemySurf = pygame.Surface(screen.get_size())
red = pygame.Color(255,0,0)
enemy = pygame.Rect(200,50,20,20)
pygame.draw.rect(enemySurf, red, enemy, 0)
上面的函数确实绘制了一个红色矩形 - 在它创建的新surace上,而不是 “屏幕”表面。
将enemySurf = ...
行放在那里并更改pygame.draw.rect(enemySurf, red, enemy, 0)
至
pygame.draw.rect(screen, red, enemy, 0)
要在下次调用pygame.display.flip()