问题描述
我正在使用 Pygame 用 Python 编写井字游戏。如果有任何获胜者(连续 3 个或对角线),我需要检查我的循环。我使用 for 循环和矩形的位置(Pygame 中的内置类)绘制零和十字。
是否可以将我自己的属性设置为内置类(pygame.rect),例如...
sq1.isFull = True
...即使这不是 rect 的内置方法?
如果不是,如果我的所有正方形和圆形都是在 for 循环中制作的,我将如何检查胜利?
代码如下:
import pygame
# initialize pygame
pygame.init()
# window setup
screen = pygame.display.set_mode((550,550))
pygame.display.set_caption('Tic Tac Toe by Donnaven')
# squares
sq1 = pygame.draw.rect(screen,(255,255,255),(25,25,150,150))
sq2 = pygame.draw.rect(screen,(200,150))
sq3 = pygame.draw.rect(screen,(375,150))
sq4 = pygame.draw.rect(screen,200,150))
sq5 = pygame.draw.rect(screen,150))
sq6 = pygame.draw.rect(screen,150))
sq7 = pygame.draw.rect(screen,375,150))
sq8 = pygame.draw.rect(screen,150))
sq9 = pygame.draw.rect(screen,150))
square_list = [sq1,sq2,sq3,sq4,sq5,sq6,sq7,sq8,sq9]
# game loop
pTurn = True # Whose turn it is.
# True = Rectangle,False = Circle
running = True
while running:
pygame.time.delay(100)
# checking for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
mouse_pos = pygame.mouse.get_pos()
for square in square_list:
if square.collidepoint(mouse_pos):
square_x = square.x
square_y = square.y
# draw shape inside of square
if pTurn: # rectangle player turn
pygame.draw.rect(screen,0),(square_x + 25,square_y + 25,100,100))
pTurn = False
elif not pTurn: # circle player turn
pygame.draw.circle(screen,(0,(square_x + 75,square_y + 75),60)
pTurn = True
# update frame (DONE LAST!)
pygame.display.update()
解决方法
不是直接的,但是你可以创建一个包装类,a-la 组合。
class Tile:
def __init__(self,square):
self.square = square
self.is_full = False
square_list = [Tile(sq1),... Tile(sqn)]
for tile in square_list:
square = tile.square
if square.collidepoint(mouse_pos) and not tile.is_full:
...
tile.is_full = True
或者看看@Rabbid76 的继承答案。给猫剥皮的方法很多。
,如果要向类添加属性,请使用 Inheritance。使用子类 MyRect
创建一个类 pygame.Rect
:
class MyRect(pygame.Rect):
def __init__(self,x,y,w,h,isFull = True):
super().__init__(x,h)
self.isFull = isFull
但是,您还应该考虑为聚合 pygame.Rect
的图块创建一个类:
class MyTile:
def __init__(self,isFull = True):
self.rect = pygame.Rect(x,h)
self.isFull = isFull
这将允许您使 MyTile
成为 pygame.sprite.Sprite
的子类:
class MyTile(pygame.sprite.Sprite):
def __init__(self,isFull = True):
super().__init__()
self.rect = pygame.Rect(x,h)
self.isFull = isFull
self.image = pygame.Surface(self.rect.size)
self.image.fill((255,0)) # just for example