Python通过Pygame绘制移动的矩形实例代码

yipeiwu_com5年前Python基础

Pygame是一个多用于游戏开发的模块。

本文实例主要是在演示框里实现一个移动的矩形实例代码,完整代码如下:

#moving rectangle project

import pygame

from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((600,500))

pygame.display.set_caption("Drawing Rectangles")

pos_x = 300

pos_y = 250

vel_x = 2

vel_y = 1

while True:

  for event in pygame.event.get():

    if event.type in (QUIT,KEYDOWN):

      pygame.quit()

  screen.fill((0,0,200))



  # move the rectangle

  pos_x += vel_x

  pos_y += vel_y

  # keep rectangle on the screen

  if pos_x > 500 or pos_x < 0:

    vel_x = -vel_x

  if pos_y > 400 or pos_y < 0:

    vel_y = -vel_y

  # draw the rectangle

  color = 255,255,0

  width = 0 #solid fill

  pos = pos_x,pos_y,100,100

  pygame.draw.rect(screen,color,pos,width)

  pygame.display.update()   

演示如下:

总结

以上就是本文关于Python通过Pygame绘制移动的矩形实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

对python For 循环的三种遍历方式解析

实例如下所示: array = ["a","b","c"] for item in array: print(item) for index in range(len...

Django-Model数据库操作(增删改查、连表结构)详解

Django-Model数据库操作(增删改查、连表结构)详解

一、数据库操作 1、创建model表 基本结构 from django.db import models class userinfo(models.Model): #如果没...

flask中的wtforms使用方法

flask中的wtforms使用方法

一、简单介绍flask中的wtforms WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证。 安装: pip3 install wtforms...

Python随机生成彩票号码的方法

本文实例讲述了Python随机生成彩票号码的方法。分享给大家供大家参考。具体如下: 前些日子在淘宝上买了一阵子彩票,每次都是使用淘宝的机选,每次一注。后来觉得不如自己写一个机选的程序有意...

python树莓派红外反射传感器

python树莓派红外反射传感器

本文实例为大家分享了python树莓派红外反射传感器的程序,供大家参考,具体内容如下 1、工具 rpi3,微雪ARPI600,Infrared Reflective Sensor 2、基...