renju.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import pygame
  2. EMPTY = 0
  3. BLACK = 1
  4. WHITE = 2
  5. black_color = [0, 0, 0]
  6. white_color = [255, 255, 255]
  7. class RenjuBoard(object):
  8. def __init__(self):
  9. self._board = [[]] * 15
  10. self.reset()
  11. def reset(self):
  12. for row in range(len(self._board)):
  13. self._board[row] = [EMPTY] * 15
  14. def move(self, row, col, is_black):
  15. if self._board[row][col] == EMPTY:
  16. self._board[row][col] = BLACK if is_black else WHITE
  17. return True
  18. return False
  19. def draw(self, screen):
  20. for index in range(1, 16):
  21. pygame.draw.line(screen, black_color,
  22. [40, 40 * index], [600, 40 * index], 1)
  23. pygame.draw.line(screen, black_color,
  24. [40 * index, 40], [40 * index, 600], 1)
  25. pygame.draw.rect(screen, black_color, [36, 36, 568, 568], 4)
  26. pygame.draw.circle(screen, black_color, [320, 320], 5, 0)
  27. pygame.draw.circle(screen, black_color, [160, 160], 5, 0)
  28. pygame.draw.circle(screen, black_color, [480, 480], 5, 0)
  29. pygame.draw.circle(screen, black_color, [480, 160], 5, 0)
  30. pygame.draw.circle(screen, black_color, [160, 480], 5, 0)
  31. for row in range(len(self._board)):
  32. for col in range(len(self._board[row])):
  33. if self._board[row][col] != EMPTY:
  34. ccolor = black_color \
  35. if self._board[row][col] == BLACK else white_color
  36. pos = [40 * (col + 1), 40 * (row + 1)]
  37. pygame.draw.circle(screen, ccolor, pos, 20, 0)
  38. def main():
  39. board = RenjuBoard()
  40. is_black = True
  41. pygame.init()
  42. pygame.display.set_caption('五子棋')
  43. screen = pygame.display.set_mode([640, 640])
  44. screen.fill([255, 255, 0])
  45. board.draw(screen)
  46. pygame.display.flip()
  47. running = True
  48. while running:
  49. for event in pygame.event.get():
  50. if event.type == pygame.QUIT:
  51. running = False
  52. elif event.type == pygame.KEYUP:
  53. pass
  54. elif event.type == pygame.MOUSEBUTTONDOWN\
  55. and event.button == 1:
  56. x, y = event.pos
  57. row = round((y - 40) / 40)
  58. col = round((x - 40) / 40)
  59. if board.move(row, col, is_black):
  60. is_black = not is_black
  61. screen.fill([255, 255, 0])
  62. board.draw(screen)
  63. pygame.display.flip()
  64. pygame.quit()
  65. if __name__ == '__main__':
  66. main()