目录
  •  一、效果展示
    • 1、俄罗斯方块
    • 2、扫雷
    • 3、五子棋
    • 4、贪吃蛇
  • 二、代码展示
    • 1、俄罗斯方块
    • 2、扫雷
    • 3、五子棋
    • 4、贪吃蛇

 一、效果展示

1、俄罗斯方块

这个应该是玩起来最最简单的了…

2、扫雷

运气好,点了四下都没踩雷哈哈…

3、五子棋

我是菜鸡,玩不赢电脑人…

4、贪吃蛇

害,这个是最惊心动魄的,为了我的小心脏,不玩了不玩了…

女朋友:你就是借机在玩游戏,逮到了

啊这…

那我不吹牛逼了,我们来敲代码吧~

二、代码展示

1、俄罗斯方块

方块部分

这部分代码单独保存py文件,这里我命名为 blocks.py

方块形状的设计,一开始我是做成 4 × 4,长宽最长都是4的话旋转的时候就不考虑怎么转了,就是从一个图形替换成另一个。

要实现这个功能,只要固定左上角的坐标就可以了。

import random
from collections import namedtuple

point = namedtuple('point', 'x y')
shape = namedtuple('shape', 'x y width height')
block = namedtuple('block', 'template start_pos end_pos name next')


# s形方块
s_block = [block(['.oo',
                  'oo.',
                  '...'], point(0, 0), point(2, 1), 's', 1),
           block(['o..',
                  'oo.',
                  '.o.'], point(0, 0), point(1, 2), 's', 0)]
# z形方块
z_block = [block(['oo.',
                  '.oo',
                  '...'], point(0, 0), point(2, 1), 'z', 1),
           block(['.o.',
                  'oo.',
                  'o..'], point(0, 0), point(1, 2), 'z', 0)]
# i型方块
i_block = [block(['.o..',
                  '.o..',
                  '.o..',
                  '.o..'], point(1, 0), point(1, 3), 'i', 1),
           block(['....',
                  '....',
                  'oooo',
                  '....'], point(0, 2), point(3, 2), 'i', 0)]
# o型方块
o_block = [block(['oo',
                  'oo'], point(0, 0), point(1, 1), 'o', 0)]
# j型方块
j_block = [block(['o..',
                  'ooo',
                  '...'], point(0, 0), point(2, 1), 'j', 1),
           block(['.oo',
                  '.o.',
                  '.o.'], point(1, 0), point(2, 2), 'j', 2),
           block(['...',
                  'ooo',
                  '..o'], point(0, 1), point(2, 2), 'j', 3),
           block(['.o.',
                  '.o.',
                  'oo.'], point(0, 0), point(1, 2), 'j', 0)]
# l型方块
l_block = [block(['..o',
                  'ooo',
                  '...'], point(0, 0), point(2, 1), 'l', 1),
           block(['.o.',
                  '.o.',
                  '.oo'], point(1, 0), point(2, 2), 'l', 2),
           block(['...',
                  'ooo',
                  'o..'], point(0, 1), point(2, 2), 'l', 3),
           block(['oo.',
                  '.o.',
                  '.o.'], point(0, 0), point(1, 2), 'l', 0)]
# t型方块
t_block = [block(['.o.',
                  'ooo',
                  '...'], point(0, 0), point(2, 1), 't', 1),
           block(['.o.',
                  '.oo',
                  '.o.'], point(1, 0), point(2, 2), 't', 2),
           block(['...',
                  'ooo',
                  '.o.'], point(0, 1), point(2, 2), 't', 3),
           block(['.o.',
                  'oo.',
                  '.o.'], point(0, 0), point(1, 2), 't', 0)]

blocks = {'o': o_block,
          'i': i_block,
          'z': z_block,
          't': t_block,
          'l': l_block,
          's': s_block,
          'j': j_block}


def get_block():
    block_name = random.choice('oiztlsj')
    b = blocks[block_name]
    idx = random.randint(0, len(b) - 1)
    return b[idx]


def get_next_block(block):
    b = blocks[block.name]
    return b[block.next]

游戏主代码

import sys
import time
import pygame
from pygame.locals import *
import blocks
size = 30  # 每个小方格大小
block_height = 25  # 游戏区高度
block_width = 10   # 游戏区宽度
border_width = 4   # 游戏区边框宽度
border_color = (40, 40, 200)  # 游戏区边框颜色
screen_width = size * (block_width + 5)  # 游戏屏幕的宽
screen_height = size * block_height      # 游戏屏幕的高
bg_color = (40, 40, 60)  # 背景色
block_color = (20, 128, 200)  #
black = (0, 0, 0)
red = (200, 30, 30)      # game over 的字体颜色
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgtext = font.render(text, true, fcolor)
screen.blit(imgtext, (x, y))
def main():
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('俄罗斯方块')
font1 = pygame.font.sysfont('simhei', 24)  # 黑体24
font2 = pygame.font.font(none, 72)  # game over 的字体
font_pos_x = block_width * size + border_width + 10  # 右侧信息显示区域字体位置的x坐标
gameover_size = font2.size('game over')
font1_height = int(font1.size('得分')[1])
cur_block = none   # 当前下落方块
next_block = none  # 下一个方块
cur_pos_x, cur_pos_y = 0, 0
game_area = none    # 整个游戏区域
game_over = true
start = false       # 是否开始,当start = true,game_over = true 时,才显示 game over
score = 0           # 得分
orispeed = 0.5      # 原始速度
speed = orispeed    # 当前速度
pause = false       # 暂停
last_drop_time = none   # 上次下落时间
last_press_time = none  # 上次按键时间
def _dock():
nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y, game_over, score, speed
for _i in range(cur_block.start_pos.y, cur_block.end_pos.y + 1):
for _j in range(cur_block.start_pos.x, cur_block.end_pos.x + 1):
if cur_block.template[_i][_j] != '.':
game_area[cur_pos_y + _i][cur_pos_x + _j] = '0'
if cur_pos_y + cur_block.start_pos.y <= 0:
game_over = true
else:
# 计算消除
remove_idxs = []
for _i in range(cur_block.start_pos.y, cur_block.end_pos.y + 1):
if all(_x == '0' for _x in game_area[cur_pos_y + _i]):
remove_idxs.append(cur_pos_y + _i)
if remove_idxs:
# 计算得分
remove_count = len(remove_idxs)
if remove_count == 1:
score += 100
elif remove_count == 2:
score += 300
elif remove_count == 3:
score += 700
elif remove_count == 4:
score += 1500
speed = orispeed - 0.03 * (score // 10000)
# 消除
_i = _j = remove_idxs[-1]
while _i >= 0:
while _j in remove_idxs:
_j -= 1
if _j < 0:
game_area[_i] = ['.'] * block_width
else:
game_area[_i] = game_area[_j]
_i -= 1
_j -= 1
cur_block = next_block
next_block = blocks.get_block()
cur_pos_x, cur_pos_y = (block_width - cur_block.end_pos.x - 1) // 2, -1 - cur_block.end_pos.y
def _judge(pos_x, pos_y, block):
nonlocal game_area
for _i in range(block.start_pos.y, block.end_pos.y + 1):
if pos_y + block.end_pos.y >= block_height:
return false
for _j in range(block.start_pos.x, block.end_pos.x + 1):
if pos_y + _i >= 0 and block.template[_i][_j] != '.' and game_area[pos_y + _i][pos_x + _j] != '.':
return false
return true
while true:
for event in pygame.event.get():
if event.type == quit:
sys.exit()
elif event.type == keydown:
if event.key == k_return:
if game_over:
start = true
game_over = false
score = 0
last_drop_time = time.time()
last_press_time = time.time()
game_area = [['.'] * block_width for _ in range(block_height)]
cur_block = blocks.get_block()
next_block = blocks.get_block()
cur_pos_x, cur_pos_y = (block_width - cur_block.end_pos.x - 1) // 2, -1 - cur_block.end_pos.y
elif event.key == k_space:
if not game_over:
pause = not pause
elif event.key in (k_w, k_up):
if 0 <= cur_pos_x <= block_width - len(cur_block.template[0]):
_next_block = blocks.get_next_block(cur_block)
if _judge(cur_pos_x, cur_pos_y, _next_block):
cur_block = _next_block
if event.type == pygame.keydown:
if event.key == pygame.k_left:
if not game_over and not pause:
if time.time() - last_press_time > 0.1:
last_press_time = time.time()
if cur_pos_x > - cur_block.start_pos.x:
if _judge(cur_pos_x - 1, cur_pos_y, cur_block):
cur_pos_x -= 1
if event.key == pygame.k_right:
if not game_over and not pause:
if time.time() - last_press_time > 0.1:
last_press_time = time.time()
# 不能移除右边框
if cur_pos_x + cur_block.end_pos.x + 1 < block_width:
if _judge(cur_pos_x + 1, cur_pos_y, cur_block):
cur_pos_x += 1
if event.key == pygame.k_down:
if not game_over and not pause:
if time.time() - last_press_time > 0.1:
last_press_time = time.time()
if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
_dock()
else:
last_drop_time = time.time()
cur_pos_y += 1
_draw_background(screen)
_draw_game_area(screen, game_area)
_draw_gridlines(screen)
_draw_info(screen, font1, font_pos_x, font1_height, score)
# 画显示信息中的下一个方块
_draw_block(screen, next_block, font_pos_x, 30 + (font1_height + 6) * 5, 0, 0)
if not game_over:
cur_drop_time = time.time()
if cur_drop_time - last_drop_time > speed:
if not pause:
if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
_dock()
else:
last_drop_time = cur_drop_time
cur_pos_y += 1
else:
if start:
print_text(screen, font2,
(screen_width - gameover_size[0]) // 2, (screen_height - gameover_size[1]) // 2,
'game over', red)
# 画当前下落方块
_draw_block(screen, cur_block, 0, 0, cur_pos_x, cur_pos_y)
pygame.display.flip()
# 画背景
def _draw_background(screen):
# 填充背景色
screen.fill(bg_color)
# 画游戏区域分隔线
pygame.draw.line(screen, border_color,
(size * block_width + border_width // 2, 0),
(size * block_width + border_width // 2, screen_height), border_width)
# 画网格线
def _draw_gridlines(screen):
# 画网格线 竖线
for x in range(block_width):
pygame.draw.line(screen, black, (x * size, 0), (x * size, screen_height), 1)
# 画网格线 横线
for y in range(block_height):
pygame.draw.line(screen, black, (0, y * size), (block_width * size, y * size), 1)
# 画已经落下的方块
def _draw_game_area(screen, game_area):
if game_area:
for i, row in enumerate(game_area):
for j, cell in enumerate(row):
if cell != '.':
pygame.draw.rect(screen, block_color, (j * size, i * size, size, size), 0)
# 画单个方块
def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
if block:
for i in range(block.start_pos.y, block.end_pos.y + 1):
for j in range(block.start_pos.x, block.end_pos.x + 1):
if block.template[i][j] != '.':
pygame.draw.rect(screen, block_color,
(offset_x + (pos_x + j) * size, offset_y + (pos_y + i) * size, size, size), 0)
# 画得分等信息
def _draw_info(screen, font, pos_x, font_height, score):
print_text(screen, font, pos_x, 10, f'得分: ')
print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个:')
if __name__ == '__main__':
main()

2、扫雷

地雷部分

一样的,单独保存py文件,mineblock.py

import random
from enum import enum
block_width = 30
block_height = 16
size = 20           # 块大小
mine_count = 99     # 地雷数
class blockstatus(enum):
normal = 1  # 未点击
opened = 2  # 已点击
mine = 3    # 地雷
flag = 4    # 标记为地雷
ask = 5     # 标记为问号
bomb = 6    # 踩中地雷
hint = 7    # 被双击的周围
double = 8  # 正被鼠标左右键双击
class mine:
def __init__(self, x, y, value=0):
self._x = x
self._y = y
self._value = 0
self._around_mine_count = -1
self._status = blockstatus.normal
self.set_value(value)
def __repr__(self):
return str(self._value)
# return f'({self._x},{self._y})={self._value}, status={self.status}'
def get_x(self):
return self._x
def set_x(self, x):
self._x = x
x = property(fget=get_x, fset=set_x)
def get_y(self):
return self._y
def set_y(self, y):
self._y = y
y = property(fget=get_y, fset=set_y)
def get_value(self):
return self._value
def set_value(self, value):
if value:
self._value = 1
else:
self._value = 0
value = property(fget=get_value, fset=set_value, doc='0:非地雷 1:雷')
def get_around_mine_count(self):
return self._around_mine_count
def set_around_mine_count(self, around_mine_count):
self._around_mine_count = around_mine_count
around_mine_count = property(fget=get_around_mine_count, fset=set_around_mine_count, doc='四周地雷数量')
def get_status(self):
return self._status
def set_status(self, value):
self._status = value
status = property(fget=get_status, fset=set_status, doc='blockstatus')
class mineblock:
def __init__(self):
self._block = [[mine(i, j) for i in range(block_width)] for j in range(block_height)]
# 埋雷
for i in random.sample(range(block_width * block_height), mine_count):
self._block[i // block_width][i % block_width].value = 1
def get_block(self):
return self._block
block = property(fget=get_block)
def getmine(self, x, y):
return self._block[y][x]
def open_mine(self, x, y):
# 踩到雷了
if self._block[y][x].value:
self._block[y][x].status = blockstatus.bomb
return false
# 先把状态改为 opened
self._block[y][x].status = blockstatus.opened
around = _get_around(x, y)
_sum = 0
for i, j in around:
if self._block[j][i].value:
_sum += 1
self._block[y][x].around_mine_count = _sum
# 如果周围没有雷,那么将周围8个未中未点开的递归算一遍
# 这就能实现一点出现一大片打开的效果了
if _sum == 0:
for i, j in around:
if self._block[j][i].around_mine_count == -1:
self.open_mine(i, j)
return true
def double_mouse_button_down(self, x, y):
if self._block[y][x].around_mine_count == 0:
return true
self._block[y][x].status = blockstatus.double
around = _get_around(x, y)
sumflag = 0     # 周围被标记的雷数量
for i, j in _get_around(x, y):
if self._block[j][i].status == blockstatus.flag:
sumflag += 1
# 周边的雷已经全部被标记
result = true
if sumflag == self._block[y][x].around_mine_count:
for i, j in around:
if self._block[j][i].status == blockstatus.normal:
if not self.open_mine(i, j):
result = false
else:
for i, j in around:
if self._block[j][i].status == blockstatus.normal:
self._block[j][i].status = blockstatus.hint
return result
def double_mouse_button_up(self, x, y):
self._block[y][x].status = blockstatus.opened
for i, j in _get_around(x, y):
if self._block[j][i].status == blockstatus.hint:
self._block[j][i].status = blockstatus.normal
def _get_around(x, y):
"""返回(x, y)周围的点的坐标"""
# 这里注意,range 末尾是开区间,所以要加 1
return [(i, j) for i in range(max(0, x - 1), min(block_width - 1, x + 1) + 1)
for j in range(max(0, y - 1), min(block_height - 1, y + 1) + 1) if i != x or j != y]

素材

主代码

import sys
import time
from enum import enum
import pygame
from pygame.locals import *
from mineblock import *
# 游戏屏幕的宽
screen_width = block_width * size
# 游戏屏幕的高
screen_height = (block_height + 2) * size
class gamestatus(enum):
readied = 1,
started = 2,
over = 3,
win = 4
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgtext = font.render(text, true, fcolor)
screen.blit(imgtext, (x, y))
def main():
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('扫雷')
font1 = pygame.font.font('resources/a.ttf', size * 2)  # 得分的字体
fwidth, fheight = font1.size('999')
red = (200, 40, 40)
# 加载资源图片,因为资源文件大小不一,所以做了统一的缩放处理
img0 = pygame.image.load('resources/0.bmp').convert()
img0 = pygame.transform.smoothscale(img0, (size, size))
img1 = pygame.image.load('resources/1.bmp').convert()
img1 = pygame.transform.smoothscale(img1, (size, size))
img2 = pygame.image.load('resources/2.bmp').convert()
img2 = pygame.transform.smoothscale(img2, (size, size))
img3 = pygame.image.load('resources/3.bmp').convert()
img3 = pygame.transform.smoothscale(img3, (size, size))
img4 = pygame.image.load('resources/4.bmp').convert()
img4 = pygame.transform.smoothscale(img4, (size, size))
img5 = pygame.image.load('resources/5.bmp').convert()
img5 = pygame.transform.smoothscale(img5, (size, size))
img6 = pygame.image.load('resources/6.bmp').convert()
img6 = pygame.transform.smoothscale(img6, (size, size))
img7 = pygame.image.load('resources/7.bmp').convert()
img7 = pygame.transform.smoothscale(img7, (size, size))
img8 = pygame.image.load('resources/8.bmp').convert()
img8 = pygame.transform.smoothscale(img8, (size, size))
img_blank = pygame.image.load('resources/blank.bmp').convert()
img_blank = pygame.transform.smoothscale(img_blank, (size, size))
img_flag = pygame.image.load('resources/flag.bmp').convert()
img_flag = pygame.transform.smoothscale(img_flag, (size, size))
img_ask = pygame.image.load('resources/ask.bmp').convert()
img_ask = pygame.transform.smoothscale(img_ask, (size, size))
img_mine = pygame.image.load('resources/mine.bmp').convert()
img_mine = pygame.transform.smoothscale(img_mine, (size, size))
img_blood = pygame.image.load('resources/blood.bmp').convert()
img_blood = pygame.transform.smoothscale(img_blood, (size, size))
img_error = pygame.image.load('resources/error.bmp').convert()
img_error = pygame.transform.smoothscale(img_error, (size, size))
face_size = int(size * 1.25)
img_face_fail = pygame.image.load('resources/face_fail.bmp').convert()
img_face_fail = pygame.transform.smoothscale(img_face_fail, (face_size, face_size))
img_face_normal = pygame.image.load('resources/face_normal.bmp').convert()
img_face_normal = pygame.transform.smoothscale(img_face_normal, (face_size, face_size))
img_face_success = pygame.image.load('resources/face_success.bmp').convert()
img_face_success = pygame.transform.smoothscale(img_face_success, (face_size, face_size))
face_pos_x = (screen_width - face_size) // 2
face_pos_y = (size * 2 - face_size) // 2
img_dict = {
0: img0,
1: img1,
2: img2,
3: img3,
4: img4,
5: img5,
6: img6,
7: img7,
8: img8
}
bgcolor = (225, 225, 225)   # 背景色
block = mineblock()
game_status = gamestatus.readied
start_time = none   # 开始时间
elapsed_time = 0    # 耗时
while true:
# 填充背景色
screen.fill(bgcolor)
for event in pygame.event.get():
if event.type == quit:
sys.exit()
elif event.type == mousebuttondown:
mouse_x, mouse_y = event.pos
x = mouse_x // size
y = mouse_y // size - 2
b1, b2, b3 = pygame.mouse.get_pressed()
if game_status == gamestatus.started:
# 鼠标左右键同时按下,如果已经标记了所有雷,则打开周围一圈
# 如果还未标记完所有雷,则有一个周围一圈被同时按下的效果
if b1 and b3:
mine = block.getmine(x, y)
if mine.status == blockstatus.opened:
if not block.double_mouse_button_down(x, y):
game_status = gamestatus.over
elif event.type == mousebuttonup:
if y < 0:
if face_pos_x <= mouse_x <= face_pos_x + face_size \
and face_pos_y <= mouse_y <= face_pos_y + face_size:
game_status = gamestatus.readied
block = mineblock()
start_time = time.time()
elapsed_time = 0
continue
if game_status == gamestatus.readied:
game_status = gamestatus.started
start_time = time.time()
elapsed_time = 0
if game_status == gamestatus.started:
mine = block.getmine(x, y)
if b1 and not b3:       # 按鼠标左键
if mine.status == blockstatus.normal:
if not block.open_mine(x, y):
game_status = gamestatus.over
elif not b1 and b3:     # 按鼠标右键
if mine.status == blockstatus.normal:
mine.status = blockstatus.flag
elif mine.status == blockstatus.flag:
mine.status = blockstatus.ask
elif mine.status == blockstatus.ask:
mine.status = blockstatus.normal
elif b1 and b3:
if mine.status == blockstatus.double:
block.double_mouse_button_up(x, y)
flag_count = 0
opened_count = 0
for row in block.block:
for mine in row:
pos = (mine.x * size, (mine.y + 2) * size)
if mine.status == blockstatus.opened:
screen.blit(img_dict[mine.around_mine_count], pos)
opened_count += 1
elif mine.status == blockstatus.double:
screen.blit(img_dict[mine.around_mine_count], pos)
elif mine.status == blockstatus.bomb:
screen.blit(img_blood, pos)
elif mine.status == blockstatus.flag:
screen.blit(img_flag, pos)
flag_count += 1
elif mine.status == blockstatus.ask:
screen.blit(img_ask, pos)
elif mine.status == blockstatus.hint:
screen.blit(img0, pos)
elif game_status == gamestatus.over and mine.value:
screen.blit(img_mine, pos)
elif mine.value == 0 and mine.status == blockstatus.flag:
screen.blit(img_error, pos)
elif mine.status == blockstatus.normal:
screen.blit(img_blank, pos)
print_text(screen, font1, 30, (size * 2 - fheight) // 2 - 2, '%02d' % (mine_count - flag_count), red)
if game_status == gamestatus.started:
elapsed_time = int(time.time() - start_time)
print_text(screen, font1, screen_width - fwidth - 30, (size * 2 - fheight) // 2 - 2, '%03d' % elapsed_time, red)
if flag_count + opened_count == block_width * block_height:
game_status = gamestatus.win
if game_status == gamestatus.over:
screen.blit(img_face_fail, (face_pos_x, face_pos_y))
elif game_status == gamestatus.win:
screen.blit(img_face_success, (face_pos_x, face_pos_y))
else:
screen.blit(img_face_normal, (face_pos_x, face_pos_y))
pygame.display.update()
if __name__ == '__main__':
main()

3、五子棋

五子棋就没那么多七七八八的素材和其它代码了

import sys
import random
import pygame
from pygame.locals import *
import pygame.gfxdraw
from collections import namedtuple
chessman = namedtuple('chessman', 'name value color')
point = namedtuple('point', 'x y')
black_chessman = chessman('黑子', 1, (45, 45, 45))
white_chessman = chessman('白子', 2, (219, 219, 219))
offset = [(1, 0), (0, 1), (1, 1), (1, -1)]
class checkerboard:
def __init__(self, line_points):
self._line_points = line_points
self._checkerboard = [[0] * line_points for _ in range(line_points)]
def _get_checkerboard(self):
return self._checkerboard
checkerboard = property(_get_checkerboard)
# 判断是否可落子
def can_drop(self, point):
return self._checkerboard[point.y][point.x] == 0
def drop(self, chessman, point):
"""
落子
:param chessman:
:param point:落子位置
:return:若该子落下之后即可获胜,则返回获胜方,否则返回 none
"""
print(f'{chessman.name} ({point.x}, {point.y})')
self._checkerboard[point.y][point.x] = chessman.value
if self._win(point):
print(f'{chessman.name}获胜')
return chessman
# 判断是否赢了
def _win(self, point):
cur_value = self._checkerboard[point.y][point.x]
for os in offset:
if self._get_count_on_direction(point, cur_value, os[0], os[1]):
return true
def _get_count_on_direction(self, point, value, x_offset, y_offset):
count = 1
for step in range(1, 5):
x = point.x + step * x_offset
y = point.y + step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
for step in range(1, 5):
x = point.x - step * x_offset
y = point.y - step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
return count >= 5
size = 30  # 棋盘每个点时间的间隔
line_points = 19  # 棋盘每行/每列点数
outer_width = 20  # 棋盘外宽度
border_width = 4  # 边框宽度
inside_width = 4  # 边框跟实际的棋盘之间的间隔
border_length = size * (line_points - 1) + inside_width * 2 + border_width  # 边框线的长度
start_x = start_y = outer_width + int(border_width / 2) + inside_width  # 网格线起点(左上角)坐标
screen_height = size * (line_points - 1) + outer_width * 2 + border_width + inside_width * 2  # 游戏屏幕的高
screen_width = screen_height + 200  # 游戏屏幕的宽
stone_radius = size // 2 - 3  # 棋子半径
stone_radius2 = size // 2 + 3
checkerboard_color = (0xe3, 0x92, 0x65)  # 棋盘颜色
black_color = (0, 0, 0)
white_color = (255, 255, 255)
red_color = (200, 30, 30)
blue_color = (30, 30, 200)
right_info_pos_x = screen_height + stone_radius2 * 2 + 10
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgtext = font.render(text, true, fcolor)
screen.blit(imgtext, (x, y))
def main():
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('五子棋')
font1 = pygame.font.sysfont('simhei', 32)
font2 = pygame.font.sysfont('simhei', 72)
fwidth, fheight = font2.size('黑方获胜')
checkerboard = checkerboard(line_points)
cur_runner = black_chessman
winner = none
computer = ai(line_points, white_chessman)
black_win_count = 0
white_win_count = 0
while true:
for event in pygame.event.get():
if event.type == quit:
sys.exit()
elif event.type == keydown:
if event.key == k_return:
if winner is not none:
winner = none
cur_runner = black_chessman
checkerboard = checkerboard(line_points)
computer = ai(line_points, white_chessman)
elif event.type == mousebuttondown:
if winner is none:
pressed_array = pygame.mouse.get_pressed()
if pressed_array[0]:
mouse_pos = pygame.mouse.get_pos()
click_point = _get_clickpoint(mouse_pos)
if click_point is not none:
if checkerboard.can_drop(click_point):
winner = checkerboard.drop(cur_runner, click_point)
if winner is none:
cur_runner = _get_next(cur_runner)
computer.get_opponent_drop(click_point)
ai_point = computer.ai_drop()
winner = checkerboard.drop(cur_runner, ai_point)
if winner is not none:
white_win_count += 1
cur_runner = _get_next(cur_runner)
else:
black_win_count += 1
else:
print('超出棋盘区域')
# 画棋盘
_draw_checkerboard(screen)
# 画棋盘上已有的棋子
for i, row in enumerate(checkerboard.checkerboard):
for j, cell in enumerate(row):
if cell == black_chessman.value:
_draw_chessman(screen, point(j, i), black_chessman.color)
elif cell == white_chessman.value:
_draw_chessman(screen, point(j, i), white_chessman.color)
_draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count)
if winner:
print_text(screen, font2, (screen_width - fwidth)//2, (screen_height - fheight)//2, winner.name + '获胜', red_color)
pygame.display.flip()
def _get_next(cur_runner):
if cur_runner == black_chessman:
return white_chessman
else:
return black_chessman
# 画棋盘
def _draw_checkerboard(screen):
# 填充棋盘背景色
screen.fill(checkerboard_color)
# 画棋盘网格线外的边框
pygame.draw.rect(screen, black_color, (outer_width, outer_width, border_length, border_length), border_width)
# 画网格线
for i in range(line_points):
pygame.draw.line(screen, black_color,
(start_y, start_y + size * i),
(start_y + size * (line_points - 1), start_y + size * i),
1)
for j in range(line_points):
pygame.draw.line(screen, black_color,
(start_x + size * j, start_x),
(start_x + size * j, start_x + size * (line_points - 1)),
1)
# 画星位和天元
for i in (3, 9, 15):
for j in (3, 9, 15):
if i == j == 9:
radius = 5
else:
radius = 3
# pygame.draw.circle(screen, black, (start_x + size * i, start_y + size * j), radius)
pygame.gfxdraw.aacircle(screen, start_x + size * i, start_y + size * j, radius, black_color)
pygame.gfxdraw.filled_circle(screen, start_x + size * i, start_y + size * j, radius, black_color)
# 画棋子
def _draw_chessman(screen, point, stone_color):
# pygame.draw.circle(screen, stone_color, (start_x + size * point.x, start_y + size * point.y), stone_radius)
pygame.gfxdraw.aacircle(screen, start_x + size * point.x, start_y + size * point.y, stone_radius, stone_color)
pygame.gfxdraw.filled_circle(screen, start_x + size * point.x, start_y + size * point.y, stone_radius, stone_color)
# 画左侧信息显示
def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count):
_draw_chessman_pos(screen, (screen_height + stone_radius2, start_x + stone_radius2), black_chessman.color)
_draw_chessman_pos(screen, (screen_height + stone_radius2, start_x + stone_radius2 * 4), white_chessman.color)
print_text(screen, font, right_info_pos_x, start_x + 3, '玩家', blue_color)
print_text(screen, font, right_info_pos_x, start_x + stone_radius2 * 3 + 3, '电脑', blue_color)
print_text(screen, font, screen_height, screen_height - stone_radius2 * 8, '战况:', blue_color)
_draw_chessman_pos(screen, (screen_height + stone_radius2, screen_height - int(stone_radius2 * 4.5)), black_chessman.color)
_draw_chessman_pos(screen, (screen_height + stone_radius2, screen_height - stone_radius2 * 2), white_chessman.color)
print_text(screen, font, right_info_pos_x, screen_height - int(stone_radius2 * 5.5) + 3, f'{black_win_count} 胜', blue_color)
print_text(screen, font, right_info_pos_x, screen_height - stone_radius2 * 3 + 3, f'{white_win_count} 胜', blue_color)
def _draw_chessman_pos(screen, pos, stone_color):
pygame.gfxdraw.aacircle(screen, pos[0], pos[1], stone_radius2, stone_color)
pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], stone_radius2, stone_color)
# 根据鼠标点击位置,返回游戏区坐标
def _get_clickpoint(click_pos):
pos_x = click_pos[0] - start_x
pos_y = click_pos[1] - start_y
if pos_x < -inside_width or pos_y < -inside_width:
return none
x = pos_x // size
y = pos_y // size
if pos_x % size > stone_radius:
x += 1
if pos_y % size > stone_radius:
y += 1
if x >= line_points or y >= line_points:
return none
return point(x, y)
class ai:
def __init__(self, line_points, chessman):
self._line_points = line_points
self._my = chessman
self._opponent = black_chessman if chessman == white_chessman else white_chessman
self._checkerboard = [[0] * line_points for _ in range(line_points)]
def get_opponent_drop(self, point):
self._checkerboard[point.y][point.x] = self._opponent.value
def ai_drop(self):
point = none
score = 0
for i in range(self._line_points):
for j in range(self._line_points):
if self._checkerboard[j][i] == 0:
_score = self._get_point_score(point(i, j))
if _score > score:
score = _score
point = point(i, j)
elif _score == score and _score > 0:
r = random.randint(0, 100)
if r % 2 == 0:
point = point(i, j)
self._checkerboard[point.y][point.x] = self._my.value
return point
def _get_point_score(self, point):
score = 0
for os in offset:
score += self._get_direction_score(point, os[0], os[1])
return score
def _get_direction_score(self, point, x_offset, y_offset):
count = 0   # 落子处我方连续子数
_count = 0  # 落子处对方连续子数
space = none   # 我方连续子中有无空格
_space = none  # 对方连续子中有无空格
both = 0    # 我方连续子两端有无阻挡
_both = 0   # 对方连续子两端有无阻挡
# 如果是 1 表示是边上是我方子,2 表示敌方子
flag = self._get_stone_color(point, x_offset, y_offset, true)
if flag != 0:
for step in range(1, 6):
x = point.x + step * x_offset
y = point.y + step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points:
if flag == 1:
if self._checkerboard[y][x] == self._my.value:
count += 1
if space is false:
space = true
elif self._checkerboard[y][x] == self._opponent.value:
_both += 1
break
else:
if space is none:
space = false
else:
break   # 遇到第二个空格退出
elif flag == 2:
if self._checkerboard[y][x] == self._my.value:
_both += 1
break
elif self._checkerboard[y][x] == self._opponent.value:
_count += 1
if _space is false:
_space = true
else:
if _space is none:
_space = false
else:
break
else:
# 遇到边也就是阻挡
if flag == 1:
both += 1
elif flag == 2:
_both += 1
if space is false:
space = none
if _space is false:
_space = none
_flag = self._get_stone_color(point, -x_offset, -y_offset, true)
if _flag != 0:
for step in range(1, 6):
x = point.x - step * x_offset
y = point.y - step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points:
if _flag == 1:
if self._checkerboard[y][x] == self._my.value:
count += 1
if space is false:
space = true
elif self._checkerboard[y][x] == self._opponent.value:
_both += 1
break
else:
if space is none:
space = false
else:
break   # 遇到第二个空格退出
elif _flag == 2:
if self._checkerboard[y][x] == self._my.value:
_both += 1
break
elif self._checkerboard[y][x] == self._opponent.value:
_count += 1
if _space is false:
_space = true
else:
if _space is none:
_space = false
else:
break
else:
# 遇到边也就是阻挡
if _flag == 1:
both += 1
elif _flag == 2:
_both += 1
score = 0
if count == 4:
score = 10000
elif _count == 4:
score = 9000
elif count == 3:
if both == 0:
score = 1000
elif both == 1:
score = 100
else:
score = 0
elif _count == 3:
if _both == 0:
score = 900
elif _both == 1:
score = 90
else:
score = 0
elif count == 2:
if both == 0:
score = 100
elif both == 1:
score = 10
else:
score = 0
elif _count == 2:
if _both == 0:
score = 90
elif _both == 1:
score = 9
else:
score = 0
elif count == 1:
score = 10
elif _count == 1:
score = 9
else:
score = 0
if space or _space:
score /= 2
return score
# 判断指定位置处在指定方向上是我方子、对方子、空
def _get_stone_color(self, point, x_offset, y_offset, next):
x = point.x + x_offset
y = point.y + y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points:
if self._checkerboard[y][x] == self._my.value:
return 1
elif self._checkerboard[y][x] == self._opponent.value:
return 2
else:
if next:
return self._get_stone_color(point(x, y), x_offset, y_offset, false)
else:
return 0
else:
return 0
if __name__ == '__main__':
main()

4、贪吃蛇

import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque
screen_width = 600      # 屏幕宽度
screen_height = 480     # 屏幕高度
size = 20               # 小方格大小
line_width = 1          # 网格线宽度
# 游戏区域的坐标范围
scope_x = (0, screen_width // size - 1)
scope_y = (2, screen_height // size - 1)
# 食物的分值及颜色
food_style_list = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]
light = (100, 100, 100)
dark = (200, 200, 200)      # 蛇的颜色
black = (0, 0, 0)           # 网格线颜色
red = (200, 30, 30)         # 红色,game over 的字体颜色
bgcolor = (40, 40, 60)      # 背景色
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgtext = font.render(text, true, fcolor)
screen.blit(imgtext, (x, y))
# 初始化蛇
def init_snake():
snake = deque()
snake.append((2, scope_y[0]))
snake.append((1, scope_y[0]))
snake.append((0, scope_y[0]))
return snake
def create_food(snake):
food_x = random.randint(scope_x[0], scope_x[1])
food_y = random.randint(scope_y[0], scope_y[1])
while (food_x, food_y) in snake:
# 如果食物出现在蛇身上,则重来
food_x = random.randint(scope_x[0], scope_x[1])
food_y = random.randint(scope_y[0], scope_y[1])
return food_x, food_y
def get_food_style():
return food_style_list[random.randint(0, 2)]
def main():
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')
font1 = pygame.font.sysfont('simhei', 24)  # 得分的字体
font2 = pygame.font.font(none, 72)  # game over 的字体
fwidth, fheight = font2.size('game over')
# 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接game over
# b 变量就是用于防止这种情况的发生
b = true
# 蛇
snake = init_snake()
# 食物
food = create_food(snake)
food_style = get_food_style()
# 方向
pos = (1, 0)
game_over = true
start = false       # 是否开始,当start = true,game_over = true 时,才显示 game over
score = 0           # 得分
orispeed = 0.5      # 原始速度
speed = orispeed
last_move_time = none
pause = false       # 暂停
while true:
for event in pygame.event.get():
if event.type == quit:
sys.exit()
elif event.type == keydown:
if event.key == k_return:
if game_over:
start = true
game_over = false
b = true
snake = init_snake()
food = create_food(snake)
food_style = get_food_style()
pos = (1, 0)
# 得分
score = 0
last_move_time = time.time()
elif event.key == k_space:
if not game_over:
pause = not pause
elif event.key in (k_w, k_up):
# 这个判断是为了防止蛇向上移时按了向下键,导致直接 game over
if b and not pos[1]:
pos = (0, -1)
b = false
elif event.key in (k_s, k_down):
if b and not pos[1]:
pos = (0, 1)
b = false
elif event.key in (k_a, k_left):
if b and not pos[0]:
pos = (-1, 0)
b = false
elif event.key in (k_d, k_right):
if b and not pos[0]:
pos = (1, 0)
b = false
# 填充背景色
screen.fill(bgcolor)
# 画网格线 竖线
for x in range(size, screen_width, size):
pygame.draw.line(screen, black, (x, scope_y[0] * size), (x, screen_height), line_width)
# 画网格线 横线
for y in range(scope_y[0] * size, screen_height, size):
pygame.draw.line(screen, black, (0, y), (screen_width, y), line_width)
if not game_over:
curtime = time.time()
if curtime - last_move_time > speed:
if not pause:
b = true
last_move_time = curtime
next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1])
if next_s == food:
# 吃到了食物
snake.appendleft(next_s)
score += food_style[0]
speed = orispeed - 0.03 * (score // 100)
food = create_food(snake)
food_style = get_food_style()
else:
if scope_x[0] <= next_s[0] <= scope_x[1] and scope_y[0] <= next_s[1] <= scope_y[1] \
and next_s not in snake:
snake.appendleft(next_s)
snake.pop()
else:
game_over = true
# 画食物
if not game_over:
# 避免 game over 的时候把 game over 的字给遮住了
pygame.draw.rect(screen, food_style[1], (food[0] * size, food[1] * size, size, size), 0)
# 画蛇
for s in snake:
pygame.draw.rect(screen, dark, (s[0] * size + line_width, s[1] * size + line_width,
size - line_width * 2, size - line_width * 2), 0)
print_text(screen, font1, 30, 7, f'速度: {score//100}')
print_text(screen, font1, 450, 7, f'得分: {score}')
if game_over:
if start:
print_text(screen, font2, (screen_width - fwidth) // 2, (screen_height - fheight) // 2, 'game over', red)
pygame.display.update()
if __name__ == '__main__':
main()

以上就是python实现四个经典小游戏合集的详细内容,更多关于python游戏合集的资料请关注www.887551.com其它相关文章!