绘制一个可以移动的矩形,当矩形碰到屏幕边界时,矩形都将会改变颜色

import pygame #导包
from pygame.locals import*
import sys

pygame.init() #初始化

screen_width=600
screen_height=600
screen = pygame.display.set_mode(size=(screen_width,screen_height))
pygame.display.set_caption("这是标题")

pos_x = 300
pos_y =300#矩形左上角位置

vel_x = 0.16
vel_y = 0.1#粗略滴可以看作矩形的移动速度

colors = [0,250,154], [0, 255, 0], [0,255,255], [148,0,211],[220,20,60], [255,0,255]
color_index = 0

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

    screen.fill((0,0,0))#每次循环都要将背景置为黑色
    pos_x += vel_x
    pos_y += vel_y

    #当矩形超过屏幕范围后返回
    if pos_x > 500 or pos_x < 0:
        vel_x = -vel_x
        color_index = (color_index + 1) % len(colors)  # 更新颜色索引
    if pos_y > 500 or pos_y < 0:
        vel_y = -vel_y
        color_index = (color_index + 1) % len(colors)

#绘制矩形
    color = colors[color_index]
    width = 0
    pos = pos_x,pos_y, 100,100
    pygame.draw.rect(screen,color,pos,width)
    pygame.display.update()

参考资料:pygame学习(二)——绘制线条、圆、矩形等图案-CSDN博客

  • 16
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执沐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值