当前位置:   article > 正文

python中pygame画图_Python--写游戏pygame入门二(屏幕上画圆,矩形,椭圆)

pygame.draw.ellipse

1、建立一个窗口

import pygame

#模块初始化

pygame.init()

#创建一个窗口,窗口大小为640*480

screen=pygame.display.set_mode([640,480])

#定义窗口的标题为'Draw'

pygame.display.set_caption('Draw')

#用白色填充窗口

screen.fill((255,255,255))

2、退出窗口

while True:

for event in pygame.event.get():

if event.type==pygame.QUIT:

sys.exit()

event.get()函数获取事件队列,即把捕获到的事件放入一个队列,然后一一执行。

3、画圆,矩形,椭圆

说明文档链接如下:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

4、当按下键盘上的按键,在频幕上随机画出圆,矩形或者椭圆,按【退出键】退出程序

#!usr/bin/env python

#coding=utf-8

import pygame

import sys

import random

screen_size = (640, 480)

backgroundcolor = (255, 127, 255)

#pygame初始化

pygame.init()

#创建一个窗口

screen = pygame.display.set_mode(screen_size, 0, 32)

pygame.display.set_caption('Draw rect and circle')

#背景填充

screen.fill(backgroundcolor)

while True:

for event in pygame.event.get():

#按下关闭按钮,退出程序

if event.type==pygame.QUIT:

sys.exit()

#按下键盘上的任意键,在屏幕上画图

elif event.type == pygame.KEYDOWN:

i = random.randint(0, 2)

drawcolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255))

top = random.randint(0,400)

left = random.randint(0,500)

width = random.randint(0,5)

#画圆

if i == 0:

radiu = random.randint(width,100)

pygame.draw.circle(screen, drawcolor, [top, left], radiu, width)

#画矩形

elif i == 1:

rectwidth = random.randint(0,255)

rectheight = random.randint(0,100)

pygame.draw.rect(screen, drawcolor,[left, top, rectwidth, rectheight], width)

#画椭圆

else:

try:

rectwidth = random.randint(0,255)

rectheight = random.randint(0,100)

pygame.draw.ellipse(screen, drawcolor, [left, top, rectwidth, rectheight], width)

except ValueError:

print 'ellipse'

pass

#重画屏幕

pygame.display.flip()

5、效果图

0818b9ca8b590ca3270a3433284dd417.png

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/154457
推荐阅读
相关标签
  

闽ICP备14008679号