Python 在不减慢整个游戏的情况下减慢pygame函数
我正试图在pygame中完成我的第一个游戏 我希望游戏有这个动画的背景 我正在使用python 3.9.2Python 在不减慢整个游戏的情况下减慢pygame函数,python,python-3.x,pygame,Python,Python 3.x,Pygame,我正试图在pygame中完成我的第一个游戏 我希望游戏有这个动画的背景 我正在使用python 3.9.2 import pygame, math, random, sys from pygame.locals import * screen = pygame.display.set_mode((400, 400)) fps = 60 pygame.init() mainClock = pygame.time.Clock() # Colors black = (0, 0, 0) whit
import pygame, math, random, sys
from pygame.locals import *
screen = pygame.display.set_mode((400, 400))
fps = 60
pygame.init()
mainClock = pygame.time.Clock()
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
# Function for close the game ------------------------------------------------------------------------------------------------------------
def close_game():
pygame.quit()
sys.exit()
# Functions for drawing ------------------------------------------------------------------------------------------------------------------
def background():
screen.fill(black)
def canvas():
margin = pygame.draw.rect(screen, white, (50, 50, 300, 300), 1)
def bar_animation():
bar_width = 15
for b in range(0, 20):
bar_b_height = random.randint(10, 100)
bar_b = pygame.draw.rect(screen, white, (50 + (bar_width * b), 350 - bar_b_height, bar_width, bar_b_height), 0)
# Main game loop --------------------------------------------------------------------------------------------------------------------------
def main_loop():
running = True
while running:
background()
bar_animation()
canvas()
for event in pygame.event.get():
if event.type == QUIT:
close_game()
pass
pygame.display.update()
mainClock.tick(fps)
# Run game --
main_loop()
在这段代码中,我重新创建了我想要的游戏背景。
我想让bar_animation()函数运行得更慢,而不会使整个游戏或其他函数运行得更慢
该代码生成如下内容:
我建议您执行代码以了解我在做什么您可以通过每隔几次更新一次来降低功能的速度:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((400, 400))
mainClock = pygame.time.Clock()
running = True
bar_b_heights = []
while running:
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 255, 255), (50, 50, 300, 300), 1)
if pygame.time.get_ticks() % 10 == 0 or not bar_b_heights:
bar_b_heights = [random.randint(10, 100) for b in range(0, 20)]
for i, bar_b_height in enumerate(bar_b_heights):
pygame.draw.rect(screen, (255, 255, 255), (50 + (15 * i), 350 - bar_b_height, 15, bar_b_height), 0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
mainClock.tick(60)
pygame.display.quit()
pygame.quit()
输出: