pygame绘制一个随机背景

Posted xiyu714

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pygame绘制一个随机背景相关的知识,希望对你有一定的参考价值。

import random
import pygame

# ----- 初始化 -----
pygame.init()
screen = pygame.display.set_mode((640, 480))
screenrect = screen.get_rect()  # 创建一个矩形
background = pygame.Surface(screen.get_size())
mainloop = True
dcirc = True
nocleanup = True
clock = pygame.time.Clock()
FPS = 60

# ------ 随机绘制圆 -----
def draw_random_circle(back):
    bally = random.randint(0, screenrect.height)
    ballx = random.randint(0, screenrect.width)
    color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
    radius = random.randint(0, (screenrect.height+screenrect.width)//4)
    pygame.draw.circle(back, color, (ballx, bally), radius)
# ---- mainloop ----
while mainloop:
    clock.tick(FPS)
    pygame.display.set_caption("FPS: %d" % clock.get_fps())     # 显示FPS
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mainloop = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                dcirc = not dcirc
                nocleanup = True
            elif event.key == pygame.K_ESCAPE:
                mainloop = False
            elif event.key == pygame.K_c:
                nocleanup = not nocleanup
                if nocleanup:
                    dcirc = True
                else:
                    dcirc = False

    # ----- 控制绘制背景和 清空背景
    if not nocleanup:
        background.fill((255, 255, 255))
    if dcirc:
        draw_random_circle(background)
    screen.blit(background, (0, 0))
    # ----- 刷新 ------
    pygame.display.flip()

 

以上是关于pygame绘制一个随机背景的主要内容,如果未能解决你的问题,请参考以下文章

pygame绘制背景

在Pygame中绘制一个又一个的图像

为啥我的python用pygame做图片移动会留下轨迹?

如何在pygame中只对背景进行一次blit?

基础DAY14-飞机大战-绘制图像

在mac下初次使用pygame踩坑纪实(卡死)