1. 程式人生 > 實用技巧 >pgame實現小遊戲

pgame實現小遊戲

from enum import Enum, unique
from math import sqrt
from random import randint
import pygame

def main():
    # 定義用來裝所有球的容器
    balls = []
    # 初始化匯入的pygame中的模組
    pygame.init()
    # 初始化用於顯示的視窗並設定視窗尺寸
    screen = pygame.display.set_mode((800, 600))
    # 設定當前視窗的標題
    pygame.display.set_caption('大球吃小球
') running = True # 開啟一個事件迴圈處理髮生的事件 while running: # 從訊息佇列中獲取事件並對事件進行處理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 處理滑鼠事件的程式碼 if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# 獲得點選滑鼠的位置 x, y = event.pos radius = randint(10, 100) sx, sy = randint(-10, 10), randint(-10, 10) color = Color.random_color() # 在點選滑鼠的位置建立一個球(大小、速度和顏色隨機) ball = Ball(x, y, radius, sx, sy, color)
# 將球新增到列表容器中 balls.append(ball) screen.fill((255, 255, 255)) # 取出容器中的球 如果沒被吃掉就繪製 被吃掉了就移除 for ball in balls: if ball.alive: ball.draw(screen) else: balls.remove(ball) pygame.display.flip() # 每隔50毫秒就改變球的位置再重新整理視窗 pygame.time.delay(50) for ball in balls: ball.move(screen) # 檢查球有沒有吃到其他的球 for other in balls: ball.eat(other) @unique class Color(Enum): """顏色""" RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (242, 242, 242) @staticmethod def random_color(): """獲得隨機顏色""" r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) return (r, g, b) class Ball(object): """""" def __init__(self, x, y, radius, sx, sy, color=Color.RED): """初始化方法""" self.x = x self.y = y self.radius = radius self.sx = sx self.sy = sy self.color = color self.alive = True def move(self, screen): """移動""" self.x += self.sx self.y += self.sy if self.x - self.radius <= 0 or \ self.x + self.radius >= screen.get_width(): self.sx = -self.sx if self.y - self.radius <= 0 or \ self.y + self.radius >= screen.get_height(): self.sy = -self.sy def eat(self, other): """吃其他球""" if self.alive and other.alive and self != other: dx, dy = self.x - other.x, self.y - other.y distance = sqrt(dx ** 2 + dy ** 2) if distance < self.radius + other.radius \ and self.radius > other.radius: other.alive = False self.radius = self.radius + int(other.radius * 0.146) def draw(self, screen): """在視窗上繪製球""" pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius, 0) if __name__ == '__main__': main()

效果