期望: 1.球體接觸到框體後反彈 2.設置速度按鍵,按下後改變球體速度、顏色狀態 具體實現: ...
期望:
1.球體接觸到框體後反彈
2.設置速度按鍵,按下後改變球體速度、顏色狀態
具體實現:
1 import pygame 2 from pygame.locals import * 3 import sys, random 4 5 6 class Circle(object): 7 # 設置Circle類屬性 8 def __init__(self): 9 self.vel_x = 1 10 self.vel_y = 1 11 self.radius = 20 12 self.pos_x, self.pos_y = random.randint(0, 255), random.randint(0, 255) 13 self.width = 0 14 self.color = 0, 0, 0 15 16 # 球體顏色速度改變方法 17 def change_circle(self, number): 18 self.color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) 19 # 防止球體速度方向發生改變 20 if self.vel_x < 0: 21 self.vel_x = -number 22 else: 23 self.vel_x = number 24 if self.vel_y < 0: 25 self.vel_y = -number 26 else: 27 self.vel_y = number 28 # self.vel_x, self.vel_y = number, number 如果僅此句,速度方向會發生改變 29 30 def circle_run(self): 31 # 防止球體超出游戲界面框體 32 if self.pos_x > 580 or self.pos_x < 20: 33 self.vel_x = -self.vel_x 34 35 if self.pos_y > 480 or self.pos_y < 20: 36 self.vel_y = -self.vel_y 37 self.pos_x += self.vel_x 38 self.pos_y += self.vel_y 39 pos = self.pos_x, self.pos_y 40 pygame.draw.circle(screen, self.color, pos, self.radius, self.width) 41 42 pygame.init() 43 screen = pygame.display.set_mode((600, 500)) 44 # Circle實例 45 circle1 = Circle() 46 47 while True: 48 for event in pygame.event.get(): 49 if event.type == QUIT: 50 sys.exit() 51 elif event.type == KEYUP: 52 if event.key == pygame.K_1: 53 circle1.change_circle(1) 54 elif event.key == pygame.K_2: 55 circle1.change_circle(2) 56 elif event.key == pygame.K_3: 57 circle1.change_circle(3) 58 elif event.key == pygame.K_4: 59 circle1.change_circle(4) 60 61 screen.fill((0, 0, 100)) 62 63 circle1.circle_run() 64 65 pygame.display.update()