1. 程式人生 > >pygame 繪製移動矩形,並碰到邊界時改變顏色

pygame 繪製移動矩形,並碰到邊界時改變顏色

import pygame,sys;
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((700,600))
pygame.display.set_caption("Drawing Rectangles")
pos_x = 300
pos_y = 250
vel_x = 6
vel_y = 3
a = int(10)
b = int(20)
c = int(10)
while True:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN):
            sys.exit()
    screen.fill((0,0,200))
    pos_x+=vel_x
    pos_y+=vel_y
    if pos_x > 600 or pos_x < 0:
        vel_x = -vel_x
        if a <= 205 and a >= 50:
            a = a + 50
        elif a > 205:
            a = a - 5
        elif a < 5:
            a = a + 50
        if b <= 205 and b >= 50:
            b = b + 50
        elif b > 205:
            b = b - 50
        elif b < 50:
            b = b + 50
        if c <= 205 and c >= 50:
            c = c + 5
        elif c > 205:
            c = c - 50
        elif c < 50:
            c = c + 20
        print(a)
        print(b)
        print(c)
    if pos_y > 500 or pos_y < 0:
        vel_y = -vel_y
        if a <= 205 and a >= 50:
            a = a + 22
        elif a > 205:
            a = a - 32
        elif a < 50:
            a = a + 21
        if b <= 205 and b >= 50:
            b = b + 23
        elif b > 205:
            b = b - 21
        elif b < 50:
            b = b + 21
        if c <= 205 and c >= 50:
            c = c + 23
        elif c > 205:
            c = c - 32
        elif c < 50:
            c = c + 43
        print(a)
        print(b)
        print(c)
    color = a,b,c
    width = 0
    pos = pos_x,pos_y,100,100
    pygame.draw.rect(screen,color,pos,width)
    pygame.display.update()