# Pygame之五子棋和贪吃蛇游戏设计

## 面向对象编程之五子棋

import pygame
EMPTY = 100
BLACK = 1
WHITE = 10
black_color = [0, 0, 0]
white_color = [255, 255, 255]

class RenjuBoard(object):

def __init__(self):
self._board = [[]] * 15
self.reset()

def reset(self):
for row in range(len(self._board)):
self._board[row] = [EMPTY] * 15

def draw(self, screen):
for index in range(1, 16):
pygame.draw.line(screen, black_color, [40, 40 * index], [600, 40 * index], 1)
pygame.draw.line(screen, black_color, [40 * index, 40], [40 * index, 600], 1)
pygame.draw.rect(screen, black_color, [36, 36, 568, 568], 4)  # 36,36表示起点的横纵坐标，568，568表示矩形的长宽
pygame.draw.circle(screen, black_color, [320, 320], 5, 0)  # 5表示半径，0表示线条是实心
pygame.draw.circle(screen, black_color, [160, 160], 5, 0)
pygame.draw.circle(screen, black_color, [480, 480], 5, 0)
pygame.draw.circle(screen, black_color, [480, 160], 5, 0)
pygame.draw.circle(screen, black_color, [160, 480], 5, 0)
for row in range(len(self._board)):
for col in range(len(self._board[row])):
if self._board[row][col] != EMPTY:
ccolor = black_color \
if self._board[row][col] == BLACK else white_color
pos = [40 * (col + 1), 40 * (row + 1)]
pygame.draw.circle(screen, ccolor, pos, 20, 0)

def move(self,row,col,is_black):
if self._board[row][col] == EMPTY:
self._board[row][col] = BLACK if is_black else WHITE
return True
return False

def judge(self):
my_sum = 0
for row in range(len(self._board)):
for col in range(len(self._board[row])):
if row + 4 <= 14:
my_sum = 0
for x in range(5):
my_sum += self._board[row + x][col]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if row - 4 >= 0:
my_sum = 0
for x in range(5):
my_sum += self._board[row - x][col]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if col + 4 <= 14:
my_sum = 0
for x in range(5):
my_sum += self._board[row ][col + x]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if col - 4 >= 0:
my_sum = 0
for x in range(5):
my_sum += self._board[row ][col - x]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if row + 4 <= 14 and col + 4 <= 14:
my_sum = 0
for x in range(5):
my_sum += self._board[row + x][col + x]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if row - 4 >= 0 and col + 4 <= 14:
my_sum = 0
for x in range(5):
my_sum += self._board[row - x][col + x]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if row + 4 <= 14 and col - 4 >= 0:
my_sum = 0
for x in range(5):
my_sum += self._board[row + x][col - x]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
if row - 4 >= 0 and col - 4 >= 0:
my_sum = 0
for x in range(5):
my_sum += self._board[row - x][col - x]
if my_sum == 5:
return 1
elif my_sum == 50:
return 2
return 0

def main():

def show_font(font, winer, screen):
over_text = font.render('游戏结束，%s方胜，请选择重新游戏R或退出游戏Q' % winer,
True, [0, 0, 0], [242, 242, 242])
over_board = over_text.get_rect()
over_board.center = (320, 320)
screen.blit(over_text, over_board)
pygame.display.update()

pygame.init()
over_font = pygame.font.SysFont('SimHei', 24)
is_black = True
pygame.display.set_caption('五子棋')  # 创建标题
screen = pygame.display.set_mode([640, 640]) #创建窗口
screen.fill([255, 255, 0]) #添加背景颜色
r1 = RenjuBoard()
r1.draw(screen)
pygame.display.flip()  # 刷新窗口
running = True
play = True
while running:
for event in pygame.event.get(): #接受事件
if event.type == pygame.QUIT: #事件类型是关闭事件
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
running = False
elif event.key == pygame.K_r:
r1.reset()
screen.fill([255, 255, 0])
r1.draw(screen)
pygame.display.flip()
play = True

elif event.type == pygame.MOUSEBUTTONDOWN \
and event.button == 1 and play:
x, y = event.pos
row = round(abs(y - 40) / 40)
col = round(abs(x - 40) / 40)
if r1.move(row, col, is_black):
is_black = not is_black
screen.fill([255, 255, 0])
r1.draw(screen)
if r1.judge() == 1 :
play = False
show_font(over_font, '黑', screen)

elif r1.judge() == 2:
play = False
show_font(over_font, '白', screen)

pygame.display.flip()

pygame.quit()

if __name__ == '__main__':
main()

## 面向对象编程之贪吃蛇

from random import randint
from abc import ABCMeta, abstractmethod
import pygame

BLACK_COLOR = (0, 0, 0)
FOOD_COLOR = (255, 100, 100)
GREEN_COLOR = (0, 255, 0)
UP = 0
RIGHT = 1
DOWM = 2
LEFT = 3

class GameObject(object, metaclass=ABCMeta):

def __init__(self, x, y, color):
self._x = x
self._y = y
self._color = color

@property
def x(self):
return self._x

@property
def y(self):
return self._y

@abstractmethod
def draw(self,screen):
pass

class Wall(GameObject):

def __init__(self, x, y, width, height, color=BLACK_COLOR):
super().__init__(x, y, color)
self._width = width
self._height = height

@property
def width(self):
return self._width

@property
def height(self):
return self._height

def draw(self,screen):
pygame.draw.rect(screen, self._color,
(self._x, self._y, self._width, self._height), 4)

class Food(GameObject):

def __init__(self, x, y, size, color=FOOD_COLOR):
super().__init__(x, y, color)
self._size = size
self._hidden = False

@property
def size(self):
return self._size

def draw(self, screen):
if not self._hidden:
pygame.draw.circle(screen, self._color,
(self._x + self._size // 2, self._y +
self._size // 2),  self._size // 2, 0)
self._hidden = not self._hidden

class SnakeNode(GameObject):

def __init__(self, x, y, size, color=GREEN_COLOR):
super().__init__(x, y, color)
self._size = size

@property
def size(self):
return self._size

def draw(self, screen):
pygame.draw.rect(screen, self._color,
(self._x, self._y, self._size, self._size), 0)
pygame.draw.rect(screen, BLACK_COLOR,
(self._x, self._y, self._size, self._size), 1)

class Snake(GameObject):

def __init__(self):
self._dir = LEFT
self._nodes = []
for index in range(5):
node = SnakeNode(290 + index * 20, 250, 20)
self._nodes.append(node)

@property
def dir(self):
return self._dir

def draw(self, screen):
for node in self._nodes:
node.draw(screen)

def collide(self, wall):

def eat_food(self, food):
self._nodes.append(self._nodes[-1])
return True

def eat_me(self):
for snake in self._nodes[4 :]:
return True

def move(self):
snake_dir = self._dir
if snake_dir == UP:
y -= size
if snake_dir == RIGHT:
x += size
if snake_dir == DOWM:
y += size
if snake_dir == LEFT:
x -= size
self._nodes.pop()

def change_dir(self, new_dir):
if new_dir != self._dir and (self._dir + new_dir) % 2 != 0:
self._dir = new_dir

def main():

def refresh():
"""刷新窗口"""
screen.fill((242, 242, 242))
snake.draw(screen)
wall.draw(screen)
food.draw(screen)
pygame.display.flip()

def handle_key_event(key_event):
key = key_event.key
if key == pygame.K_F2:
reset_game()
elif key in (pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d):
if not game_over:
if key == pygame.K_w:
new_dir = UP
elif key == pygame.K_d:
new_dir = RIGHT
elif key == pygame.K_s:
new_dir = DOWM
elif key == pygame.K_a:
new_dir = LEFT
snake.change_dir(new_dir)

def create_egg():
row = randint(0, 29)
col = randint(0, 29)
return Food(10 + 20 * col, 10 + 20 * row, 20)

def reset_game():
nonlocal snake, food, game_over, total
food = create_egg()
snake = Snake()
game_over = False
total = 0
pygame.event.clear() #清理事件

pygame.init()
total = 0
wall = Wall(10, 10, 600, 600)
food = create_egg()
snake = Snake()
score = pygame.font.SysFont('SimHei', 32)
pygame.display.set_caption('贪吃蛇')
screen = pygame.display.set_mode((620, 620))
screen.fill((242, 242, 242))

pygame.display.flip()
clock = pygame.time.Clock()

running = True
game_over = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
handle_key_event(event)
if not game_over:
refresh()
snake.eat_food(food)
snake.move()

if snake.collide(wall) or snake.eat_me():
game_over = True
if snake.eat_food(food):
food = create_egg()
total += 10
score_board = score.render("score: %d" % total, True, [0, 0, 0])
text_board = score_board.get_rect()
text_board.center = (520, 25)
screen.blit(score_board, text_board)
pygame.display.update()
clock.tick(10)

pygame.quit()

if __name__ == '__main__':
main()
#panda3D 用于3D游戏开发
#软技能、 unix编程技术（好书）