| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 396 人关注过本帖
标题:分享一个自动贪吃蛇代码
只看楼主 加入收藏
yuma
Rank: 12Rank: 12Rank: 12
来 自:银河系
等 级:贵宾
威 望:37
帖 子:1934
专家分:3012
注 册:2009-12-22
结帖率:89.13%
收藏
 问题点数:0 回复次数:0 
分享一个自动贪吃蛇代码
最多支持1000X1000的方格,只要你的显示器支持就行。

程序代码:
import pygame
import random
import sys
from queue import PriorityQueue

# 初始化 pygame
pygame.init()

# 颜色定义
WHITE = (255, 255, 255)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
GRAY = (169, 169, 169)  # 网格颜色

# 网格数量
GRID_WIDTH = 100  # 列数
GRID_HEIGHT = 100  # 行数

# 计算网格大小
screen_info = pygame.display.Info()
SCREEN_WIDTH = screen_info.current_w
SCREEN_HEIGHT = screen_info.current_h
GRID_SIZE = min(SCREEN_WIDTH // GRID_WIDTH, SCREEN_HEIGHT // GRID_HEIGHT)

# 全屏模式
full_screen = True

if full_screen:
    screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
else:
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# 调整贪吃蛇移动速度
SNAKE_SPEED = 100  # 每秒移动次数

class Snake:
    def __init__(self):
        self.elements = [(GRID_WIDTH // 2 * GRID_SIZE, GRID_HEIGHT // 2 * GRID_SIZE)]
        self.direction = 'up'
        self.grow = False

    def move(self):
        head_x, head_y = self.elements[0]

        # 检查是否碰到墙壁
        if head_x < 0 or head_x >= SCREEN_WIDTH or head_y < 0 or head_y >= SCREEN_HEIGHT:
            sys.exit("Game Over - Hit the Wall!")

        # 检查是否碰到自身
        if self.check_self_collision():
            sys.exit("Game Over - Hit Yourself!")

        new_head = self.get_next_head()
        self.elements.insert(0, new_head)

        if self.grow:
            self.grow = False
        else:
            self.elements.pop()

    def add_to_snake(self):
        self.grow = True

    def render(self, screen):
        for element in self.elements:
            pygame.draw.rect(screen, GREEN, pygame.Rect(element[0], element[1], GRID_SIZE, GRID_SIZE))

    def check_self_collision(self):
        return self.elements[0] in self.elements[1:]

    def get_next_head(self):
        head_x, head_y = self.elements[0]
        if self.direction == 'up':
            return (head_x, head_y - GRID_SIZE)
        elif self.direction == 'down':
            return (head_x, head_y + GRID_SIZE)
        elif self.direction == 'left':
            return (head_x - GRID_SIZE, head_y)
        elif self.direction == 'right':
            return (head_x + GRID_SIZE, head_y)

class Food:
    def __init__(self, snake):
        self.snake = snake
        self.randomize_position()

    def randomize_position(self):
        while True:
            self.position = (random.randint(0, GRID_WIDTH - 1) * GRID_SIZE, random.randint(0, GRID_HEIGHT - 1) * GRID_SIZE)
            if self.position not in self.snake.elements:
                break

    def render(self, screen):
        pygame.draw.rect(screen, RED, pygame.Rect(self.position[0], self.position[1], GRID_SIZE, GRID_SIZE))

def heuristic(a, b):
    return abs(a[0] - b[0]) + abs(a[1] - b[1])

def a_star_search(snake, food):
    start = snake.elements[0]
    goal = food.position
    open_set = PriorityQueue()
    open_set.put((0, start))
    came_from = {}
    g_score = {tuple(pos): float('inf') for pos in snake.elements}
    g_score[start] = 0
    f_score = {tuple(pos): float('inf') for pos in snake.elements}
    f_score[start] = heuristic(start, goal)

    while not open_set.empty():
        _, current = open_set.get()

        if current == goal:
            return reconstruct_path(came_from, current)

        for neighbor in get_neighbors(current):
            tentative_g_score = g_score[current] + 1

            if neighbor not in g_score or tentative_g_score < g_score[neighbor]:
                came_from[neighbor] = current
                g_score[neighbor] = tentative_g_score
                f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
                open_set.put((f_score[neighbor], neighbor))

    return None

def get_neighbors(pos):
    x, y = pos
    neighbors = [(x - GRID_SIZE, y), (x + GRID_SIZE, y), (x, y - GRID_SIZE), (x, y + GRID_SIZE)]
    return [n for n in neighbors if is_valid(n)]

def is_valid(pos):
    x, y = pos
    return 0 <= x < SCREEN_WIDTH and 0 <= y < SCREEN_HEIGHT and pos not in snake.elements

def reconstruct_path(came_from, current):
    path = []
    while current in came_from:
        path.insert(0, current)
        current = came_from[current]
    return path

def draw_grid(screen):
    for x in range(0, SCREEN_WIDTH, GRID_SIZE):
        pygame.draw.line(screen, GRAY, (x, 0), (x, SCREEN_HEIGHT))
    for y in range(0, SCREEN_HEIGHT, GRID_SIZE):
        pygame.draw.line(screen, GRAY, (0, y), (SCREEN_WIDTH, y))

snake = Snake()
food = Food(snake)

pygame.display.set_caption('自动贪吃蛇游戏')
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    path = a_star_search(snake, food)
    if path:
        next_move = path[0]
        head_x, head_y = snake.elements[0]
        if next_move[0] < head_x:
            snake.direction = 'left'
        elif next_move[0] > head_x:
            snake.direction = 'right'
        elif next_move[1] < head_y:
            snake.direction = 'up'
        elif next_move[1] > head_y:
            snake.direction = 'down'

    snake.move()

    if snake.elements[0] == food.position:
        snake.add_to_snake()
        food.randomize_position()

    screen.fill(BLACK)
    draw_grid(screen)
    snake.render(screen)
    food.render(screen)
    pygame.display.flip()
    clock.tick(SNAKE_SPEED)
搜索更多相关主题的帖子: def screen pygame if elements 
2023-10-11 11:40
快速回复:分享一个自动贪吃蛇代码
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019675 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved