Pygame:画一个方格板,在盒子的末尾继续画

2024-10-02 06:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在屏幕中间画了一块8x8方格板,板周围应该有空白,但在每一行和每列的末尾,它看起来像是在继续画到屏幕的边缘。有什么办法解决这个问题吗?或者我必须在电路板周围创建另一个曲面?在

注意:我认为问题出在drawMainBoard函数的某个地方。我试着创建一条线,每个框开始和结束,线停止在它应该的地方,但董事会继续画到屏幕的边缘。在

import pygame._view
import pygame
import sys
from pygame.locals import*
import time
import random

FPS=30
fpsClock=pygame.time.Clock()

displayWidth=600
displayHeight=600

Xmargin=(displayWidth/12)*2
Ymargin=(displayHeight/12)*2

boardRows=8
boardColumns=8

boxx=(displayWidth-(Xmargin*2))/8
boxy=(displayHeight-(Ymargin*2))/8



DISPLAYSURF=pygame.display.set_mode((displayWidth,displayHeight),0,32)

colorRed=   (255,0,0)
colorBlack= (0,0,0)
colorWhite= (255,255,255)
colorRed2=  (150,0,0)
colorBlack2=(10,10,10)

pygame.init()

myFont=pygame.font.SysFont("ariel",15)

def mainscreen():
    DISPLAYSURF.fill((255,255,255))

    drawMainboard()

    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

    fpsClock.tick(FPS)

def drawBox(boxstart,boxend,boxcolor):
    pygame.draw.rect(DISPLAYSURF,boxcolor,(boxstart,boxend),0)






def drawMainboard():
    firstColor=colorBlack
    boxxstart=Xmargin
    boxystart=Ymargin
    boxxend=Xmargin+boxx
    boxyend=Ymargin+boxy
    lettercount=0

    boxstart=(boxxstart,boxystart)
    boxend=(boxxend,boxyend)
    for columns in range(0,boardColumns):
        if firstColor==colorRed:
            firstColor=colorBlack
        else:
            firstColor=colorRed
        for rows in range(0,boardRows):
            drawBox(boxstart,boxend,firstColor)
            label=myFont.render(str(lettercount),20,(0,0,255))
            DISPLAYSURF.blit(label,(boxxstart,boxystart))
            pygame.draw.line(DISPLAYSURF,colorWhite,(boxxend,boxyend),(boxxstart,boxystart),1)
            lettercount+=1
            if firstColor==colorRed:
                firstColor=colorBlack
            else:
                firstColor=colorRed

            boxxstart+=boxx
            boxxend+=boxx
            boxstart=(boxxstart,boxystart)
            boxend=((boxxend),(boxyend))
        boxxstart=Xmargin
        boxxend=Xmargin+boxx
        boxystart+=boxy
        boxyend+=boxy
        boxstart=(boxxstart,boxystart)
        boxend=(boxxend,boxyend)


while True:
    mainscreen()

Tags: importpygamedisplaysurfdisplaywidthdisplayheightxmarginboxxcolorred
1条回答
网友
1楼 · 发布于 2024-10-02 06:31:26

{cd1>是函数中的问题。传入参数boxstartboxend,它们表示要绘制的矩形的左上角和右下角点。在

但是pygame.draw.rect函数需要一个类似Rect的对象或元组,表示矩形左上点的x和y坐标,它的大小是大小。因此,当传入值(450, 100), (500, 150)时,不会从(450, 100)到{}绘制Rect,而是从(450, 100)开始的矩形,长度为500,高度为150。在

一个简单的解决方法是计算函数中的正确大小:

def drawBox(boxstart,boxend,boxcolor):
    sx, sy = boxstart
    ex, ey = boxend
    r = Rect(sx, sy, ex-sx, ey-sy)
    pygame.draw.rect(DISPLAYSURF,boxcolor,r,0)

或者直接使用Rect类:

^{pr2}$

相关问题 更多 >

    热门问题