使用python写一个贪吃蛇小游戏
时间: 2024-01-06 19:06:36 浏览: 138
好的,下面是一个简易的贪吃蛇小游戏代码,供参考:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
# 设置标题
pygame.display.set_caption("Greedy Snake Game")
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置字体
font_style = pygame.font.SysFont(None, 50)
# 定义蛇的大小和速度
snake_size = 10
snake_speed = 15
# 定义函数:显示分数
def show_score(score):
score_text = font_style.render("Score: " + str(score), True, white)
window.blit(score_text, [0, 0])
# 定义函数:画蛇
def draw_snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, green, [x[0], x[1], snake_size, snake_size])
# 定义主函数
def main():
# 初始化蛇的位置和长度
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
# 初始化食物的位置
foodx = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
# 初始化分数
score = 0
# 游戏循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 判断是否撞墙
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_over = True
# 移动蛇的位置
x1 += x1_change
y1 += y1_change
# 画出背景
window.fill(black)
# 画出食物
pygame.draw.rect(window, red, [foodx, foody, snake_size, snake_size])
# 更新蛇的位置
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
# 判断是否吃到食物
for x in snake_list[:-1]:
if x == snake_head:
game_over = True
draw_snake(snake_size, snake_list)
show_score(score)
# 更新分数
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
length_of_snake += 1
score += 10
# 刷新屏幕
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 关闭游戏
pygame.quit()
quit()
# 运行游戏
main()
```
注意:在运行代码前,需要先安装pygame库。可以使用命令行输入`pip install pygame`来安装。
阅读全文