首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在pygame中将矩形保留在屏幕中

,可以通过以下步骤实现:

  1. 导入pygame库和sys模块:
代码语言:txt
复制
import pygame
import sys
  1. 初始化pygame:
代码语言:txt
复制
pygame.init()
  1. 设置屏幕尺寸和背景颜色:
代码语言:txt
复制
screen_width = 800
screen_height = 600
bg_color = (255, 255, 255)  # 白色背景
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill(bg_color)
  1. 创建矩形对象:
代码语言:txt
复制
rect_width = 100
rect_height = 50
rect_color = (255, 0, 0)  # 红色矩形
rect = pygame.Rect((screen_width - rect_width) // 2, (screen_height - rect_height) // 2, rect_width, rect_height)
  1. 在屏幕上绘制矩形:
代码语言:txt
复制
pygame.draw.rect(screen, rect_color, rect)
  1. 刷新屏幕显示:
代码语言:txt
复制
pygame.display.flip()
  1. 设置游戏主循环:
代码语言:txt
复制
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

完整代码示例:

代码语言:txt
复制
import pygame
import sys

pygame.init()

screen_width = 800
screen_height = 600
bg_color = (255, 255, 255)  # 白色背景
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill(bg_color)

rect_width = 100
rect_height = 50
rect_color = (255, 0, 0)  # 红色矩形
rect = pygame.Rect((screen_width - rect_width) // 2, (screen_height - rect_height) // 2, rect_width, rect_height)

pygame.draw.rect(screen, rect_color, rect)
pygame.display.flip()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

这段代码使用pygame库创建了一个窗口,并在窗口中绘制了一个红色矩形。通过设置游戏主循环,保证窗口一直显示,直到用户关闭窗口。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券