python单机小游戏贪吃蛇并加上注释
时间: 2023-07-10 19:41:20 浏览: 127
好的,下面是带有注释的Python单机小游戏贪吃蛇的实现过程:
```python
# 导入必要的模块
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小和标题
window_width = 640
window_height = 480
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# 定义颜色和字体
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
font = pygame.font.SysFont(None, 25)
# 定义贪吃蛇和食物的初始位置和大小
block_size = 10
snake_speed = 15
# 定义绘制贪吃蛇的函数
def snake(snake_list, block_size):
for x_y in snake_list:
pygame.draw.rect(game_window, black, [x_y[0], x_y[1], block_size, block_size])
# 定义显示文字的函数
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_window.blit(screen_text, [window_width/6, window_height/6])
# 定义游戏主函数
def gameLoop():
# 定义游戏结束和退出的标志
game_exit = False
game_over = False
# 定义贪吃蛇头的位置和移动的速度
lead_x = window_width/2
lead_y = window_height/2
lead_x_change = 0
lead_y_change = 0
# 定义贪吃蛇的列表和长度
snake_list = []
snake_length = 1
# 定义食物的位置
food_x = round(random.randrange(0, window_width-block_size)/10.0)*10.0
food_y = round(random.randrange(0, window_height-block_size)/10.0)*10.0
# 开始游戏循环
while not game_exit:
# 如果游戏结束,显示游戏结束的文字
while game_over == True:
game_window.fill(white)
message_to_screen('Game over, press Q to quit or C to play again', red)
pygame.display.update()
# 处理游戏结束后的事件
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
elif event.key == pygame.K_c:
gameLoop()
# 处理游戏中的事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# 判断贪吃蛇是否撞墙,如果是,游戏结束
if lead_x >= window_width or lead_x < 0 or lead_y >= window_height or lead_y < 0:
game_over = True
# 计算贪吃蛇头的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 在游戏窗口中绘制食物和贪吃蛇
game_window.fill(white)
pygame.draw.rect(game_window, red, [food_x, food_y, block_size, block_size])
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for each_segment in snake_list[:-1]:
if each_segment == snake_head:
game_over = True
snake(snake_list, block_size)
pygame.display.update()
# 判断贪吃蛇是否吃到了食物,如果是,增加贪吃蛇的长度
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(0, window_width-block_size)/10.0)*10.0
food_y = round(random.randrange(0, window_height-block_size)/10.0)*10.0
snake_length += 1
# 控制游戏的速度
clock.tick(snake_speed)
# 退出Pygame
pygame.quit()
quit()
# 调用游戏主函数
gameLoop()
```
这样一个带有注释的Python单机小游戏贪吃蛇就完成了。希望对您有所帮助!
阅读全文