基于Python Pygame实现的画饼图游戏
时间:2023-03-06 10:56:32|栏目:Python代码|点击: 次
这个游戏就是实现键盘上输入不同的数字,将圆分割成不同的几个部分,每部分用不同的颜色来实现。
导入包
导入随机包,pygame,系统包,time时间包用于时间暂停。math是用来确认弧度的。
import random import pygame, sys, time import math from pygame.locals import *
配置基本参数
初始化pygame,设置窗口大小标题,设置圆心的x和y轴,圆的半径,线条的宽度,这里设置的足够大,就会填充整个扇形。设置圆形的属性,初始的扇形的个数设置为2
pygame.init() screen = pygame.display.set_mode((400, 400)) pygame.display.set_caption("分饼干") # 饼图设置 x = 200 y = 200 radius = 100 # 颜色 WHITE = (255, 255, 255) # 线条宽度 WIDTH = 100 # 设置椭圆的属性 ellipse = (x - radius, y - radius, radius * 2, radius * 2) # 扇形大小 sectorNum = 2
根据输入的数字改变扇形的个数
根据按下数字的键,改变扇形的个数
def get_sector_num(key): """根据用户输入的数字决定扇形的大小""" if key == pygame.K_2: return 2 elif key == pygame.K_3: return 3 elif key == pygame.K_4: return 4 elif key == pygame.K_5: return 5 elif key == pygame.K_6: return 6 elif key == pygame.K_7: return 7 elif key == pygame.K_8: return 8 elif key == pygame.K_9: return 9 return 1
监听事件
循环扇形的个数,计算开始结束的弧形,并设置随机的颜色。
while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() else: sectorNum = get_sector_num(event.key) screen.fill(WHITE) for i in range(sectorNum): start_angle = 0 + (360 / sectorNum) * i end_angle = (360 / sectorNum) * (i + 1) pygame.draw.arc(screen, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), ellipse, math.radians(start_angle), math.radians(end_angle), 100) pygame.display.update() time.sleep(1)
import random
import pygame, sys, time
import math
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("分饼干")
# 饼图设置
x = 200
y = 200
radius = 100
# 颜色
WHITE = (255, 255, 255)
# 线条宽度
WIDTH = 4
# 设置椭圆的属性
ellipse = (x - radius, y - radius, radius * 2, radius * 2)
# 扇形大小
sectorNum = 2
def get_sector_num(key):
"""根据用户输入的数字决定扇形的大小"""
if key == pygame.K_2:
return 2
elif key == pygame.K_3:
return 3
elif key == pygame.K_4:
return 4
elif key == pygame.K_5:
return 5
elif key == pygame.K_6:
return 6
elif key == pygame.K_7:
return 7
elif key == pygame.K_8:
return 8
elif key == pygame.K_9:
return 9
return 1
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
else:
sectorNum = get_sector_num(event.key)
screen.fill(WHITE)
for i in range(sectorNum):
start_angle = 0 + (360 / sectorNum) * i
end_angle = (360 / sectorNum) * (i + 1)
pygame.draw.arc(screen, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), ellipse,
math.radians(start_angle), math.radians(end_angle), 100)
pygame.display.update()
time.sleep(1)