当前位置:   article > 正文

Python实现的一些小游戏_python自制小游戏

python自制小游戏

以下内容为使用Python开发的一些小游戏,仅供参考,谢谢!

猜单词游戏

  1. import random
  2. # 单词列表
  3. words = ['apple', 'banana', 'cherry', 'orange', 'pear', 'watermelon']
  4. # 随机选一个单词
  5. word = random.choice(words)
  6. # 将单词转换为小写字母
  7. word = word.lower()
  8. # 猜测次数限制
  9. max_guesses = 10
  10. # 玩家猜测的次数
  11. guesses = 0
  12. # 玩家猜测的字母集合
  13. letters_guessed = set()
  14. # 游戏是否结束的标志
  15. game_over = False
  16. print('猜单词游戏!')
  17. print('我想了一个单词,这个单词有', len(word), '个字母。')
  18. while not game_over:
  19. # 显示玩家已经猜过的字母
  20. print('你已经猜过的字母:', ' '.join(sorted(letters_guessed)))
  21. # 显示单词中已经猜中的字母
  22. display_word = ''
  23. for letter in word:
  24. if letter in letters_guessed:
  25. display_word += letter
  26. else:
  27. display_word += '_'
  28. print(display_word)
  29. # 等待玩家猜测
  30. guess = input('你猜这个单词是什么?')
  31. # 判断玩家猜测的是字母还是单词
  32. if len(guess) == 1:
  33. # 玩家猜测的是字母
  34. letter = guess.lower()
  35. if letter in letters_guessed:
  36. print('你已经猜过这个字母了,请猜一个新的字母。')
  37. else:
  38. letters_guessed.add(letter)
  39. if letter in word:
  40. print('恭喜你,你猜对了一个字母!')
  41. else:
  42. print('很遗憾,这个字母不在单词中。')
  43. guesses += 1
  44. else:
  45. # 玩家猜测的是单词
  46. if guess.lower() == word:
  47. print('恭喜你,你猜对了整个单词!')
  48. game_over = True
  49. else:
  50. print('很遗憾,你猜错了整个单词。')
  51. guesses += 1
  52. # 判断游戏是否结束
  53. if guesses >= max_guesses:
  54. print('很遗憾,你已经猜测了', max_guesses, '次,游戏结束。')
  55. game_over = True
  56. elif set(word) == letters_guessed:
  57. print('恭喜你,你猜对了整个单词!')
  58. game_over = True

猜数字游戏

  1. import random
  2. number = random.randint(1, 100)
  3. guesses = 0
  4. print('猜数字游戏!')
  5. print('我想了一个 1 到 100 之间的整数。')
  6. while True:
  7. guess = int(input('你猜这个数字是多少?'))
  8. guesses += 1
  9. if guess < number:
  10. print('猜小了!')
  11. elif guess > number:
  12. print('猜大了!')
  13. else:
  14. print('恭喜你猜对了!')
  15. break
  16. print('你总共猜了', guesses, '次。')

黑白棋游戏

  1. # 定义棋盘的大小
  2. BOARD_SIZE = 8
  3. # 定义棋子的颜色
  4. EMPTY = 0
  5. BLACK = 1
  6. WHITE = 2
  7. # 初始化棋盘
  8. board = [[EMPTY for x in range(BOARD_SIZE)] for y in range(BOARD_SIZE)]
  9. board[3][3] = WHITE
  10. board[4][4] = WHITE
  11. board[3][4] = BLACK
  12. board[4][3] = BLACK
  13. # 定义可以翻转对手棋子的方向
  14. DIRECTIONS = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
  15. # 定义玩家的颜色
  16. player_color = BLACK
  17. # 定义游戏是否结束的标志
  18. game_over = False
  19. # 统计棋盘上各种颜色的棋子数
  20. def count_pieces(board):
  21. black_count = 0
  22. white_count = 0
  23. for row in board:
  24. for cell in row:
  25. if cell == BLACK:
  26. black_count += 1
  27. elif cell == WHITE:
  28. white_count += 1
  29. return (black_count, white_count)
  30. # 判断落子是否合法
  31. def is_legal_move(board, row, col, color):
  32. if board[row][col] != EMPTY:
  33. return False
  34. for direction in DIRECTIONS:
  35. r, c = row + direction[0], col + direction[1]
  36. if (r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] == EMPTY or board[r][c] == color):
  37. continue
  38. r += direction[0]
  39. c += direction[1]
  40. while (r >= 0 and r < BOARD_SIZE and c >= 0 and c < BOARD_SIZE and board[r][c] != EMPTY):
  41. if (board[r][c] == color):
  42. return True
  43. r += direction[0]
  44. c += direction[1]
  45. return False
  46. # 翻转对手的棋子
  47. def flip_pieces(board, row, col, color):
  48. for direction in DIRECTIONS:
  49. r, c = row + direction[0], col + direction[1]
  50. if (r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] == EMPTY or board[r][c] == color):
  51. continue
  52. r += direction[0]
  53. c += direction[1]
  54. while (r >= 0 and r < BOARD_SIZE and c >= 0 and c < BOARD_SIZE and board[r][c] != EMPTY):
  55. if (board[r][c] == color):
  56. r2, c2 = row + direction[0], col + direction[1]
  57. while (r2 != r or c2 != c):
  58. board[r2][c2] = color
  59. r2 += direction[0]
  60. c2 += direction[1]
  61. break
  62. r += direction[0]
  63. c += direction[1]
  64. # 输出棋盘
  65. def print_board(board):
  66. print(' ', end='')
  67. for i in range(BOARD_SIZE):
  68. print(chr(ord('a') + i), end=' ')
  69. print()
  70. print(' +' + '-' * (2 * BOARD_SIZE - 1) + '+')
  71. for i in range(BOARD_SIZE):
  72. print(str(i + 1) + ' |', end='')
  73. for j in range(BOARD_SIZE):
  74. if board[i][j] == EMPTY:
  75. print(' ', end='')
  76. elif board[i][j] == BLACK:
  77. print('●', end='')
  78. elif board[i][j] == WHITE:
  79. print('○', end='')
  80. if j < BOARD_SIZE - 1:
  81. print(' ', end='')
  82. print('| ' + str(i + 1))
  83. print(' +-' + '-' * (2 * BOARD_SIZE - 1) + '-+')
  84. print(' ', end='')
  85. for i in range(BOARD_SIZE):
  86. print(chr(ord('a') + i), end=' ')
  87. print()
  88. # 主循环
  89. while not game_over:
  90. # 输出当前棋盘和玩家的颜色
  91. print_board(board)
  92. if player_color == BLACK:
  93. print("黑方落子")
  94. else:
  95. print("白方落子")
  96. # 等待玩家落子
  97. while True:
  98. move = input("请输入落子位置(例如d3)或输入pass跳过本回合:")
  99. if move.lower() == "pass":
  100. break
  101. col = ord(move[0]) - ord('a')
  102. row = int(move[1:]) - 1
  103. if (col < 0 or col >= BOARD_SIZE or row < 0 or row >= BOARD_SIZE or not is_legal_move(board, row, col, player_color)):
  104. print("无效落子,请重新输入。")
  105. else:
  106. board[row][col] = player_color
  107. flip_pieces(board, row, col, player_color)
  108. break
  109. # 判断游戏是否结束
  110. black_count, white_count = count_pieces(board)
  111. if (black_count == 0 or white_count == 0 or black_count + white_count == BOARD_SIZE * BOARD_SIZE):
  112. game_over = True
  113. # 切换玩家的颜色
  114. if player_color == BLACK:
  115. player_color = WHITE
  116. else:
  117. player_color = BLACK
  118. # 输出最终的棋盘和胜者
  119. print_board(board)
  120. black_count, white_count = count_pieces(board)
  121. if black_count == white_count:
  122. print("平局")
  123. elif black_count > white_count:
  124. print("黑方胜利")
  125. else:
  126. print("白方胜利")

在上面的代码中,我们首先定义了棋盘的大小和棋子的颜色,然后初始化了棋盘和玩家的颜色。游戏的主循环中,我们输出当前棋盘和玩家的颜色,等待玩家落子。如果玩家输入的落子位置合法,我们就将落子放在棋盘上,并翻转对手的一些棋子。然后,我们判断游戏是否结束。如果棋盘上只剩下一种颜色的棋子,或者棋盘上的格子都被占满了,游戏就结束。最后,我们输出最终的棋盘和胜者。

2048

  1. import random
  2. # 定义方格的大小
  3. SIZE = 4
  4. # 初始化方格
  5. board = [[0 for x in range(SIZE)] for y in range(SIZE)]
  6. # 随机生成两个数字块
  7. def init_board():
  8. for i in range(2):
  9. row = random.randint(0, SIZE - 1)
  10. col = random.randint(0, SIZE - 1)
  11. while board[row][col] != 0:
  12. row = random.randint(0, SIZE - 1)
  13. col = random.randint(0, SIZE - 1)
  14. board[row][col] = 2
  15. # 输出方格
  16. def print_board():
  17. for row in board:
  18. for cell in row:
  19. print(cell, end='\t')
  20. print()
  21. print()
  22. # 判断方格是否已满
  23. def is_full():
  24. for row in board:
  25. for cell in row:
  26. if cell == 0:
  27. return False
  28. return True
  29. # 在方格中随机生成一个数字块
  30. def spawn_block():
  31. while True:
  32. row = random.randint(0, SIZE - 1)
  33. col = random.randint(0, SIZE - 1)
  34. if board[row][col] == 0:
  35. board[row][col] = 2 if random.random() < 0.9 else 4
  36. break
  37. # 判断方格是否可以移动
  38. def can_move():
  39. for row in range(SIZE):
  40. for col in range(SIZE):
  41. if board[row][col] == 0:
  42. return True
  43. if col > 0 and board[row][col] == board[row][col - 1]:
  44. return True
  45. if col < SIZE - 1 and board[row][col] == board[row][col + 1]:
  46. return True
  47. if row > 0 and board[row][col] == board[row - 1][col]:
  48. return True
  49. if row < SIZE - 1 and board[row][col] == board[row + 1][col]:
  50. return True
  51. return False
  52. # 合并相同的数字块
  53. def merge_blocks():
  54. for row in range(SIZE):
  55. for col in range(SIZE - 1):
  56. if board[row][col] != 0 and board[row][col] == board[row][col + 1]:
  57. board[row][col] *= 2
  58. board[row][col + 1] = 0
  59. for row in range(SIZE):
  60. for col in range(SIZE - 1, 0, -1):
  61. if board[row][col] == 0:
  62. for i in range(col - 1, -1, -1):
  63. if board[row][i] != 0:
  64. board[row][col], board[row][i] = board[row][i], board[row][col]
  65. break
  66. # 处理玩家移动
  67. def handle_move(move):
  68. if move == 'w':
  69. for col in range(SIZE):
  70. for row in range(SIZE - 1):
  71. if board[row][col] == 0:
  72. for i in range(row + 1, SIZE):
  73. if board[i][col] != 0:
  74. board[row][col], board[i][col] = board[i][col], board[row][col]
  75. break
  76. merge_blocks()
  77. elif move == 's':
  78. for col in range(SIZE):
  79. for row in range(SIZE - 1, 0, -1):
  80. if board[row][col] == 0:
  81. for i in range(row - 1, -1, -1):
  82. if board[i][col] != 0:
  83. board[row][col], board[i][col] = board[i][col], board[row][col]
  84. break
  85. merge_blocks()
  86. elif move == 'a':
  87. for row in range(SIZE):
  88. for col in range(SIZE - 1):
  89. if board[row][col] == 0:
  90. for i in range(col + 1, SIZE):
  91. if board[row][i] != 0:
  92. board[row][col], board[row][i] = board[row][i], board[row][col]
  93. break
  94. merge_blocks()
  95. elif move == 'd':
  96. for row in range(SIZE):
  97. for col in range(SIZE - 1, 0, -1):
  98. if board[row][col] == 0:
  99. for i in range(col - 1, -1, -1):
  100. if board[row][i] != 0:
  101. board[row][col], board[row][i] = board[row][i], board[row][col]
  102. break
  103. merge_blocks()
  104. # 游戏循环
  105. while True:
  106. print_board()
  107. if is_full() and not can_move():
  108. print("Game over!")
  109. break
  110. move = input("Enter move (w/a/s/d): ")
  111. handle_move(move)
  112. spawn_block()

在这个游戏中,玩家可以通过键盘输入 w/a/s/d 来移动数字块,合并相同的数字块,最终得到一个 $2048$ 的方块。游戏循环会一直运行,直到方格被填满且无法再移动,此时游戏结束。

扫雷

  1. import random
  2. # 定义方格的大小
  3. n = 10
  4. m = 10
  5. # 定义地雷数量
  6. num_mines = 10
  7. # 初始化方格
  8. board = [[0 for x in range(m)] for y in range(n)]
  9. # 随机生成地雷位置
  10. def place_mines(num_mines):
  11. for i in range(num_mines):
  12. row = random.randint(0, n - 1)
  13. col = random.randint(0, m - 1)
  14. while board[row][col] == -1:
  15. row = random.randint(0, n - 1)
  16. col = random.randint(0, m - 1)
  17. board[row][col] = -1
  18. # 统计地雷数量
  19. def count_mines(row, col):
  20. count = 0
  21. for i in range(max(row - 1, 0), min(row + 2, n)):
  22. for j in range(max(col - 1, 0), min(col + 2, m)):
  23. if board[i][j] == -1:
  24. count += 1
  25. return count
  26. # 显示方格
  27. def print_board():
  28. for row in board:
  29. for cell in row:
  30. if cell == -1:
  31. print('*', end=' ')
  32. elif cell == 0:
  33. print('.', end=' ')
  34. else:
  35. print(cell, end=' ')
  36. print()
  37. # 处理玩家的选择
  38. def handle_choice(row, col):
  39. if board[row][col] == -1:
  40. return False
  41. board[row][col] = count_mines(row, col)
  42. if board[row][col] == 0:
  43. for i in range(max(row - 1, 0), min(row + 2, n)):
  44. for j in range(max(col - 1, 0), min(col + 2, m)):
  45. if board[i][j] == 0:
  46. handle_choice(i, j)
  47. return True
  48. # 游戏循环
  49. place_mines(num_mines)
  50. while True:
  51. print_board()
  52. if all(all(cell != 0 for cell in row) for row in board):
  53. print("You win!")
  54. break
  55. row = int(input("Enter row: "))
  56. col = int(input("Enter col: "))
  57. if not handle_choice(row, col):
  58. print("You lose!")
  59. break

在这个游戏中,玩家需要在一个 $n\times m$ 的方格中找出所有的地雷,而不触雷。游戏开始时,地雷的位置会被随机生成。玩家通过输入行和列的位置来选择方块,如果选择到的方块是一个地雷,游戏结束,否则会显示该方块周围的地雷数量,并递归地展开周围的方块。如果所有不是地雷的方块都被展开,游戏结束,玩家获胜。

石头剪刀布

  1. # 定义手势
  2. HAND_GESTURES = ['rock', 'paper', 'scissors']
  3. # 定义胜利关系
  4. WIN_CONDITIONS = {
  5. 'rock': 'scissors',
  6. 'paper': 'rock',
  7. 'scissors': 'paper'
  8. }
  9. # 定义玩家类
  10. class Player:
  11. def __init__(self, name):
  12. self.name = name
  13. self.score = 0
  14. # 玩家出拳
  15. def play(self):
  16. while True:
  17. gesture = input(f'{self.name}, please enter your gesture (rock/paper/scissors): ')
  18. if gesture in HAND_GESTURES:
  19. return gesture
  20. else:
  21. print('Invalid input, please try again.')
  22. # 玩家获胜
  23. def win(self):
  24. self.score += 1
  25. print(f'{self.name} wins!')
  26. # 玩家平局
  27. def tie(self):
  28. print("It's a tie!")
  29. # 玩家失败
  30. def lose(self):
  31. print(f'{self.name} loses!')
  32. # 定义游戏类
  33. class Game:
  34. def __init__(self, player1, player2):
  35. self.player1 = player1
  36. self.player2 = player2
  37. # 开始游戏
  38. def start(self):
  39. while True:
  40. gesture1 = self.player1.play()
  41. gesture2 = self.player2.play()
  42. if gesture1 == gesture2:
  43. self.player1.tie()
  44. self.player2.tie()
  45. elif WIN_CONDITIONS[gesture1] == gesture2:
  46. self.player1.win()
  47. self.player2.lose()
  48. else:
  49. self.player1.lose()
  50. self.player2.win()
  51. print(f'{self.player1.name}: {self.player1.score}, {self.player2.name}: {self.player2.score}')
  52. if input('Do you want to play again? (y/n)') != 'y':
  53. break
  54. # 创建玩家并开始游戏
  55. player1 = Player('Player 1')
  56. player2 = Player('Player 2')
  57. game = Game(player1, player2)
  58. game.start()

在这个游戏中,两个玩家通过输入手势来比拼胜负,如果两个玩家出的手势相同,则为平局;否则根据胜利关系判断胜负。游戏循环会一直运行,直到玩家选择不再继续游戏。每个玩家都有一个积分,每次胜利可以获得一分,游戏结束时积分高的玩家获胜。

飞机大战

  1. import pygame
  2. import random
  3. # 定义窗口的大小
  4. WINDOW_WIDTH = 480
  5. WINDOW_HEIGHT = 600
  6. # 初始化 Pygame
  7. pygame.init()
  8. # 创建窗口
  9. window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
  10. pygame.display.set_caption('Plane Fight')
  11. # 加载图片
  12. background_image = pygame.image.load('background.png')
  13. player_image = pygame.image.load('player.png')
  14. enemy_image = pygame.image.load('enemy.png')
  15. bullet_image = pygame.image.load('bullet.png')
  16. # 定义颜色
  17. BLACK = (0, 0, 0)
  18. WHITE = (255, 255, 255)
  19. RED = (255, 0, 0)
  20. # 定义字体
  21. font = pygame.font.Font(None, 36)
  22. # 定义玩家类
  23. class Player(pygame.sprite.Sprite):
  24. def __init__(self):
  25. super().__init__()
  26. self.image = player_image
  27. self.rect = self.image.get_rect()
  28. self.rect.centerx = WINDOW_WIDTH // 2
  29. self.rect.bottom = WINDOW_HEIGHT - 10
  30. self.speed = 5
  31. # 移动
  32. def move(self, direction):
  33. if direction == 'left':
  34. self.rect.x -= self.speed
  35. elif direction == 'right':
  36. self.rect.x += self.speed
  37. if self.rect.left < 0:
  38. self.rect.left = 0
  39. elif self.rect.right > WINDOW_WIDTH:
  40. self.rect.right = WINDOW_WIDTH
  41. # 射击
  42. def shoot(self):
  43. bullet = Bullet(self.rect.centerx, self.rect.top)
  44. all_sprites.add(bullet)
  45. bullets.add(bullet)
  46. # 定义敌机类
  47. class Enemy(pygame.sprite.Sprite):
  48. def __init__(self):
  49. super().__init__()
  50. self.image = enemy_image
  51. self.rect = self.image.get_rect()
  52. self.rect.x = random.randint(0, WINDOW_WIDTH - self.rect.width)
  53. self.rect.y = random.randint(-100, -self.rect.height)
  54. self.speed = random.randint(1, 5)
  55. # 移动
  56. def move(self):
  57. self.rect.y += self.speed
  58. if self.rect.top > WINDOW_HEIGHT:
  59. self.kill()
  60. # 定义子弹类
  61. class Bullet(pygame.sprite.Sprite):
  62. def __init__(self, x, y):
  63. super().__init__()
  64. self.image = bullet_image
  65. self.rect = self.image.get_rect()
  66. self.rect.centerx = x
  67. self.rect.bottom = y
  68. self.speed = -10
  69. # 移动
  70. def move(self):
  71. self.rect.y += self.speed
  72. if self.rect.bottom < 0:
  73. self.kill()
  74. # 创建精灵组
  75. all_sprites = pygame.sprite.Group()
  76. enemies = pygame.sprite.Group()
  77. bullets = pygame.sprite.Group()
  78. # 创建玩家并添加到精灵组
  79. player = Player()
  80. all_sprites.add(player)
  81. # 定义游戏循环
  82. clock = pygame.time.Clock()
  83. score = 0
  84. game_over = False
  85. while not game_over:
  86. # 处理事件
  87. for event in pygame.event.get():
  88. if event.type == pygame.QUIT:
  89. game_over = True
  90. elif event.type == pygame.KEYDOWN:
  91. if event.key == pygame.K_LEFT:
  92. player.move('left')
  93. elif event.key == pygame.K_RIGHT:
  94. player.move('right')
  95. elif event.key == pygame.K_SPACE:
  96. player.shoot()
  97. # 更新游戏状态
  98. all_sprites.update()
  99. # 生成敌机
  100. if len(enemies) < 10:
  101. enemy = Enemy()
  102. all_sprites.add(enemy)
  103. enemies.add(enemy)
  104. # 检测子弹是否击中敌机
  105. hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
  106. for hit in hits:
  107. score += 10
  108. enemy = Enemy()
  109. all_sprites.add(enemy)
  110. enemies.add(enemy)
  111. # 检测敌机是否撞击玩家
  112. hits = pygame.sprite.spritecollide(player, enemies, False)
  113. if len(hits) > 0:
  114. game_over = True
  115. # 清屏
  116. window.fill(BLACK)
  117. # 绘制背景
  118. window.blit(background_image, (0, 0))
  119. # 绘制精灵组中的所有元素
  120. all_sprites.draw(window)
  121. # 显示得分
  122. score_text = font.render(f'Score: {score}', True, WHITE)
  123. window.blit(score_text, (10, 10))
  124. # 更新屏幕
  125. pygame.display.flip()
  126. # 控制帧率
  127. clock.tick(60)
  128. # 游戏结束,显示最终得分
  129. game_over_text = font.render('Game Over', True, RED)
  130. score_text = font.render(f'Final Score: {score}', True, WHITE)
  131. window.blit(game_over_text, (WINDOW_WIDTH // 2 - game_over_text.get_width() // 2, WINDOW_HEIGHT // 2 - game_over_text.get_height() // 2 - 30))
  132. window.blit(score_text, (WINDOW_WIDTH // 2 - score_text.get_width() // 2, WINDOW_HEIGHT // 2 - score_text.get_height() // 2 + 30))
  133. pygame.display.flip()
  134. # 等待 3 秒后关闭窗口
  135. pygame.time.wait(3000)
  136. pygame.quit()

在这个游戏中,玩家需要控制飞机躲避敌机的攻击并射击敌机。玩家可以使用左右箭头键来移动飞机,使用空格键发射子弹。游戏中会随机生成敌机,玩家需要尽可能地消灭敌机并获得得分。如果敌机撞击到玩家飞机,游戏结束。

贪吃蛇

  1. import pygame
  2. import random
  3. # 定义窗口的大小和方格的大小
  4. WINDOW_WIDTH = 480
  5. WINDOW_HEIGHT = 480
  6. CELL_SIZE = 20
  7. # 初始化 Pygame
  8. pygame.init()
  9. # 创建窗口
  10. window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
  11. pygame.display.set_caption('Snake')
  12. # 定义颜色
  13. BLACK = (0, 0, 0)
  14. WHITE = (255, 255, 255)
  15. GREEN = (0, 255, 0)
  16. RED = (255, 0, 0)
  17. # 定义字体
  18. font = pygame.font.Font(None, 36)
  19. # 定义蛇类
  20. class Snake:
  21. def __init__(self):
  22. self.body = [(5, 5), (4, 5), (3, 5)]
  23. self.direction = 'right'
  24. # 移动
  25. def move(self):
  26. head = self.body[0]
  27. if self.direction == 'up':
  28. new_head = (head[0], head[1] - 1)
  29. elif self.direction == 'down':
  30. new_head = (head[0], head[1] + 1)
  31. elif self.direction == 'left':
  32. new_head = (head[0] - 1, head[1])
  33. elif self.direction == 'right':
  34. new_head = (head[0] + 1, head[1])
  35. self.body.insert(0, new_head)
  36. self.body.pop()
  37. # 改变方向
  38. def change_direction(self, direction):
  39. if direction == 'up' and self.direction != 'down':
  40. self.direction = 'up'
  41. elif direction == 'down' and self.direction != 'up':
  42. self.direction = 'down'
  43. elif direction == 'left' and self.direction != 'right':
  44. self.direction = 'left'
  45. elif direction == 'right' and self.direction != 'left':
  46. self.direction = 'right'
  47. # 检查是否吃到食物
  48. def check_eat_food(self, food):
  49. if self.body[0] == food.position:
  50. self.body.append(self.body[-1])
  51. # 定义食物类
  52. class Food:
  53. def __init__(self):
  54. self.position = (random.randint(0, WINDOW_WIDTH // CELL_SIZE - 1), random.randint(0, WINDOW_HEIGHT // CELL_SIZE - 1))
  55. # 重新生成位置
  56. def respawn(self):
  57. self.position = (random.randint(0, WINDOW_WIDTH // CELL_SIZE - 1), random.randint(0, WINDOW_HEIGHT // CELL_SIZE - 1))
  58. # 创建蛇和食物对象
  59. snake = Snake()
  60. food = Food()
  61. # 定义游戏循环
  62. clock = pygame.time.Clock()
  63. score = 0
  64. game_over = False
  65. while not game_over:
  66. # 处理事件
  67. for event in pygame.event.get():
  68. if event.type == pygame.QUIT:
  69. game_over = True
  70. elif event.type == pygame.KEYDOWN:
  71. if event.key == pygame.K_UP:
  72. snake.change_direction('up')
  73. elif event.key == pygame.K_DOWN:
  74. snake.change_direction('down')
  75. elif event.key == pygame.K_LEFT:
  76. snake.change_direction('left')
  77. elif event.key == pygame.K_RIGHT:
  78. snake.change_direction('right')
  79. # 更新游戏状态
  80. snake.move()
  81. snake.check_eat_food(food)
  82. if snake.body[0][0] < 0 or snake.body[0][0] >= WINDOW_WIDTH // CELL_SIZE or snake.body[0][1] < 0 or snake.body[0][1] >= WINDOW_HEIGHT // CELL_SIZE:
  83. game_over = True
  84. for i in range(1, len(snake.body)):
  85. if snake.body[i] == snake.body[0]:
  86. game_over = True
  87. # 清屏
  88. window.fill(BLACK)
  89. # 绘制蛇
  90. for cell in snake.body:
  91. pygame.draw.rect(window, GREEN, (cell[0] * CELL_SIZE, cell[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
  92. # 绘制食物
  93. pygame.draw.rect(window, RED, (food.position[0] * CELL_SIZE, food.position[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
  94. # 显示得分希望这个示例能够帮助您更好地了解 Python 编程语言。如果您有任何问题,请随时问我。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/84759
推荐阅读
相关标签
  

闽ICP备14008679号