#author: hanshiqiang365 (微信公众号)
import random
import pygame
import sys
import time
from pygame.locals import *
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 500
SIZE = 20
LINE_WIDTH = 1
SCOPE_X = int(SCREEN_WIDTH/SIZE)
SCOPE_Y = int(SCREEN_HEIGHT/SIZE)
FOOD_STYLE_LIST = [(10, (20, 120, 20)), (20, (255, 20, 20)), (30, (20, 20, 120))]
GAME_W = int(SCREEN_WIDTH/SIZE)
FIELD_SIZE = SCOPE_X * SCOPE_Y
BGCOLOR = (20, 120, 20)
BLACK = (0, 0, 0)
FOOD = 0
FREE_PLACE = (SCOPE_X+1) * (SCOPE_Y+1)
SNAKE_PLACE = 2 * FREE_PLACE
ERR = -404
Display_Clock = 17
Head_index = 0
best_move = ERR
move_directions = {
'left': -1,
'right': 1,
'up': -GAME_W,
'down': GAME_W
}
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgText = font.render(text, True, fcolor)
screen.blit(imgText, (x, y))
def close_game():
pygame.quit()
sys.exit()
def check_pressKey():
if len(pygame.event.get(QUIT)) > 0:
close_game()
KeyUp_Events = pygame.event.get(KEYUP)
if len(KeyUp_Events) == 0:
return None
elif KeyUp_Events[0].key == K_ESCAPE:
close_game()
return KeyUp_Events[0].key
def get_foodlocation(snake_Coords):
flag = True
while flag:
food_location = {'x': random.randint(0, SCOPE_X-1), 'y': random.randint(2, SCOPE_Y-1)}
if food_location not in snake_Coords:
flag = False
return food_location
def create_food(coord):
x = coord['x'] * SIZE
y = coord['y'] * SIZE
food_Rect = pygame.Rect(x, y, SIZE, SIZE)
pygame.draw.rect(screen, FOOD_STYLE_LIST[random.randint(0, 2)][1], food_Rect)
def init_snake(coords):
x = coords[0]['x'] * SIZE
y = coords[0]['y'] * SIZE
Snake_head_Rect = pygame.Rect(x, y, SIZE, SIZE)
pygame.draw.rect(screen, (0, 80, 255), Snake_head_Rect)
Snake_head_Inner_Rect = pygame.Rect(x+4, y+4, SIZE-8, SIZE-8)
pygame.draw.rect(screen, (0, 80, 255), Snake_head_Inner_Rect)
for coord in coords[1:]:
x = coord['x'] * SIZE
y = coord['y'] * SIZE
Snake_part_Rect = pygame.Rect(x, y, SIZE, SIZE)
pygame.draw.rect(screen, (0, 155, 0), Snake_part_Rect)
Snake_part_Inner_Rect = pygame.Rect(x+4, y+4, SIZE-8, SIZE-8)
pygame.draw.rect(screen, (0, 255, 0), Snake_part_Inner_Rect)
def game_start():
title_Font = pygame.font.SysFont('SimHei', 120)
title_content = title_Font.render('AI贪吃蛇', True, (255, 255, 255), (20, 120, 20))
angle = 0
while True:
screen.fill(BLACK)
rotated_title = pygame.transform.rotate(title_content, angle)
rotated_title_Rect = rotated_title.get_rect()
rotated_title_Rect.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
screen.blit(rotated_title, rotated_title_Rect)
pressKey_content = game_font.render('Press any Key to start the AI Doodle Snake Game!', True, (180, 180, 180))
pressKey_Rect = pressKey_content.get_rect()
pressKey_Rect.topleft = (SCREEN_WIDTH-600, SCREEN_HEIGHT-30)
screen.blit(pressKey_content, pressKey_Rect)
if check_pressKey():
pygame.event.get()
return
pygame.display.update()
game_clock.tick(Display_Clock)
angle -= 5
def game_over():
title_Font = pygame.font.SysFont('SimHei', 120)
title_gameover = title_Font.render('Game Over', True, (255, 0, 0))
gameover_Rect = title_gameover.get_rect()
gameover_Rect.midtop = (SCREEN_WIDTH/2, 120)
screen.blit(title_gameover, gameover_Rect)
gameauthor_line1 = game_font.render('韩思工作室出品 ', True, (20, 20, 255))
gameauthor_line1_Rect = gameauthor_line1.get_rect()
gameauthor_line1_Rect.midtop = (SCREEN_WIDTH/2, 350)
screen.blit(gameauthor_line1, gameauthor_line1_Rect)
gameauthor_line2 = game_font.render('(微信公众号:hanshiqiang365)', True, (20, 20, 255))
gameauthor_line2_Rect = gameauthor_line2.get_rect()
gameauthor_line2_Rect.midtop = (SCREEN_WIDTH/2, 390)
screen.blit(gameauthor_line2, gameauthor_line2_Rect)
pygame.display.update()
pygame.time.wait(500)
while True:
for event in pygame.event.get():
if event.type == QUIT:
close_game()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
close_game()
def is_freecell(idx, psnake):
location_x = idx % GAME_W
location_y = idx // GAME_W
idx = {'x': location_x, 'y': location_y}
return (idx not in psnake)
def board_reset(psnake, pboard, pfood):
temp_board = pboard[:]
pfood_idx = pfood['x'] + pfood['y'] * GAME_W
for i in range(FIELD_SIZE):
if i == pfood_idx:
temp_board[i] = FOOD
elif is_freecell(i, psnake):
temp_board[i] = FREE_PLACE
else:
temp_board[i] = SNAKE_PLACE
return temp_board
def is_movepossible(idx, move_direction):
flag = False
if move_direction == 'left':
if idx%GAME_W > 0:
flag = True
else:
flag = False
elif move_direction == 'right':
if idx%GAME_W < (GAME_W-1):
flag = True
else:
flag = False
elif move_direction == 'up':
if idx > (3 * GAME_W - 1):
flag = True
else:
flag = False
elif move_direction == 'down':
if idx < (FIELD_SIZE - GAME_W):
flag = True
else:
flag = False
return flag
def board_refresh(psnake, pfood, pboard):
temp_board = pboard[:]
pfood_idx = pfood['x'] + pfood['y'] * GAME_W
queue = []
queue.append(pfood_idx)
inqueue = [0] * FIELD_SIZE
found = False
while len(queue) != 0:
idx = queue.pop(0)
if inqueue[idx] == 1:
continue
inqueue[idx] = 1
for move_direction in ['left', 'right', 'up', 'down']:
if is_movepossible(idx, move_direction):
if (idx+move_directions[move_direction]) == (psnake[Head_index]['x'] + psnake[Head_index]['y']*GAME_W):
found = True
if temp_board[idx+move_directions[move_direction]] < SNAKE_PLACE:
if temp_board[idx+move_directions[move_direction]] > temp_board[idx]+1:
temp_board[idx+move_directions[move_direction]] = temp_board[idx] + 1
if inqueue[idx+move_directions[move_direction]] == 0:
queue.append(idx+move_directions[move_direction])
return (found, temp_board)
def find_snakehead(snake_Coords, direction):
if direction == 'up':
newHead = {'x': snake_Coords[Head_index]['x'],
'y': snake_Coords[Head_index]['y']-1}
elif direction == 'down':
newHead = {'x': snake_Coords[Head_index]['x'],
'y': snake_Coords[Head_index]['y']+1}
elif direction == 'left':
newHead = {'x': snake_Coords[Head_index]['x']-1,
'y': snake_Coords[Head_index]['y']}
elif direction == 'right':
newHead = {'x': snake_Coords[Head_index]['x']+1,
'y': snake_Coords[Head_index]['y']}
return newHead
def virtual_move(psnake, pboard, pfood):
temp_snake = psnake[:]
temp_board = pboard[:]
reset_tboard = board_reset(temp_snake, temp_board, pfood)
temp_board = reset_tboard
food_eated = False
while not food_eated:
refresh_tboard = board_refresh(temp_snake, pfood, temp_board)[1]
temp_board = refresh_tboard
move_direction = choose_shortestsafemove(temp_snake, temp_board)
snake_Coords = temp_snake[:]
temp_snake.insert(0, find_snakehead(snake_Coords, move_direction))
if temp_snake[Head_index] == pfood:
reset_tboard = board_reset(temp_snake, temp_board, pfood)
temp_board = reset_tboard
pfood_idx = pfood['x'] + pfood['y'] * GAME_W
temp_board[pfood_idx] = SNAKE_PLACE
food_eated = True
else:
newHead_idx = temp_snake[0]['x'] + temp_snake[0]['y'] * GAME_W
temp_board[newHead_idx] = SNAKE_PLACE
end_idx = temp_snake[-1]['x'] + temp_snake[-1]['y'] * GAME_W
temp_board[end_idx] = FREE_PLACE
del temp_snake[-1]
return temp_snake, temp_board
def is_tailinside(psnake, pboard, pfood):
temp_board = pboard[:]
temp_snake = psnake[:]
end_idx = temp_snake[-1]['x'] + temp_snake[-1]['y'] * GAME_W
temp_board[end_idx] = FOOD
v_food = temp_snake[-1]
pfood_idx = pfood['x'] + pfood['y'] * GAME_W
temp_board[pfood_idx] = SNAKE_PLACE
result, refresh_tboard = board_refresh(temp_snake, v_food, temp_board)
temp_board = refresh_tboard
for move_direction in ['left', 'right', 'up', 'down']:
idx = temp_snake[Head_index]['x'] + temp_snake[He
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 3、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 基于Python实现的经典贪吃蛇游戏和应用AI算法实现的AI贪吃蛇游戏源码+项目说明.zip
资源推荐
资源详情
资源评论
收起资源包目录
基于Python实现的经典贪吃蛇游戏和应用AI算法实现的AI贪吃蛇游戏源码+项目说明.zip (6个子文件)
code_20105
AI_doodlesnake_game.py 13KB
贪吃蛇.jpg 140KB
doodlesnake_game.py 5KB
game_bgm.wav 2.37MB
贪吃蛇.mp4 758KB
game_icon.png 186KB
共 6 条
- 1
资源评论
土豆片片
- 粉丝: 1573
- 资源: 5636
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功