软件价值2-贪吃蛇游戏

贪吃蛇游戏虽然很多,不过它可以作为软件创作的开端,用python来实现,然后dist成windows系统可执行文件。

import pygame
import sys
import random

# 初始化
pygame.init()

# 游戏设置
width, height = 640, 480
cell_size = 20
snake_speed = 15

# 颜色定义
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)

# 创建窗口
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇游戏")

# 初始化蛇
snake = [(100, 100), (90, 100), (80, 100)]
snake_direction = (cell_size, 0)

# 初始化食物
food = (random.randint(0, width - cell_size) // cell_size * cell_size,
        random.randint(0, height - cell_size) // cell_size * cell_size)

# 游戏循环
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_UP and snake_direction != (0, cell_size):
                snake_direction = (0, -cell_size)
            elif event.key == pygame.K_DOWN and snake_direction != (0, -cell_size):
                snake_direction = (0, cell_size)
            elif event.key == pygame.K_LEFT and snake_direction != (cell_size, 0):
                snake_direction = (-cell_size, 0)
            elif event.key == pygame.K_RIGHT and snake_direction != (-cell_size, 0):
                snake_direction = (cell_size, 0)

    # 移动蛇
    head = (snake[0][0] + snake_direction[0], snake[0][1] + snake_direction[1])

    # 边界碰撞检测
    if head[0] < 0:
        head = (width - cell_size, head[1])
    elif head[0] >= width:
        head = (0, head[1])
    elif head[1] < 0:
        head = (head[0], height - cell_size)
    elif head[1] >= height:
        head = (head[0], 0)

    snake = [head] + snake[:-1]

    # 判断是否吃到食物
    if head == food:
        snake.append(snake[-1])
        food = (random.randint(0, width - cell_size) // cell_size * cell_size,
                random.randint(0, height - cell_size) // cell_size * cell_size)

    # 判断是否游戏结束
    if head in snake[1:]:
        pygame.quit()
        sys.exit()

    # 绘制窗口
    window.fill(black)

    # 绘制蛇
    for segment in snake:
        pygame.draw.rect(window, white, pygame.Rect(segment[0], segment[1], cell_size, cell_size))

    # 绘制食物
    pygame.draw.rect(window, red, pygame.Rect(food[0], food[1], cell_size, cell_size))

    # 更新显示
    pygame.display.flip()

    # 控制帧率
    clock.tick(snake_speed)

发布: 

用PyInstaller可以将 Python 脚本打包成 Windows、Linux 和 macOS 上的可执行文件。你可以使用以下命令安装 PyInstaller:

pip install pyinstaller

然后,可以使用以下命令将你的游戏脚本打包成一个可执行文件:

pyinstaller --onefile greedySnake.py

这将在 dist 文件夹中生成一个单一的可执行文件。

运行:

贪吃蛇游戏

你可能感兴趣的:(软件价值,python,贪吃蛇游戏,软件价值)