贪吃蛇代码python
时间: 2023-07-02 19:21:46 浏览: 129
贪吃蛇python代码
以下是一个简单的贪吃蛇代码示例,使用 Python 语言编写:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏界面尺寸、背景颜色、标题
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREEN = pygame.Color(0, 255, 0)
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont(None, 48)
text = font.render('游戏结束', True, RED)
text_rect = text.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery - 24
screen.blit(text, text_rect)
pygame.display.flip()
pygame.time.delay(3000)
pygame.quit()
sys.exit()
# 定义主函数
def main():
# 初始化贪吃蛇和食物
snake_positions = [(200, 200), (210, 200), (220, 200)]
snake_direction = 'right'
food_position = (random.randint(0, 590), random.randint(0, 590))
food_exist = True
# 设置游戏帧率
clock = pygame.time.Clock()
# 开始游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
elif event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
# 移动贪吃蛇
if snake_direction == 'right':
new_head = (snake_positions[0][0] + 10, snake_positions[0][1])
elif snake_direction == 'left':
new_head = (snake_positions[0][0] - 10, snake_positions[0][1])
elif snake_direction == 'up':
new_head = (snake_positions[0][0], snake_positions[0][1] - 10)
elif snake_direction == 'down':
new_head = (snake_positions[0][0], snake_positions[0][1] + 10)
snake_positions.insert(0, new_head)
# 判断贪吃蛇是否吃到食物
if snake_positions[0] == food_position:
food_exist = False
else:
snake_positions.pop()
# 重新生成食物
if not food_exist:
food_position = (random.randint(0, 590), random.randint(0, 590))
food_exist = True
# 绘制游戏界面
screen.fill(BLACK)
for position in snake_positions:
pygame.draw.rect(screen, GREEN, pygame.Rect(position[0], position[1], 10, 10))
pygame.draw.rect(screen, WHITE, pygame.Rect(food_position[0], food_position[1], 10, 10))
# 判断贪吃蛇是否死亡
if snake_positions[0][0] < 0 or snake_positions[0][0] > 590 or snake_positions[0][1] < 0 or snake_positions[0][1] > 590:
game_over()
for position in snake_positions[1:]:
if snake_positions[0] == position:
game_over()
# 更新游戏界面
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 启动游戏
if __name__ == '__main__':
main()
```
这是一个基本的贪吃蛇代码示例,可以实现贪吃蛇的基本功能。当然,你可以根据自己的需要进行修改和扩展。
阅读全文