[英]Pygame Drawing a Rectangle
我正在制作一個需要知道如何在 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 像素 x 400 像素的白色窗口。 窗口內將出現一個藍色矩形。 您需要使用pygame.draw.rect
來解決這個問題,並添加DISPLAY
常量以將其添加到屏幕,變量 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 是矩形的寬度,height 是線的粗細。 如果為零,則填充矩形
使用pygame.draw模塊可以繪制矩形、圓形、多邊形、連線、橢圓或圓弧等形狀。 一些例子:
pygame.draw.rect
繪制填充的矩形形狀或輪廓。 參數是目標Surface (是顯示器)、顏色、矩形和可選的輪廓寬度。 矩形參數是一個包含 4 個分量 ( 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
繪制實心圓或輪廓。 參數是目標表面(是顯示)、顏色、中心、半徑和可選的輪廓寬度。 center參數是一個包含 2 個分量 ( x , y ) 的元組:
pygame.draw.circle(window, color, (x, y), radius)
pygame.draw.polygon
繪制填充的多邊形或輪廓。 參數是目標表面(是顯示)、顏色、點列表和可選的輪廓寬度。 每個點都是一個包含 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))
# Initialing 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])
然后記得更新顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.