1000行Python代码实现俄罗斯方块/扫雷/五子棋/贪吃蛇

x33g5p2x  于2021-12-22 转载在 Python  
字(29.0k)|赞(0)|评价(0)|浏览(502)

Python开发小游戏,它有又双叒叕来了…

一、效果展示

1、俄罗斯方块


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

2、扫雷


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

3、五子棋


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

4、贪吃蛇

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

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

啊这…

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

二、代码展示

1、俄罗斯方块

方块部分

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

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

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

  1. import random
  2. from collections import namedtuple
  3. Point = namedtuple('Point', 'X Y')
  4. Shape = namedtuple('Shape', 'X Y Width Height')
  5. Block = namedtuple('Block', 'template start_pos end_pos name next')
  6. # S形方块
  7. S_BLOCK = [Block(['.OO',
  8. 'OO.',
  9. '...'], Point(0, 0), Point(2, 1), 'S', 1),
  10. Block(['O..',
  11. 'OO.',
  12. '.O.'], Point(0, 0), Point(1, 2), 'S', 0)]
  13. # Z形方块
  14. Z_BLOCK = [Block(['OO.',
  15. '.OO',
  16. '...'], Point(0, 0), Point(2, 1), 'Z', 1),
  17. Block(['.O.',
  18. 'OO.',
  19. 'O..'], Point(0, 0), Point(1, 2), 'Z', 0)]
  20. # I型方块
  21. I_BLOCK = [Block(['.O..',
  22. '.O..',
  23. '.O..',
  24. '.O..'], Point(1, 0), Point(1, 3), 'I', 1),
  25. Block(['....',
  26. '....',
  27. 'OOOO',
  28. '....'], Point(0, 2), Point(3, 2), 'I', 0)]
  29. # O型方块
  30. O_BLOCK = [Block(['OO',
  31. 'OO'], Point(0, 0), Point(1, 1), 'O', 0)]
  32. # J型方块
  33. J_BLOCK = [Block(['O..',
  34. 'OOO',
  35. '...'], Point(0, 0), Point(2, 1), 'J', 1),
  36. Block(['.OO',
  37. '.O.',
  38. '.O.'], Point(1, 0), Point(2, 2), 'J', 2),
  39. Block(['...',
  40. 'OOO',
  41. '..O'], Point(0, 1), Point(2, 2), 'J', 3),
  42. Block(['.O.',
  43. '.O.',
  44. 'OO.'], Point(0, 0), Point(1, 2), 'J', 0)]
  45. # L型方块
  46. L_BLOCK = [Block(['..O',
  47. 'OOO',
  48. '...'], Point(0, 0), Point(2, 1), 'L', 1),
  49. Block(['.O.',
  50. '.O.',
  51. '.OO'], Point(1, 0), Point(2, 2), 'L', 2),
  52. Block(['...',
  53. 'OOO',
  54. 'O..'], Point(0, 1), Point(2, 2), 'L', 3),
  55. Block(['OO.',
  56. '.O.',
  57. '.O.'], Point(0, 0), Point(1, 2), 'L', 0)]
  58. # T型方块
  59. T_BLOCK = [Block(['.O.',
  60. 'OOO',
  61. '...'], Point(0, 0), Point(2, 1), 'T', 1),
  62. Block(['.O.',
  63. '.OO',
  64. '.O.'], Point(1, 0), Point(2, 2), 'T', 2),
  65. Block(['...',
  66. 'OOO',
  67. '.O.'], Point(0, 1), Point(2, 2), 'T', 3),
  68. Block(['.O.',
  69. 'OO.',
  70. '.O.'], Point(0, 0), Point(1, 2), 'T', 0)]
  71. BLOCKS = {'O': O_BLOCK,
  72. 'I': I_BLOCK,
  73. 'Z': Z_BLOCK,
  74. 'T': T_BLOCK,
  75. 'L': L_BLOCK,
  76. 'S': S_BLOCK,
  77. 'J': J_BLOCK}
  78. def get_block():
  79. block_name = random.choice('OIZTLSJ')
  80. b = BLOCKS[block_name]
  81. idx = random.randint(0, len(b) - 1)
  82. return b[idx]
  83. def get_next_block(block):
  84. b = BLOCKS[block.name]
  85. return b[block.next]

游戏主代码

  1. import sys
  2. import time
  3. import pygame
  4. from pygame.locals import *
  5. import blocks
  6. SIZE = 30 # 每个小方格大小
  7. BLOCK_HEIGHT = 25 # 游戏区高度
  8. BLOCK_WIDTH = 10 # 游戏区宽度
  9. BORDER_WIDTH = 4 # 游戏区边框宽度
  10. BORDER_COLOR = (40, 40, 200) # 游戏区边框颜色
  11. SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5) # 游戏屏幕的宽
  12. SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT # 游戏屏幕的高
  13. BG_COLOR = (40, 40, 60) # 背景色
  14. BLOCK_COLOR = (20, 128, 200) #
  15. BLACK = (0, 0, 0)
  16. RED = (200, 30, 30) # GAME OVER 的字体颜色
  17. def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
  18. imgText = font.render(text, True, fcolor)
  19. screen.blit(imgText, (x, y))
  20. def main():
  21. pygame.init()
  22. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
  23. pygame.display.set_caption('俄罗斯方块')
  24. font1 = pygame.font.SysFont('SimHei', 24) # 黑体24
  25. font2 = pygame.font.Font(None, 72) # GAME OVER 的字体
  26. font_pos_x = BLOCK_WIDTH * SIZE + BORDER_WIDTH + 10 # 右侧信息显示区域字体位置的X坐标
  27. gameover_size = font2.size('GAME OVER')
  28. font1_height = int(font1.size('得分')[1])
  29. cur_block = None # 当前下落方块
  30. next_block = None # 下一个方块
  31. cur_pos_x, cur_pos_y = 0, 0
  32. game_area = None # 整个游戏区域
  33. game_over = True
  34. start = False # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
  35. score = 0 # 得分
  36. orispeed = 0.5 # 原始速度
  37. speed = orispeed # 当前速度
  38. pause = False # 暂停
  39. last_drop_time = None # 上次下落时间
  40. last_press_time = None # 上次按键时间
  41. def _dock():
  42. nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y, game_over, score, speed
  43. for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
  44. for _j in range(cur_block.start_pos.X, cur_block.end_pos.X + 1):
  45. if cur_block.template[_i][_j] != '.':
  46. game_area[cur_pos_y + _i][cur_pos_x + _j] = '0'
  47. if cur_pos_y + cur_block.start_pos.Y <= 0:
  48. game_over = True
  49. else:
  50. # 计算消除
  51. remove_idxs = []
  52. for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
  53. if all(_x == '0' for _x in game_area[cur_pos_y + _i]):
  54. remove_idxs.append(cur_pos_y + _i)
  55. if remove_idxs:
  56. # 计算得分
  57. remove_count = len(remove_idxs)
  58. if remove_count == 1:
  59. score += 100
  60. elif remove_count == 2:
  61. score += 300
  62. elif remove_count == 3:
  63. score += 700
  64. elif remove_count == 4:
  65. score += 1500
  66. speed = orispeed - 0.03 * (score // 10000)
  67. # 消除
  68. _i = _j = remove_idxs[-1]
  69. while _i >= 0:
  70. while _j in remove_idxs:
  71. _j -= 1
  72. if _j < 0:
  73. game_area[_i] = ['.'] * BLOCK_WIDTH
  74. else:
  75. game_area[_i] = game_area[_j]
  76. _i -= 1
  77. _j -= 1
  78. cur_block = next_block
  79. next_block = blocks.get_block()
  80. cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y
  81. def _judge(pos_x, pos_y, block):
  82. nonlocal game_area
  83. for _i in range(block.start_pos.Y, block.end_pos.Y + 1):
  84. if pos_y + block.end_pos.Y >= BLOCK_HEIGHT:
  85. return False
  86. for _j in range(block.start_pos.X, block.end_pos.X + 1):
  87. if pos_y + _i >= 0 and block.template[_i][_j] != '.' and game_area[pos_y + _i][pos_x + _j] != '.':
  88. return False
  89. return True
  90. while True:
  91. for event in pygame.event.get():
  92. if event.type == QUIT:
  93. sys.exit()
  94. elif event.type == KEYDOWN:
  95. if event.key == K_RETURN:
  96. if game_over:
  97. start = True
  98. game_over = False
  99. score = 0
  100. last_drop_time = time.time()
  101. last_press_time = time.time()
  102. game_area = [['.'] * BLOCK_WIDTH for _ in range(BLOCK_HEIGHT)]
  103. cur_block = blocks.get_block()
  104. next_block = blocks.get_block()
  105. cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y
  106. elif event.key == K_SPACE:
  107. if not game_over:
  108. pause = not pause
  109. elif event.key in (K_w, K_UP):
  110. if 0 <= cur_pos_x <= BLOCK_WIDTH - len(cur_block.template[0]):
  111. _next_block = blocks.get_next_block(cur_block)
  112. if _judge(cur_pos_x, cur_pos_y, _next_block):
  113. cur_block = _next_block
  114. if event.type == pygame.KEYDOWN:
  115. if event.key == pygame.K_LEFT:
  116. if not game_over and not pause:
  117. if time.time() - last_press_time > 0.1:
  118. last_press_time = time.time()
  119. if cur_pos_x > - cur_block.start_pos.X:
  120. if _judge(cur_pos_x - 1, cur_pos_y, cur_block):
  121. cur_pos_x -= 1
  122. if event.key == pygame.K_RIGHT:
  123. if not game_over and not pause:
  124. if time.time() - last_press_time > 0.1:
  125. last_press_time = time.time()
  126. # 不能移除右边框
  127. if cur_pos_x + cur_block.end_pos.X + 1 < BLOCK_WIDTH:
  128. if _judge(cur_pos_x + 1, cur_pos_y, cur_block):
  129. cur_pos_x += 1
  130. if event.key == pygame.K_DOWN:
  131. if not game_over and not pause:
  132. if time.time() - last_press_time > 0.1:
  133. last_press_time = time.time()
  134. if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
  135. _dock()
  136. else:
  137. last_drop_time = time.time()
  138. cur_pos_y += 1
  139. _draw_background(screen)
  140. _draw_game_area(screen, game_area)
  141. _draw_gridlines(screen)
  142. _draw_info(screen, font1, font_pos_x, font1_height, score)
  143. # 画显示信息中的下一个方块
  144. _draw_block(screen, next_block, font_pos_x, 30 + (font1_height + 6) * 5, 0, 0)
  145. if not game_over:
  146. cur_drop_time = time.time()
  147. if cur_drop_time - last_drop_time > speed:
  148. if not pause:
  149. if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
  150. _dock()
  151. else:
  152. last_drop_time = cur_drop_time
  153. cur_pos_y += 1
  154. else:
  155. if start:
  156. print_text(screen, font2,
  157. (SCREEN_WIDTH - gameover_size[0]) // 2, (SCREEN_HEIGHT - gameover_size[1]) // 2,
  158. 'GAME OVER', RED)
  159. # 画当前下落方块
  160. _draw_block(screen, cur_block, 0, 0, cur_pos_x, cur_pos_y)
  161. pygame.display.flip()
  162. # 画背景
  163. def _draw_background(screen):
  164. # 填充背景色
  165. screen.fill(BG_COLOR)
  166. # 画游戏区域分隔线
  167. pygame.draw.line(screen, BORDER_COLOR,
  168. (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
  169. (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)
  170. # 画网格线
  171. def _draw_gridlines(screen):
  172. # 画网格线 竖线
  173. for x in range(BLOCK_WIDTH):
  174. pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
  175. # 画网格线 横线
  176. for y in range(BLOCK_HEIGHT):
  177. pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)
  178. # 画已经落下的方块
  179. def _draw_game_area(screen, game_area):
  180. if game_area:
  181. for i, row in enumerate(game_area):
  182. for j, cell in enumerate(row):
  183. if cell != '.':
  184. pygame.draw.rect(screen, BLOCK_COLOR, (j * SIZE, i * SIZE, SIZE, SIZE), 0)
  185. # 画单个方块
  186. def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
  187. if block:
  188. for i in range(block.start_pos.Y, block.end_pos.Y + 1):
  189. for j in range(block.start_pos.X, block.end_pos.X + 1):
  190. if block.template[i][j] != '.':
  191. pygame.draw.rect(screen, BLOCK_COLOR,
  192. (offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)
  193. # 画得分等信息
  194. def _draw_info(screen, font, pos_x, font_height, score):
  195. print_text(screen, font, pos_x, 10, f'得分: ')
  196. print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
  197. print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
  198. print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
  199. print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个:')
  200. if __name__ == '__main__':
  201. main()
2、扫雷

地雷部分
一样的,单独保存py文件,mineblock.py

  1. import random
  2. from enum import Enum
  3. BLOCK_WIDTH = 30
  4. BLOCK_HEIGHT = 16
  5. SIZE = 20 # 块大小
  6. MINE_COUNT = 99 # 地雷数
  7. class BlockStatus(Enum):
  8. normal = 1 # 未点击
  9. opened = 2 # 已点击
  10. mine = 3 # 地雷
  11. flag = 4 # 标记为地雷
  12. ask = 5 # 标记为问号
  13. bomb = 6 # 踩中地雷
  14. hint = 7 # 被双击的周围
  15. double = 8 # 正被鼠标左右键双击
  16. class Mine:
  17. def __init__(self, x, y, value=0):
  18. self._x = x
  19. self._y = y
  20. self._value = 0
  21. self._around_mine_count = -1
  22. self._status = BlockStatus.normal
  23. self.set_value(value)
  24. def __repr__(self):
  25. return str(self._value)
  26. # return f'({self._x},{self._y})={self._value}, status={self.status}'
  27. def get_x(self):
  28. return self._x
  29. def set_x(self, x):
  30. self._x = x
  31. x = property(fget=get_x, fset=set_x)
  32. def get_y(self):
  33. return self._y
  34. def set_y(self, y):
  35. self._y = y
  36. y = property(fget=get_y, fset=set_y)
  37. def get_value(self):
  38. return self._value
  39. def set_value(self, value):
  40. if value:
  41. self._value = 1
  42. else:
  43. self._value = 0
  44. value = property(fget=get_value, fset=set_value, doc='0:非地雷 1:雷')
  45. def get_around_mine_count(self):
  46. return self._around_mine_count
  47. def set_around_mine_count(self, around_mine_count):
  48. self._around_mine_count = around_mine_count
  49. around_mine_count = property(fget=get_around_mine_count, fset=set_around_mine_count, doc='四周地雷数量')
  50. def get_status(self):
  51. return self._status
  52. def set_status(self, value):
  53. self._status = value
  54. status = property(fget=get_status, fset=set_status, doc='BlockStatus')
  55. class MineBlock:
  56. def __init__(self):
  57. self._block = [[Mine(i, j) for i in range(BLOCK_WIDTH)] for j in range(BLOCK_HEIGHT)]
  58. # 埋雷
  59. for i in random.sample(range(BLOCK_WIDTH * BLOCK_HEIGHT), MINE_COUNT):
  60. self._block[i // BLOCK_WIDTH][i % BLOCK_WIDTH].value = 1
  61. def get_block(self):
  62. return self._block
  63. block = property(fget=get_block)
  64. def getmine(self, x, y):
  65. return self._block[y][x]
  66. def open_mine(self, x, y):
  67. # 踩到雷了
  68. if self._block[y][x].value:
  69. self._block[y][x].status = BlockStatus.bomb
  70. return False
  71. # 先把状态改为 opened
  72. self._block[y][x].status = BlockStatus.opened
  73. around = _get_around(x, y)
  74. _sum = 0
  75. for i, j in around:
  76. if self._block[j][i].value:
  77. _sum += 1
  78. self._block[y][x].around_mine_count = _sum
  79. # 如果周围没有雷,那么将周围8个未中未点开的递归算一遍
  80. # 这就能实现一点出现一大片打开的效果了
  81. if _sum == 0:
  82. for i, j in around:
  83. if self._block[j][i].around_mine_count == -1:
  84. self.open_mine(i, j)
  85. return True
  86. def double_mouse_button_down(self, x, y):
  87. if self._block[y][x].around_mine_count == 0:
  88. return True
  89. self._block[y][x].status = BlockStatus.double
  90. around = _get_around(x, y)
  91. sumflag = 0 # 周围被标记的雷数量
  92. for i, j in _get_around(x, y):
  93. if self._block[j][i].status == BlockStatus.flag:
  94. sumflag += 1
  95. # 周边的雷已经全部被标记
  96. result = True
  97. if sumflag == self._block[y][x].around_mine_count:
  98. for i, j in around:
  99. if self._block[j][i].status == BlockStatus.normal:
  100. if not self.open_mine(i, j):
  101. result = False
  102. else:
  103. for i, j in around:
  104. if self._block[j][i].status == BlockStatus.normal:
  105. self._block[j][i].status = BlockStatus.hint
  106. return result
  107. def double_mouse_button_up(self, x, y):
  108. self._block[y][x].status = BlockStatus.opened
  109. for i, j in _get_around(x, y):
  110. if self._block[j][i].status == BlockStatus.hint:
  111. self._block[j][i].status = BlockStatus.normal
  112. def _get_around(x, y):
  113. """返回(x, y)周围的点的坐标"""
  114. # 这里注意,range 末尾是开区间,所以要加 1
  115. return [(i, j) for i in range(max(0, x - 1), min(BLOCK_WIDTH - 1, x + 1) + 1)
  116. for j in range(max(0, y - 1), min(BLOCK_HEIGHT - 1, y + 1) + 1) if i != x or j != y]

素材

左侧扫码获取

主代码

  1. import sys
  2. import time
  3. from enum import Enum
  4. import pygame
  5. from pygame.locals import *
  6. from mineblock import *
  7. # 游戏屏幕的宽
  8. SCREEN_WIDTH = BLOCK_WIDTH * SIZE
  9. # 游戏屏幕的高
  10. SCREEN_HEIGHT = (BLOCK_HEIGHT + 2) * SIZE
  11. class GameStatus(Enum):
  12. readied = 1,
  13. started = 2,
  14. over = 3,
  15. win = 4
  16. def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
  17. imgText = font.render(text, True, fcolor)
  18. screen.blit(imgText, (x, y))
  19. def main():
  20. pygame.init()
  21. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
  22. pygame.display.set_caption('扫雷')
  23. font1 = pygame.font.Font('resources/a.TTF', SIZE * 2) # 得分的字体
  24. fwidth, fheight = font1.size('999')
  25. red = (200, 40, 40)
  26. # 加载资源图片,因为资源文件大小不一,所以做了统一的缩放处理
  27. img0 = pygame.image.load('resources/0.bmp').convert()
  28. img0 = pygame.transform.smoothscale(img0, (SIZE, SIZE))
  29. img1 = pygame.image.load('resources/1.bmp').convert()
  30. img1 = pygame.transform.smoothscale(img1, (SIZE, SIZE))
  31. img2 = pygame.image.load('resources/2.bmp').convert()
  32. img2 = pygame.transform.smoothscale(img2, (SIZE, SIZE))
  33. img3 = pygame.image.load('resources/3.bmp').convert()
  34. img3 = pygame.transform.smoothscale(img3, (SIZE, SIZE))
  35. img4 = pygame.image.load('resources/4.bmp').convert()
  36. img4 = pygame.transform.smoothscale(img4, (SIZE, SIZE))
  37. img5 = pygame.image.load('resources/5.bmp').convert()
  38. img5 = pygame.transform.smoothscale(img5, (SIZE, SIZE))
  39. img6 = pygame.image.load('resources/6.bmp').convert()
  40. img6 = pygame.transform.smoothscale(img6, (SIZE, SIZE))
  41. img7 = pygame.image.load('resources/7.bmp').convert()
  42. img7 = pygame.transform.smoothscale(img7, (SIZE, SIZE))
  43. img8 = pygame.image.load('resources/8.bmp').convert()
  44. img8 = pygame.transform.smoothscale(img8, (SIZE, SIZE))
  45. img_blank = pygame.image.load('resources/blank.bmp').convert()
  46. img_blank = pygame.transform.smoothscale(img_blank, (SIZE, SIZE))
  47. img_flag = pygame.image.load('resources/flag.bmp').convert()
  48. img_flag = pygame.transform.smoothscale(img_flag, (SIZE, SIZE))
  49. img_ask = pygame.image.load('resources/ask.bmp').convert()
  50. img_ask = pygame.transform.smoothscale(img_ask, (SIZE, SIZE))
  51. img_mine = pygame.image.load('resources/mine.bmp').convert()
  52. img_mine = pygame.transform.smoothscale(img_mine, (SIZE, SIZE))
  53. img_blood = pygame.image.load('resources/blood.bmp').convert()
  54. img_blood = pygame.transform.smoothscale(img_blood, (SIZE, SIZE))
  55. img_error = pygame.image.load('resources/error.bmp').convert()
  56. img_error = pygame.transform.smoothscale(img_error, (SIZE, SIZE))
  57. face_size = int(SIZE * 1.25)
  58. img_face_fail = pygame.image.load('resources/face_fail.bmp').convert()
  59. img_face_fail = pygame.transform.smoothscale(img_face_fail, (face_size, face_size))
  60. img_face_normal = pygame.image.load('resources/face_normal.bmp').convert()
  61. img_face_normal = pygame.transform.smoothscale(img_face_normal, (face_size, face_size))
  62. img_face_success = pygame.image.load('resources/face_success.bmp').convert()
  63. img_face_success = pygame.transform.smoothscale(img_face_success, (face_size, face_size))
  64. face_pos_x = (SCREEN_WIDTH - face_size) // 2
  65. face_pos_y = (SIZE * 2 - face_size) // 2
  66. img_dict = {
  67. 0: img0,
  68. 1: img1,
  69. 2: img2,
  70. 3: img3,
  71. 4: img4,
  72. 5: img5,
  73. 6: img6,
  74. 7: img7,
  75. 8: img8
  76. }
  77. bgcolor = (225, 225, 225) # 背景色
  78. block = MineBlock()
  79. game_status = GameStatus.readied
  80. start_time = None # 开始时间
  81. elapsed_time = 0 # 耗时
  82. while True:
  83. # 填充背景色
  84. screen.fill(bgcolor)
  85. for event in pygame.event.get():
  86. if event.type == QUIT:
  87. sys.exit()
  88. elif event.type == MOUSEBUTTONDOWN:
  89. mouse_x, mouse_y = event.pos
  90. x = mouse_x // SIZE
  91. y = mouse_y // SIZE - 2
  92. b1, b2, b3 = pygame.mouse.get_pressed()
  93. if game_status == GameStatus.started:
  94. # 鼠标左右键同时按下,如果已经标记了所有雷,则打开周围一圈
  95. # 如果还未标记完所有雷,则有一个周围一圈被同时按下的效果
  96. if b1 and b3:
  97. mine = block.getmine(x, y)
  98. if mine.status == BlockStatus.opened:
  99. if not block.double_mouse_button_down(x, y):
  100. game_status = GameStatus.over
  101. elif event.type == MOUSEBUTTONUP:
  102. if y < 0:
  103. if face_pos_x <= mouse_x <= face_pos_x + face_size \
  104. and face_pos_y <= mouse_y <= face_pos_y + face_size:
  105. game_status = GameStatus.readied
  106. block = MineBlock()
  107. start_time = time.time()
  108. elapsed_time = 0
  109. continue
  110. if game_status == GameStatus.readied:
  111. game_status = GameStatus.started
  112. start_time = time.time()
  113. elapsed_time = 0
  114. if game_status == GameStatus.started:
  115. mine = block.getmine(x, y)
  116. if b1 and not b3: # 按鼠标左键
  117. if mine.status == BlockStatus.normal:
  118. if not block.open_mine(x, y):
  119. game_status = GameStatus.over
  120. elif not b1 and b3: # 按鼠标右键
  121. if mine.status == BlockStatus.normal:
  122. mine.status = BlockStatus.flag
  123. elif mine.status == BlockStatus.flag:
  124. mine.status = BlockStatus.ask
  125. elif mine.status == BlockStatus.ask:
  126. mine.status = BlockStatus.normal
  127. elif b1 and b3:
  128. if mine.status == BlockStatus.double:
  129. block.double_mouse_button_up(x, y)
  130. flag_count = 0
  131. opened_count = 0
  132. for row in block.block:
  133. for mine in row:
  134. pos = (mine.x * SIZE, (mine.y + 2) * SIZE)
  135. if mine.status == BlockStatus.opened:
  136. screen.blit(img_dict[mine.around_mine_count], pos)
  137. opened_count += 1
  138. elif mine.status == BlockStatus.double:
  139. screen.blit(img_dict[mine.around_mine_count], pos)
  140. elif mine.status == BlockStatus.bomb:
  141. screen.blit(img_blood, pos)
  142. elif mine.status == BlockStatus.flag:
  143. screen.blit(img_flag, pos)
  144. flag_count += 1
  145. elif mine.status == BlockStatus.ask:
  146. screen.blit(img_ask, pos)
  147. elif mine.status == BlockStatus.hint:
  148. screen.blit(img0, pos)
  149. elif game_status == GameStatus.over and mine.value:
  150. screen.blit(img_mine, pos)
  151. elif mine.value == 0 and mine.status == BlockStatus.flag:
  152. screen.blit(img_error, pos)
  153. elif mine.status == BlockStatus.normal:
  154. screen.blit(img_blank, pos)
  155. print_text(screen, font1, 30, (SIZE * 2 - fheight) // 2 - 2, '%02d' % (MINE_COUNT - flag_count), red)
  156. if game_status == GameStatus.started:
  157. elapsed_time = int(time.time() - start_time)
  158. print_text(screen, font1, SCREEN_WIDTH - fwidth - 30, (SIZE * 2 - fheight) // 2 - 2, '%03d' % elapsed_time, red)
  159. if flag_count + opened_count == BLOCK_WIDTH * BLOCK_HEIGHT:
  160. game_status = GameStatus.win
  161. if game_status == GameStatus.over:
  162. screen.blit(img_face_fail, (face_pos_x, face_pos_y))
  163. elif game_status == GameStatus.win:
  164. screen.blit(img_face_success, (face_pos_x, face_pos_y))
  165. else:
  166. screen.blit(img_face_normal, (face_pos_x, face_pos_y))
  167. pygame.display.update()
  168. if __name__ == '__main__':
  169. main()
3、五子棋

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

  1. import sys
  2. import random
  3. import pygame
  4. from pygame.locals import *
  5. import pygame.gfxdraw
  6. from collections import namedtuple
  7. Chessman = namedtuple('Chessman', 'Name Value Color')
  8. Point = namedtuple('Point', 'X Y')
  9. BLACK_CHESSMAN = Chessman('黑子', 1, (45, 45, 45))
  10. WHITE_CHESSMAN = Chessman('白子', 2, (219, 219, 219))
  11. offset = [(1, 0), (0, 1), (1, 1), (1, -1)]
  12. class Checkerboard:
  13. def __init__(self, line_points):
  14. self._line_points = line_points
  15. self._checkerboard = [[0] * line_points for _ in range(line_points)]
  16. def _get_checkerboard(self):
  17. return self._checkerboard
  18. checkerboard = property(_get_checkerboard)
  19. # 判断是否可落子
  20. def can_drop(self, point):
  21. return self._checkerboard[point.Y][point.X] == 0
  22. def drop(self, chessman, point):
  23. """ 落子 :param chessman: :param point:落子位置 :return:若该子落下之后即可获胜,则返回获胜方,否则返回 None """
  24. print(f'{chessman.Name} ({point.X}, {point.Y})')
  25. self._checkerboard[point.Y][point.X] = chessman.Value
  26. if self._win(point):
  27. print(f'{chessman.Name}获胜')
  28. return chessman
  29. # 判断是否赢了
  30. def _win(self, point):
  31. cur_value = self._checkerboard[point.Y][point.X]
  32. for os in offset:
  33. if self._get_count_on_direction(point, cur_value, os[0], os[1]):
  34. return True
  35. def _get_count_on_direction(self, point, value, x_offset, y_offset):
  36. count = 1
  37. for step in range(1, 5):
  38. x = point.X + step * x_offset
  39. y = point.Y + step * y_offset
  40. if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
  41. count += 1
  42. else:
  43. break
  44. for step in range(1, 5):
  45. x = point.X - step * x_offset
  46. y = point.Y - step * y_offset
  47. if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
  48. count += 1
  49. else:
  50. break
  51. return count >= 5
  52. SIZE = 30 # 棋盘每个点时间的间隔
  53. Line_Points = 19 # 棋盘每行/每列点数
  54. Outer_Width = 20 # 棋盘外宽度
  55. Border_Width = 4 # 边框宽度
  56. Inside_Width = 4 # 边框跟实际的棋盘之间的间隔
  57. Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width # 边框线的长度
  58. Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width # 网格线起点(左上角)坐标
  59. SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2 # 游戏屏幕的高
  60. SCREEN_WIDTH = SCREEN_HEIGHT + 200 # 游戏屏幕的宽
  61. Stone_Radius = SIZE // 2 - 3 # 棋子半径
  62. Stone_Radius2 = SIZE // 2 + 3
  63. Checkerboard_Color = (0xE3, 0x92, 0x65) # 棋盘颜色
  64. BLACK_COLOR = (0, 0, 0)
  65. WHITE_COLOR = (255, 255, 255)
  66. RED_COLOR = (200, 30, 30)
  67. BLUE_COLOR = (30, 30, 200)
  68. RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10
  69. def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
  70. imgText = font.render(text, True, fcolor)
  71. screen.blit(imgText, (x, y))
  72. def main():
  73. pygame.init()
  74. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
  75. pygame.display.set_caption('五子棋')
  76. font1 = pygame.font.SysFont('SimHei', 32)
  77. font2 = pygame.font.SysFont('SimHei', 72)
  78. fwidth, fheight = font2.size('黑方获胜')
  79. checkerboard = Checkerboard(Line_Points)
  80. cur_runner = BLACK_CHESSMAN
  81. winner = None
  82. computer = AI(Line_Points, WHITE_CHESSMAN)
  83. black_win_count = 0
  84. white_win_count = 0
  85. while True:
  86. for event in pygame.event.get():
  87. if event.type == QUIT:
  88. sys.exit()
  89. elif event.type == KEYDOWN:
  90. if event.key == K_RETURN:
  91. if winner is not None:
  92. winner = None
  93. cur_runner = BLACK_CHESSMAN
  94. checkerboard = Checkerboard(Line_Points)
  95. computer = AI(Line_Points, WHITE_CHESSMAN)
  96. elif event.type == MOUSEBUTTONDOWN:
  97. if winner is None:
  98. pressed_array = pygame.mouse.get_pressed()
  99. if pressed_array[0]:
  100. mouse_pos = pygame.mouse.get_pos()
  101. click_point = _get_clickpoint(mouse_pos)
  102. if click_point is not None:
  103. if checkerboard.can_drop(click_point):
  104. winner = checkerboard.drop(cur_runner, click_point)
  105. if winner is None:
  106. cur_runner = _get_next(cur_runner)
  107. computer.get_opponent_drop(click_point)
  108. AI_point = computer.AI_drop()
  109. winner = checkerboard.drop(cur_runner, AI_point)
  110. if winner is not None:
  111. white_win_count += 1
  112. cur_runner = _get_next(cur_runner)
  113. else:
  114. black_win_count += 1
  115. else:
  116. print('超出棋盘区域')
  117. # 画棋盘
  118. _draw_checkerboard(screen)
  119. # 画棋盘上已有的棋子
  120. for i, row in enumerate(checkerboard.checkerboard):
  121. for j, cell in enumerate(row):
  122. if cell == BLACK_CHESSMAN.Value:
  123. _draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color)
  124. elif cell == WHITE_CHESSMAN.Value:
  125. _draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color)
  126. _draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count)
  127. if winner:
  128. print_text(screen, font2, (SCREEN_WIDTH - fwidth)//2, (SCREEN_HEIGHT - fheight)//2, winner.Name + '获胜', RED_COLOR)
  129. pygame.display.flip()
  130. def _get_next(cur_runner):
  131. if cur_runner == BLACK_CHESSMAN:
  132. return WHITE_CHESSMAN
  133. else:
  134. return BLACK_CHESSMAN
  135. # 画棋盘
  136. def _draw_checkerboard(screen):
  137. # 填充棋盘背景色
  138. screen.fill(Checkerboard_Color)
  139. # 画棋盘网格线外的边框
  140. pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)
  141. # 画网格线
  142. for i in range(Line_Points):
  143. pygame.draw.line(screen, BLACK_COLOR,
  144. (Start_Y, Start_Y + SIZE * i),
  145. (Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),
  146. 1)
  147. for j in range(Line_Points):
  148. pygame.draw.line(screen, BLACK_COLOR,
  149. (Start_X + SIZE * j, Start_X),
  150. (Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),
  151. 1)
  152. # 画星位和天元
  153. for i in (3, 9, 15):
  154. for j in (3, 9, 15):
  155. if i == j == 9:
  156. radius = 5
  157. else:
  158. radius = 3
  159. # pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius)
  160. pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
  161. pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
  162. # 画棋子
  163. def _draw_chessman(screen, point, stone_color):
  164. # pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius)
  165. pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
  166. pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
  167. # 画左侧信息显示
  168. def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count):
  169. _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), BLACK_CHESSMAN.Color)
  170. _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), WHITE_CHESSMAN.Color)
  171. print_text(screen, font, RIGHT_INFO_POS_X, Start_X + 3, '玩家', BLUE_COLOR)
  172. print_text(screen, font, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3 + 3, '电脑', BLUE_COLOR)
  173. print_text(screen, font, SCREEN_HEIGHT, SCREEN_HEIGHT - Stone_Radius2 * 8, '战况:', BLUE_COLOR)
  174. _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - int(Stone_Radius2 * 4.5)), BLACK_CHESSMAN.Color)
  175. _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - Stone_Radius2 * 2), WHITE_CHESSMAN.Color)
  176. print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - int(Stone_Radius2 * 5.5) + 3, f'{black_win_count} 胜', BLUE_COLOR)
  177. print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - Stone_Radius2 * 3 + 3, f'{white_win_count} 胜', BLUE_COLOR)
  178. def _draw_chessman_pos(screen, pos, stone_color):
  179. pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color)
  180. pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color)
  181. # 根据鼠标点击位置,返回游戏区坐标
  182. def _get_clickpoint(click_pos):
  183. pos_x = click_pos[0] - Start_X
  184. pos_y = click_pos[1] - Start_Y
  185. if pos_x < -Inside_Width or pos_y < -Inside_Width:
  186. return None
  187. x = pos_x // SIZE
  188. y = pos_y // SIZE
  189. if pos_x % SIZE > Stone_Radius:
  190. x += 1
  191. if pos_y % SIZE > Stone_Radius:
  192. y += 1
  193. if x >= Line_Points or y >= Line_Points:
  194. return None
  195. return Point(x, y)
  196. class AI:
  197. def __init__(self, line_points, chessman):
  198. self._line_points = line_points
  199. self._my = chessman
  200. self._opponent = BLACK_CHESSMAN if chessman == WHITE_CHESSMAN else WHITE_CHESSMAN
  201. self._checkerboard = [[0] * line_points for _ in range(line_points)]
  202. def get_opponent_drop(self, point):
  203. self._checkerboard[point.Y][point.X] = self._opponent.Value
  204. def AI_drop(self):
  205. point = None
  206. score = 0
  207. for i in range(self._line_points):
  208. for j in range(self._line_points):
  209. if self._checkerboard[j][i] == 0:
  210. _score = self._get_point_score(Point(i, j))
  211. if _score > score:
  212. score = _score
  213. point = Point(i, j)
  214. elif _score == score and _score > 0:
  215. r = random.randint(0, 100)
  216. if r % 2 == 0:
  217. point = Point(i, j)
  218. self._checkerboard[point.Y][point.X] = self._my.Value
  219. return point
  220. def _get_point_score(self, point):
  221. score = 0
  222. for os in offset:
  223. score += self._get_direction_score(point, os[0], os[1])
  224. return score
  225. def _get_direction_score(self, point, x_offset, y_offset):
  226. count = 0 # 落子处我方连续子数
  227. _count = 0 # 落子处对方连续子数
  228. space = None # 我方连续子中有无空格
  229. _space = None # 对方连续子中有无空格
  230. both = 0 # 我方连续子两端有无阻挡
  231. _both = 0 # 对方连续子两端有无阻挡
  232. # 如果是 1 表示是边上是我方子,2 表示敌方子
  233. flag = self._get_stone_color(point, x_offset, y_offset, True)
  234. if flag != 0:
  235. for step in range(1, 6):
  236. x = point.X + step * x_offset
  237. y = point.Y + step * y_offset
  238. if 0 <= x < self._line_points and 0 <= y < self._line_points:
  239. if flag == 1:
  240. if self._checkerboard[y][x] == self._my.Value:
  241. count += 1
  242. if space is False:
  243. space = True
  244. elif self._checkerboard[y][x] == self._opponent.Value:
  245. _both += 1
  246. break
  247. else:
  248. if space is None:
  249. space = False
  250. else:
  251. break # 遇到第二个空格退出
  252. elif flag == 2:
  253. if self._checkerboard[y][x] == self._my.Value:
  254. _both += 1
  255. break
  256. elif self._checkerboard[y][x] == self._opponent.Value:
  257. _count += 1
  258. if _space is False:
  259. _space = True
  260. else:
  261. if _space is None:
  262. _space = False
  263. else:
  264. break
  265. else:
  266. # 遇到边也就是阻挡
  267. if flag == 1:
  268. both += 1
  269. elif flag == 2:
  270. _both += 1
  271. if space is False:
  272. space = None
  273. if _space is False:
  274. _space = None
  275. _flag = self._get_stone_color(point, -x_offset, -y_offset, True)
  276. if _flag != 0:
  277. for step in range(1, 6):
  278. x = point.X - step * x_offset
  279. y = point.Y - step * y_offset
  280. if 0 <= x < self._line_points and 0 <= y < self._line_points:
  281. if _flag == 1:
  282. if self._checkerboard[y][x] == self._my.Value:
  283. count += 1
  284. if space is False:
  285. space = True
  286. elif self._checkerboard[y][x] == self._opponent.Value:
  287. _both += 1
  288. break
  289. else:
  290. if space is None:
  291. space = False
  292. else:
  293. break # 遇到第二个空格退出
  294. elif _flag == 2:
  295. if self._checkerboard[y][x] == self._my.Value:
  296. _both += 1
  297. break
  298. elif self._checkerboard[y][x] == self._opponent.Value:
  299. _count += 1
  300. if _space is False:
  301. _space = True
  302. else:
  303. if _space is None:
  304. _space = False
  305. else:
  306. break
  307. else:
  308. # 遇到边也就是阻挡
  309. if _flag == 1:
  310. both += 1
  311. elif _flag == 2:
  312. _both += 1
  313. score = 0
  314. if count == 4:
  315. score = 10000
  316. elif _count == 4:
  317. score = 9000
  318. elif count == 3:
  319. if both == 0:
  320. score = 1000
  321. elif both == 1:
  322. score = 100
  323. else:
  324. score = 0
  325. elif _count == 3:
  326. if _both == 0:
  327. score = 900
  328. elif _both == 1:
  329. score = 90
  330. else:
  331. score = 0
  332. elif count == 2:
  333. if both == 0:
  334. score = 100
  335. elif both == 1:
  336. score = 10
  337. else:
  338. score = 0
  339. elif _count == 2:
  340. if _both == 0:
  341. score = 90
  342. elif _both == 1:
  343. score = 9
  344. else:
  345. score = 0
  346. elif count == 1:
  347. score = 10
  348. elif _count == 1:
  349. score = 9
  350. else:
  351. score = 0
  352. if space or _space:
  353. score /= 2
  354. return score
  355. # 判断指定位置处在指定方向上是我方子、对方子、空
  356. def _get_stone_color(self, point, x_offset, y_offset, next):
  357. x = point.X + x_offset
  358. y = point.Y + y_offset
  359. if 0 <= x < self._line_points and 0 <= y < self._line_points:
  360. if self._checkerboard[y][x] == self._my.Value:
  361. return 1
  362. elif self._checkerboard[y][x] == self._opponent.Value:
  363. return 2
  364. else:
  365. if next:
  366. return self._get_stone_color(Point(x, y), x_offset, y_offset, False)
  367. else:
  368. return 0
  369. else:
  370. return 0
  371. if __name__ == '__main__':
  372. main()
4、贪吃蛇
  1. import random
  2. import sys
  3. import time
  4. import pygame
  5. from pygame.locals import *
  6. from collections import deque
  7. SCREEN_WIDTH = 600 # 屏幕宽度
  8. SCREEN_HEIGHT = 480 # 屏幕高度
  9. SIZE = 20 # 小方格大小
  10. LINE_WIDTH = 1 # 网格线宽度
  11. # 游戏区域的坐标范围
  12. SCOPE_X = (0, SCREEN_WIDTH // SIZE - 1)
  13. SCOPE_Y = (2, SCREEN_HEIGHT // SIZE - 1)
  14. # 食物的分值及颜色
  15. FOOD_STYLE_LIST = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]
  16. LIGHT = (100, 100, 100)
  17. DARK = (200, 200, 200) # 蛇的颜色
  18. BLACK = (0, 0, 0) # 网格线颜色
  19. RED = (200, 30, 30) # 红色,GAME OVER 的字体颜色
  20. BGCOLOR = (40, 40, 60) # 背景色
  21. def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
  22. imgText = font.render(text, True, fcolor)
  23. screen.blit(imgText, (x, y))
  24. # 初始化蛇
  25. def init_snake():
  26. snake = deque()
  27. snake.append((2, SCOPE_Y[0]))
  28. snake.append((1, SCOPE_Y[0]))
  29. snake.append((0, SCOPE_Y[0]))
  30. return snake
  31. def create_food(snake):
  32. food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
  33. food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
  34. while (food_x, food_y) in snake:
  35. # 如果食物出现在蛇身上,则重来
  36. food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
  37. food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
  38. return food_x, food_y
  39. def get_food_style():
  40. return FOOD_STYLE_LIST[random.randint(0, 2)]
  41. def main():
  42. pygame.init()
  43. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
  44. pygame.display.set_caption('贪吃蛇')
  45. font1 = pygame.font.SysFont('SimHei', 24) # 得分的字体
  46. font2 = pygame.font.Font(None, 72) # GAME OVER 的字体
  47. fwidth, fheight = font2.size('GAME OVER')
  48. # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
  49. # b 变量就是用于防止这种情况的发生
  50. b = True
  51. # 蛇
  52. snake = init_snake()
  53. # 食物
  54. food = create_food(snake)
  55. food_style = get_food_style()
  56. # 方向
  57. pos = (1, 0)
  58. game_over = True
  59. start = False # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
  60. score = 0 # 得分
  61. orispeed = 0.5 # 原始速度
  62. speed = orispeed
  63. last_move_time = None
  64. pause = False # 暂停
  65. while True:
  66. for event in pygame.event.get():
  67. if event.type == QUIT:
  68. sys.exit()
  69. elif event.type == KEYDOWN:
  70. if event.key == K_RETURN:
  71. if game_over:
  72. start = True
  73. game_over = False
  74. b = True
  75. snake = init_snake()
  76. food = create_food(snake)
  77. food_style = get_food_style()
  78. pos = (1, 0)
  79. # 得分
  80. score = 0
  81. last_move_time = time.time()
  82. elif event.key == K_SPACE:
  83. if not game_over:
  84. pause = not pause
  85. elif event.key in (K_w, K_UP):
  86. # 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER
  87. if b and not pos[1]:
  88. pos = (0, -1)
  89. b = False
  90. elif event.key in (K_s, K_DOWN):
  91. if b and not pos[1]:
  92. pos = (0, 1)
  93. b = False
  94. elif event.key in (K_a, K_LEFT):
  95. if b and not pos[0]:
  96. pos = (-1, 0)
  97. b = False
  98. elif event.key in (K_d, K_RIGHT):
  99. if b and not pos[0]:
  100. pos = (1, 0)
  101. b = False
  102. # 填充背景色
  103. screen.fill(BGCOLOR)
  104. # 画网格线 竖线
  105. for x in range(SIZE, SCREEN_WIDTH, SIZE):
  106. pygame.draw.line(screen, BLACK, (x, SCOPE_Y[0] * SIZE), (x, SCREEN_HEIGHT), LINE_WIDTH)
  107. # 画网格线 横线
  108. for y in range(SCOPE_Y[0] * SIZE, SCREEN_HEIGHT, SIZE):
  109. pygame.draw.line(screen, BLACK, (0, y), (SCREEN_WIDTH, y), LINE_WIDTH)
  110. if not game_over:
  111. curTime = time.time()
  112. if curTime - last_move_time > speed:
  113. if not pause:
  114. b = True
  115. last_move_time = curTime
  116. next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1])
  117. if next_s == food:
  118. # 吃到了食物
  119. snake.appendleft(next_s)
  120. score += food_style[0]
  121. speed = orispeed - 0.03 * (score // 100)
  122. food = create_food(snake)
  123. food_style = get_food_style()
  124. else:
  125. if SCOPE_X[0] <= next_s[0] <= SCOPE_X[1] and SCOPE_Y[0] <= next_s[1] <= SCOPE_Y[1] \
  126. and next_s not in snake:
  127. snake.appendleft(next_s)
  128. snake.pop()
  129. else:
  130. game_over = True
  131. # 画食物
  132. if not game_over:
  133. # 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了
  134. pygame.draw.rect(screen, food_style[1], (food[0] * SIZE, food[1] * SIZE, SIZE, SIZE), 0)
  135. # 画蛇
  136. for s in snake:
  137. pygame.draw.rect(screen, DARK, (s[0] * SIZE + LINE_WIDTH, s[1] * SIZE + LINE_WIDTH,
  138. SIZE - LINE_WIDTH * 2, SIZE - LINE_WIDTH * 2), 0)
  139. print_text(screen, font1, 30, 7, f'速度: {score//100}')
  140. print_text(screen, font1, 450, 7, f'得分: {score}')
  141. if game_over:
  142. if start:
  143. print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER', RED)
  144. pygame.display.update()
  145. if __name__ == '__main__':
  146. main()

相关文章