您现在的位置是:网站首页> 编程资料编程资料
Python实现智能贪吃蛇游戏的示例代码_python_
2023-05-26
384人已围观
简介 Python实现智能贪吃蛇游戏的示例代码_python_
前言
我想大家都玩过诺基亚上面的贪吃蛇吧,本文将带你一步步用python语言实现一个snake小游戏。
基本环境配置
版本:Python3
系统:Windows
相关模块:pygame
pip install pygame安装即可
实现效果


实现代码
import random, pygame, sys from pygame.locals import * import time ''' ''' FPS = 1 ##WINDOWWIDTH = 640 #WINDOWHEIGHT = 480 WINDOWWIDTH = 600 WINDOWHEIGHT = 480 CELLSIZE = 40 assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size." assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size." CELLWIDTH = int(WINDOWWIDTH / CELLSIZE) CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE) # R G B WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) RED = (255, 0, 0) GREEN = ( 0, 255, 0) DARKGREEN = ( 0, 155, 0) DARKGRAY = ( 40, 40, 40) BGCOLOR = BLACK UP = 'up' DOWN = 'down' LEFT = 'left' RIGHT = 'right' direction = UP DIRECTION = [UP,DOWN,LEFT,RIGHT] HEAD = 0 # syntactic sugar: index of the worm's head distance = [] for y in range(CELLHEIGHT): distance.append([]) for x in range(CELLWIDTH): distance[y].append(8888) def into_queue(grid, queue, visited, worm,apple): x,y = grid if (x, y) == (apple['x'],apple['y']): return False elif x < 0 or x >= CELLWIDTH: return False elif y < 0 or y >= CELLHEIGHT: return False elif (x, y) in queue: return False elif (x, y) in visited: return False else: return True def is_snake(x,y,worm): for body in worm: if body['x'] == x and body['y'] == y: return True return False def cal_distance(worm,apple): queue = [(apple['x'],apple['y'])] visited = [] found = False for y in range(CELLHEIGHT): for x in range(CELLWIDTH): distance[y][x] = 9999 distance[apple['y']][apple['x']] = 0 while len(queue) != 0: head = queue[0] visited.append(head) up_grid = head[0], head[1] - 1 down_grid = head[0], head[1] + 1 left_grid = head[0] - 1, head[1] right_grid = head[0] + 1, head[1] for grid in [up_grid, down_grid, left_grid, right_grid]: if into_queue(grid, queue, visited,worm,apple): if grid[0] == worm[HEAD]['x'] and grid[1] == worm[HEAD]['y']: found = True if not is_snake(grid[0],grid[1],worm): queue.append(grid) distance[grid[1]][grid[0]] = distance[head[1]][head[0]] + 1 queue.pop(0) return found def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) BASICFONT = pygame.font.Font('freesansbold.ttf', 18) pygame.display.set_caption('Snaky') showStartScreen() while True: runGame() showGameOverScreen() def can_move(grid, worm): x,y = grid if x < 0 or x >= CELLWIDTH: return False elif y < 0 or y >= CELLHEIGHT: return False elif is_snake(x, y,worm): return False elif (x, y) == (worm[HEAD]['x'], worm[HEAD]['y']): return False else: return True def update_dirc(now, direc): loc = {'x':0,'y':0} if direc == UP: loc = {'x':now['x'],'y':now['y']-1} elif direc == DOWN: loc = {'x':now['x'],'y':now['y']+1} elif direc == RIGHT: loc = {'x':now['x']+1,'y':now['y']} elif direc == LEFT: loc = {'x':now['x']-1,'y':now['y']} return loc def virtual_run(wormCoords, apple,direction): wormCoords = list(wormCoords) food_eated = False while not food_eated: cal_distance(wormCoords,apple) four_dis = [99999, 99999, 99999, 99999] if can_move((wormCoords[HEAD]['x'], wormCoords[HEAD]['y'] - 1), wormCoords): four_dis[0] = distance[wormCoords[HEAD]['y'] - 1][wormCoords[HEAD]['x']] if can_move((wormCoords[HEAD]['x'] + 1, wormCoords[HEAD]['y']), wormCoords): four_dis[1] = distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] + 1] if can_move((wormCoords[HEAD]['x'], wormCoords[HEAD]['y'] + 1), wormCoords): four_dis[2] = distance[wormCoords[HEAD]['y'] + 1][wormCoords[HEAD]['x']] if can_move((wormCoords[HEAD]['x'] - 1, wormCoords[HEAD]['y']), wormCoords): four_dis[3] = distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] - 1] min_num = min(four_dis) if four_dis[0] < 99999 and distance[wormCoords[HEAD]['y'] - 1][wormCoords[HEAD]['x']] == min_num and direction != DOWN: direction = UP elif four_dis[1] < 99999 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] + 1] == min_num and direction != "LEFT": direction = RIGHT elif four_dis[2] < 99999 and distance[wormCoords[HEAD]['y'] + 1][wormCoords[HEAD]['x']] == min_num and direction != "UP": direction = DOWN elif four_dis[3] < 99999 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] - 1] == min_num and direction != RIGHT: direction = LEFT if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == CELLHEIGHT: return # game over for wormBody in wormCoords[1:]: if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']: return # move the worm by adding a segment in the direction it is moving if direction == UP: newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1} elif direction == DOWN: newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1} elif direction == LEFT: newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']} elif direction == RIGHT: newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']} if wormCoords[HEAD]['x'] != apple['x'] or wormCoords[HEAD]['y'] != apple['y']: food_eated = True wormCoords.insert(0, newHead) else: del wormCoords[-1] # remove worm's tail segment wormCoords.insert(0, newHead) result = cal_distance(wormCoords,wormCoords[-1]) for i in range(4): temp = update_dirc(wormCoords[HEAD],DIRECTION[i]) if temp['x'] == wormCoords[-1]['x'] and temp['y'] == wormCoords[-1]['y']: result = False return result def distance_(x,y): return abs(x['x']-y['x']) + abs(x['y'] - x['y']) def any_possible_move(worm,apple,direction): temp_direc = direction max_dis = 0 for i in range(4): temp = update_dirc(worm[0],DIRECTION[i]) if can_move((temp['x'],temp['y']),worm): if (distance_(temp, apple) > max_dis) and (examine_direction(DIRECTION[i], direction)): max_dis = distance_(temp, apple) temp_direc = DIRECTION[i] return temp_direc def examine_direction(temp , direction): if direction == UP: if temp == DOWN: return False elif direction == RIGHT: if temp == LEFT: return False elif direction == LEFT: if temp == RIGHT: return False elif direction == DOWN: if temp == UP: return False return True def check_head(worm,direction): for i in range(4): temp = update_dirc(worm[HEAD], DIRECTION[i]) if can_move((temp['x'],temp['y']),worm) and examine_direction(DIRECTION[i],direction): if distance[temp['y']][temp['x']] < 9999: return True return False def runGame(): global running_,DIRECTION # Set a random start point. startx = random.randint(0, CELLWIDTH -1) starty = random.randint(0, CELLHEIGHT -1) wormCoords = [{'x': startx, 'y': starty}, {'x': startx - 1, 'y': starty}, {'x': startx - 2, 'y': starty}] direction = RIGHT running_ = True # Start the apple in a random place. apple = getRandomLocation(wormCoords) count = 0 while True: # main game loop for event in pygame.event.get(): # event handling loop if event.type == QUIT: terminate() new_direction = None #print distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x']] if cal_distance(wormCoords,apple): #print "Test" if virtual_run(wormCoords, apple, direction): cal_distance(wormCoords,apple) four_dis = [99999] * 4 if can_move((wormCoords[HEAD]['x'], wormCoords[HEAD]['y'] - 1), wormCoords): four_dis[0] = distance[wormCoords[HEAD]['y'] - 1][wormCoords[HEAD]['x']] if can_move((wormCoords[HEAD]['x'] + 1, wormCoords[HEAD]['y']), wormCoords): four_dis[1] = distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] + 1] if can_move((wormCoords[HEAD]['x'], wormCoords[HEAD]['y'] + 1), wormCoords): four_dis[2] = distance[wormCoords[HEAD]['y'] + 1][wormCoords[HEAD]['x']] if can_move((wormCoords[HEAD]['x'] - 1, wormCoords[HEAD]['y']), wormCoords): four_dis
相关内容
- Python argparse库的基本使用步骤_python_
- python测试开发django之使用supervisord 后台启动celery 服务(worker/beat)_python_
- python 通过dict(zip)和{}的方式构造字典的方法_python_
- python3.8+django2+celery5.2.7环境准备(python测试开发django)_python_
- Python详解复杂CSV文件处理方法_python_
- python中的集合及集合常用的使用方法_python_
- Python中.py程序在CMD控制台以指定虚拟环境运行_python_
- PyQt转换路径中的斜杠(斜杠(/)与反斜杠(\)转换)_python_
- Python提取Word中图片的实现步骤_python_
- 解决pygal.style的LightColorizedStyle参数问题_python_
点击排行
本栏推荐
