我正在用Pygame用Python编写一个tic-tac-toe游戏。我需要在我的循环中检查是否有任何赢家(连续3个或对角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, (255, 255, 255), (200, 25, 150, 150))
sq3 = pygame.draw.rect(screen, (255, 255, 255), (375, 25, 150, 150))
sq4 = pygame.draw.rect(screen, (255, 255, 255), (25, 200, 150, 150))
sq5 = pygame.draw.rect(screen, (255, 255, 255), (200, 200, 150, 150))
sq6 = pygame.draw.rect(screen, (255, 255, 255), (375, 200, 150, 150))
sq7 = pygame.draw.rect(screen, (255, 255, 255), (25, 375, 150, 150))
sq8 = pygame.draw.rect(screen, (255, 255, 255), (200, 375, 150, 150))
sq9 = pygame.draw.rect(screen, (255, 255, 255), (375, 375, 150, 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, (255, 0, 0), (square_x + 25, square_y + 25, 100, 100))
pTurn = False
elif not pTurn: # circle player turn
pygame.draw.circle(screen, (0, 255, 0), (square_x + 75, square_y + 75), 60)
pTurn = True
# update frame (DONE LAST!)
pygame.display.update()
如果要向类添加属性,请使用Inheritance。创建具有子类
pygame.Rect
的类MyRect
:但是,您也应该考虑创建一个用于聚集^ {< CD2>}:
的块的类。这将允许您使} 的子类:
MyTile
成为^{不是直接的,但是您可以创建一个包装类,a-la组合
或者看看@rabbi76关于继承的答案。剥猫皮的方法很多
相关问题 更多 >
编程相关推荐