用python代码实现贪吃蛇游戏
时间: 2023-05-18 22:07:00 浏览: 71
100行python代码完成的贪吃蛇游戏,简单方便快捷,下载即可运行,可做毕业设计
可以使用pygame库来实现贪吃蛇游戏,以下是一个简单的实现:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 640
window_height = 480
window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义贪吃蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = window_width / 2
snake_y = window_height / 2
# 定义食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义显示分数的函数
def show_score(score):
score_text = font_style.render("Score: " + str(score), True, black)
window.blit(score_text, [0, 0])
# 定义游戏结束的函数
def game_over():
game_over_text = font_style.render("Game Over!", True, red)
window.blit(game_over_text, [window_width / 3, window_height / 3])
pygame.display.update()
pygame.time.delay(2000)
# 游戏循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
# 获取键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_x -= snake_block_size
elif keys[pygame.K_RIGHT]:
snake_x += snake_block_size
elif keys[pygame.K_UP]:
snake_y -= snake_block_size
elif keys[pygame.K_DOWN]:
snake_y += snake_block_size
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
snake_length += 1
# 更新贪吃蛇的位置
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断是否撞到自己
for block in snake_list[:-1]:
if block == snake_head:
game_over()
# 绘制游戏界面
window.fill(white)
pygame.draw.rect(window, green, [food_x, food_y, food_block_size, food_block_size])
for block in snake_list:
pygame.draw.rect(window, black, [block[0], block[1], snake_block_size, snake_block_size])
show_score(snake_length - 1)
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
```
阅读全文