我正在制作一个需要在Python(3.2)中绘制矩形的游戏。
我查看了很多资料,但没有一个能够准确地展示如何完成此操作。
我正在制作一个需要在Python(3.2)中绘制矩形的游戏。
我查看了很多资料,但没有一个能够准确地展示如何完成此操作。
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
DISPLAY=pygame.display.set_mode((500,400),0,32)
WHITE=(255,255,255)
BLUE=(0,0,255)
DISPLAY.fill(WHITE)
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
main()
这将创建一个简单的窗口,大小为500像素乘以400像素,背景为白色。在窗口中将有一个蓝色矩形。您需要使用 pygame.draw.rect
进行操作,并添加 DISPLAY
常量将其添加到屏幕上,变量 blue 使其变成蓝色(blue 是一个元组,其中的值等于 RGB 值中的蓝色和它的坐标)。
查看 pygame.org 获取更多信息。
以下是方法:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
你尝试过这个吗:
来自该网站的内容:
pygame.draw.rect(screen, color, (x,y,width,height), thickness) 绘制一个矩形,(x,y,width,height) 是一个Python元组,x、y是左上角的坐标,width和height是矩形的宽度和高度,thickness是线条的粗细。如果为零,则矩形将被填充。
使用模块pygame.draw可以绘制矩形、圆形、多边形、直线、椭圆或者弧形等图形。以下是一些例子:
pygame.draw.rect
用于绘制填充的矩形或轮廓线条,参数包括目标Surface(即显示器),color颜色,rectangle矩形区域和可选的轮廓线宽度width。其中rectangle参数是由四个组件(x,y,width,height)组成的元组,其中(x,y)表示矩形左上角位置。另外,也可以使用pygame.Rect
对象作为参数。
pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)
pygame.draw.circle
函数可以用来绘制实心或轮廓圆。传入该函数的参数包括目标Surface(即显示屏)、color(颜色)、center(中心坐标)、radius(半径)和可选的轮廓线width(宽度)。其中center参数是一个有两个元素(x, y)的元组:
pygame.draw.circle(window, color, (x, y), radius)
pygame.draw.polygon
用于绘制填充多边形或轮廓。参数包括目标Surface(即显示器),颜色,points列表和可选的轮廓width。每个point是一个具有2个分量(x,y)的元组:
pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])
最简例子:
repl.it/@Rabbid76/PyGame-Shapes
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((255, 255, 255))
pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
pygame.draw.polygon(window, (255, 255, 0),
[(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])
pygame.display.flip()
pygame.quit()
exit()
最基本的工作包括:
# Importing the library
import pygame
# Initializing Pygame
pygame.init()
# Initializing surface
surface = pygame.display.set_mode((400,300))
# Initializing color
color = (255,0,0)
# Drawing Rectangle
pygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60))
pygame.display.flip()
使用pygame.draw.rect()
有一种更简单的方法:
pygame.draw.rect(surface/screen, color, [x,y,width,height])
然后记得更新显示。