请用python写一个贪吃蛇游戏
时间: 2023-10-11 08:05:56 浏览: 107
Python编写一个贪吃蛇游戏
好的,我可以为您编写一个贪吃蛇游戏。以下是一份简单的Python代码示例,可能需要您对其进行调整以适应您的环境和需要:
```python
import pygame
import random
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 设置屏幕大小
dis_width = 800
dis_height = 600
pygame.init()
# 初始化游戏
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')
clock = pygame.time.Clock()
# 设置字体样式
font_style = pygame.font.SysFont(None, 50)
# 在屏幕上显示消息
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width/6, dis_height/3])
# 游戏主循环
def gameLoop():
game_over = False
game_close = False
# 蛇头的位置和大小
x1 = dis_width / 2
y1 = dis_height / 2
snake_block = 10
# 蛇的初始长度
snake_List = []
Length_of_snake = 1
# 初始化果实位置
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
# 蛇的移动速度
x1_change = 0
y1_change = 0
snake_speed = 30
while not game_over:
while game_close == True:
# 显示游戏结束提示信息
dis.fill(blue)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
# 退出游戏
game_over = True
game_close = False
if event.key == pygame.K_c:
# 重新开始游戏
gameLoop()
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_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 蛇头的位置发生变化
x1 += x1_change
y1 += y1_change
# 判断是否吃到果实
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
dis.fill(blue)
# 在屏幕上显示果实
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
# 更新蛇的位置
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_close = True
# 在屏幕上显示蛇
for x in snake_List:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
pygame.display.update()
# 不断更新屏幕的内容
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
# 调整速度
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 运行游戏
gameLoop()
```
希望以上代码能够帮助您编写出一个简单的贪吃蛇游戏。
阅读全文