贪吃蛇源码
  TccrgeKp8P69 2023年11月02日 53 0
贪吃蛇游戏的Python代码如下:

首先,需要安装pygame库,可以使用以下命令安装:

```bash
pip install pygame
```

接下来是贪吃蛇游戏的代码:

```python
import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置游戏标题
pygame.display.set_caption("贪吃蛇")

# 定义颜色
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 蛇的初始位置
snake_pos = [[100, 100], [80, 100], [60, 100]]

# 食物的初始位置
food_pos = [300, 300]

# 设置蛇和食物的大小
snake_size = 20
food_size = 20

# 设置游戏速度
clock = pygame.time.Clock()
speed = 15

# 设置蛇的移动方向
direction = "RIGHT"

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_UP and direction != "DOWN":
                direction = "UP"
            elif event.key == pygame.K_DOWN and direction != "UP":
                direction = "DOWN"
            elif event.key == pygame.K_LEFT and direction != "RIGHT":
                direction = "LEFT"
            elif event.key == pygame.K_RIGHT and direction != "LEFT":
                direction = "RIGHT"

    # 更新蛇的位置
    if direction == "UP":
        snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] - snake_size])
    elif direction == "DOWN":
        snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] + snake_size])
    elif direction == "LEFT":
        snake_pos.insert(0, [snake_pos[0][0] - snake_size, snake_pos[0][1]])
    elif direction == "RIGHT":
        snake_pos.insert(0, [snake_pos[0][0] + snake_size, snake_pos[0][1]])

    # 检查蛇是否吃到食物
    if snake_pos[0] == food_pos:
        food_pos = [random.randrange(1, screen_width // snake_size) * snake_size,
                    random.randrange(1, screen_height // snake_size) * snake_size]
    else:
        snake_pos.pop()

    # 检查蛇是否撞到墙或者自己
    if (snake_pos[0][0] < 0 or snake_pos[0][0] >= screen_width or
            snake_pos[0][1] < 0 or snake_pos[0][1] >= screen_height or
            snake_pos[0] in snake_pos[1:]):
        pygame.quit()
        sys.exit()

    # 绘制蛇和食物
    screen.fill(WHITE)
    for pos in snake_pos:
        pygame.draw.rect(screen, GREEN, (pos[0], pos[1], snake_size, snake_size))
    pygame.draw.rect(screen, RED, (food_pos[0], food_pos[1], food_size, food_size))

    # 更新屏幕
    pygame.display.flip()

    # 控制游戏速度
    clock.tick(speed)
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  fl0iHpTOb5wE   2023年11月13日   33   0   0 linuxpythonCentOS
  fl0iHpTOb5wE   2023年11月13日   27   0   0 Tensorflowlinuxpython
  nQkVcpdWfLDr   2023年11月13日   42   0   0 数组sort函数python
TccrgeKp8P69
作者其他文章 更多

2023-11-02