贪吃蛇小游戏python代码
时间: 2023-09-04 10:10:51 浏览: 98
贪吃蛇游戏python代码
5星 · 资源好评率100%
下面是一个简单的贪吃蛇小游戏的Python代码,你可以在Python环境下运行它:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置游戏窗口大小
window_width = 800
window_height = 600
game_display = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('贪吃蛇小游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置蛇的方块大小
block_size = 20
# 加载字体
font = pygame.font.SysFont(None, 25)
# 定义函数,显示消息
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [window_width/2, window_height/2])
# 定义函数,画出蛇
def draw_snake(block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, black, [x[0], x[1], block_size, block_size])
# 设置帧率
clock = pygame.time.Clock()
# 定义主函数,游戏循环
def game_loop():
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_display.fill(white)
message_to_screen("Game over, press Q to quit or C to continue", 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
if event.key == pygame.K_c:
game_loop()
# 监听事件
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_display.fill(white)
# 画出食物
pygame.draw.rect(game_display, 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
# 画出蛇
draw_snake(block_size, snake_list)
# 更新屏幕
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(15)
# 退出游戏
pygame.quit()
quit()
# 开始游戏
game_loop()
```
运行代码后,你就可以开始玩这个贪吃蛇小游戏了。
阅读全文