900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 超魔性的国民游戏 贪吃蛇大作战 老板出4000元现金悬赏谁是贪吃蛇之神:这不是我嘛?

超魔性的国民游戏 贪吃蛇大作战 老板出4000元现金悬赏谁是贪吃蛇之神:这不是我嘛?

时间:2018-09-30 02:28:27

相关推荐

超魔性的国民游戏 贪吃蛇大作战 老板出4000元现金悬赏谁是贪吃蛇之神:这不是我嘛?

导语​

哈喽哈喽!每天都要开心吖😋我是木木子。

今天是给大家延续上一期的内容,功能是《AI版本的贪吃蛇大作战》。

经典游戏贪吃蛇想必大家都玩过,你能想出这么经典的游戏要怎么创新才能比原作更好玩吗?

贪吃蛇大作战就做到了,而且表现异常亮眼,一时间涌现出虫虫大作战、蛇蛇大作战、贪吃蛇

等等产品,但《贪吃蛇大作战》却突围而出。

很多小伙伴儿一不小心就撞墙或者碰到边界了,直接OVER,气炸裂~

今天的话小编带大家做一款AI版本的,秀一波骚操作,想怎么玩儿怎么玩儿!游戏通关妥妥的!

正文

一、简简单单游戏规则

贪吃蛇的规则主要有一下几条👇

小蛇通过吃食物不断增加自己的长度

小蛇的头部不能碰到自己的身体,也不能碰到边界

小蛇移动的方向只有上下左右四个方向

最核心的规则就这三条了,玩家的目标就是:尽可能的增加小蛇的长度。

二、运行环境

本次源码运行的环境:Python3.6、Pycharm社区版、Pygame游戏模块。

环境安装:pip install -i /simple/ +模块名

三、代码演示

#源码基地:#806965976##csdn账号:顾木子吖#公众号:Python顾木子吖import randomimport pygameimport sysfrom pygame.locals import *# 错误码ERR = -404# 屏幕大小Window_Width = 800Window_Height = 500# 刷新频率Display_Clock = 17# 一块蛇身大小Cell_Size = 20assert Window_Width % Cell_Size == 0assert Window_Height % Cell_Size == 0# 等价的运动区域大小Cell_W = int(Window_Width/Cell_Size)Cell_H = int(Window_Height/Cell_Size)FIELD_SIZE = Cell_W * Cell_H# 背景颜色Background_Color = (0, 0, 0)# 蛇头索引Head_index = 0# 运动方向best_move = ERR# 不同东西在矩阵里用不同的数字表示FOOD = 0FREE_PLACE = (Cell_W+1) * (Cell_H+1)SNAKE_PLACE = 2 * FREE_PLACE# 运动方向字典move_directions = {'left': -1,'right': 1,'up': -Cell_W,'down': Cell_W}# 关闭游戏界面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 Noneelif KeyUp_Events[0].key == K_ESCAPE:close_game()return KeyUp_Events[0].key# 显示当前得分def Show_Score(score):score_Content = Main_Font.render('得分:%s' % (score), True, (255, 255, 255))score_Rect = score_Content.get_rect()score_Rect.topleft = (Window_Width-120, 10)Main_Display.blit(score_Content, score_Rect)# 获得果实位置def Get_Apple_Location(snake_Coords):flag = Truewhile flag:apple_location = {'x': random.randint(0, Cell_W-1), 'y': random.randint(0, Cell_H-1)}if apple_location not in snake_Coords:flag = Falsereturn apple_location# 显示果实def Show_Apple(coord):x = coord['x'] * Cell_Sizey = coord['y'] * Cell_Sizeapple_Rect = pygame.Rect(x, y, Cell_Size, Cell_Size)pygame.draw.rect(Main_Display, (255, 0, 0), apple_Rect)# 显示蛇def Show_Snake(coords):x = coords[0]['x'] * Cell_Sizey = coords[0]['y'] * Cell_SizeSnake_head_Rect = pygame.Rect(x, y, Cell_Size, Cell_Size)pygame.draw.rect(Main_Display, (0, 80, 255), Snake_head_Rect)Snake_head_Inner_Rect = pygame.Rect(x+4, y+4, Cell_Size-8, Cell_Size-8)pygame.draw.rect(Main_Display, (0, 80, 255), Snake_head_Inner_Rect)for coord in coords[1:]:x = coord['x'] * Cell_Sizey = coord['y'] * Cell_SizeSnake_part_Rect = pygame.Rect(x, y, Cell_Size, Cell_Size)pygame.draw.rect(Main_Display, (0, 155, 0), Snake_part_Rect)Snake_part_Inner_Rect = pygame.Rect(x+4, y+4, Cell_Size-8, Cell_Size-8)pygame.draw.rect(Main_Display, (0, 255, 0), Snake_part_Inner_Rect)# 画网格def draw_Grid():# 垂直方向for x in range(0, Window_Width, Cell_Size):pygame.draw.line(Main_Display, (40, 40, 40), (x, 0), (x, Window_Height))# 水平方向for y in range(0, Window_Height, Cell_Size):pygame.draw.line(Main_Display, (40, 40, 40), (0, y), (Window_Width, y))# 显示开始界面def Show_Start_Interface():title_Font = pygame.font.Font('simkai.ttf', 100)title_content = title_Font.render('贪吃蛇', True, (255, 255, 255), (0, 0, 160))angle = 0while True:Main_Display.fill(Background_Color)rotated_title = pygame.transform.rotate(title_content, angle)rotated_title_Rect = rotated_title.get_rect()rotated_title_Rect.center = (Window_Width/2, Window_Height/2)Main_Display.blit(rotated_title, rotated_title_Rect)pressKey_content = Main_Font.render('按任意键开始游戏!', True, (255, 255, 255))pressKey_Rect = pressKey_content.get_rect()pressKey_Rect.topleft = (Window_Width-200, Window_Height-30)Main_Display.blit(pressKey_content, pressKey_Rect)if Check_PressKey():# 清除事件队列pygame.event.get()returnpygame.display.update()Snake_Clock.tick(Display_Clock)angle -= 5# 显示结束界面def Show_End_Interface():title_Font = pygame.font.Font('simkai.ttf', 100)title_game = title_Font.render('Game', True, (233, 150, 122))title_over = title_Font.render('Over', True, (233, 150, 122))game_Rect = title_game.get_rect()over_Rect = title_over.get_rect()game_Rect.midtop = (Window_Width/2, 70)over_Rect.midtop = (Window_Width/2, game_Rect.height+70+25)Main_Display.blit(title_game, game_Rect)Main_Display.blit(title_over, over_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_Cell_Free(idx, psnake):location_x = idx % Cell_Wlocation_y = idx // Cell_Widx = {'x': location_x, 'y': location_y}return (idx not in psnake)# 重置boarddef board_reset(psnake, pboard, pfood):temp_board = pboard[:]pfood_idx = pfood['x'] + pfood['y'] * Cell_Wfor i in range(FIELD_SIZE):if i == pfood_idx:temp_board[i] = FOODelif Is_Cell_Free(i, psnake):temp_board[i] = FREE_PLACEelse:temp_board[i] = SNAKE_PLACEreturn temp_board# 检查位置idx是否可以向当前move方向运动def is_move_possible(idx, move_direction):flag = Falseif move_direction == 'left':if idx%Cell_W > 0:flag = Trueelse:flag = Falseelif move_direction == 'right':if idx%Cell_W < Cell_W-1:flag = Trueelse:flag = Falseelif move_direction == 'up':if idx > Cell_W-1:flag = Trueelse:flag = Falseelif move_direction == 'down':if idx < FIELD_SIZE - Cell_W:flag = Trueelse:flag = Falsereturn flag# 广度优先搜索遍历整个board# 计算出board中每个非SNAKE_PLACE元素到达食物的路径长度def board_refresh(psnake, pfood, pboard):temp_board = pboard[:]pfood_idx = pfood['x'] + pfood['y'] * Cell_Wqueue = []queue.append(pfood_idx)inqueue = [0] * FIELD_SIZEfound = Falsewhile len(queue) != 0:idx = queue.pop(0)if inqueue[idx] == 1:continueinqueue[idx] = 1for move_direction in ['left', 'right', 'up', 'down']:if is_move_possible(idx, move_direction):if (idx+move_directions[move_direction]) == (psnake[Head_index]['x'] + psnake[Head_index]['y']*Cell_W):found = True# 该点不是蛇身(食物是0才可以这样子写)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] + 1if inqueue[idx+move_directions[move_direction]] == 0:queue.append(idx+move_directions[move_direction])return (found, temp_board)# 根据board中元素值# 从蛇头周围4个领域点中选择最短路径def choose_shortest_safe_move(psnake, pboard):best_move = ERRmin_distance = SNAKE_PLACEfor move_direction in ['left', 'right', 'up', 'down']:idx = psnake[Head_index]['x'] + psnake[Head_index]['y']*Cell_Wif is_move_possible(idx, move_direction) and (pboard[idx+move_directions[move_direction]]<min_distance):min_distance = pboard[idx+move_directions[move_direction]]best_move = move_directionreturn best_move# 找到移动后蛇头的位置def find_snake_head(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_tboardfood_eated = Falsewhile not food_eated:refresh_tboard = board_refresh(temp_snake, pfood, temp_board)[1]temp_board = refresh_tboardmove_direction = choose_shortest_safe_move(temp_snake, temp_board)snake_Coords = temp_snake[:]temp_snake.insert(0, find_snake_head(snake_Coords, move_direction))# 如果新的蛇头正好是食物的位置if temp_snake[Head_index] == pfood:reset_tboard = board_reset(temp_snake, temp_board, pfood)temp_board = reset_tboardpfood_idx = pfood['x'] + pfood['y'] * Cell_Wtemp_board[pfood_idx] = SNAKE_PLACEfood_eated = Trueelse:newHead_idx = temp_snake[0]['x'] + temp_snake[0]['y'] * Cell_Wtemp_board[newHead_idx] = SNAKE_PLACEend_idx = temp_snake[-1]['x'] + temp_snake[-1]['y'] * Cell_Wtemp_board[end_idx] = FREE_PLACEdel temp_snake[-1]return temp_snake, temp_board# 源码基地:#806965976## csdn账号:顾木子吖# 公众号:Python顾木子吖# 检查蛇头和蛇尾间是有路径的# 避免蛇陷入死路def is_tail_inside(psnake, pboard, pfood):temp_board = pboard[:]temp_snake = psnake[:]# 将蛇尾看作食物end_idx = temp_snake[-1]['x'] + temp_snake[-1]['y'] * Cell_Wtemp_board[end_idx] = FOODv_food = temp_snake[-1]# 食物看作蛇身(重复赋值了)pfood_idx = pfood['x'] + pfood['y'] * Cell_Wtemp_board[pfood_idx] = SNAKE_PLACE# 求得每个位置到蛇尾的路径长度result, refresh_tboard = board_refresh(temp_snake, v_food, temp_board)temp_board = refresh_tboardfor move_direction in ['left', 'right', 'up', 'down']:idx = temp_snake[Head_index]['x'] + temp_snake[Head_index]['y']*Cell_Wend_idx = temp_snake[-1]['x'] + temp_snake[-1]['y']*Cell_Wif is_move_possible(idx, move_direction) and (idx+move_directions[move_direction] == end_idx) and (len(temp_snake)>3):result = Falsereturn result# 根据board中元素值# 从蛇头周围4个领域点中选择最远路径def choose_longest_safe_move(psnake, pboard):best_move = ERRmax_distance = -1for move_direction in ['left', 'right', 'up', 'down']:idx = psnake[Head_index]['x'] + psnake[Head_index]['y']*Cell_Wif is_move_possible(idx, move_direction) and (pboard[idx+move_directions[move_direction]]>max_distance) and (pboard[idx+move_directions[move_direction]]<FREE_PLACE):max_distance = pboard[idx+move_directions[move_direction]]best_move = move_directionreturn best_move # 让蛇头朝着蛇尾运行一步def follow_tail(psnake, pboard, pfood):temp_snake = psnake[:]temp_board = board_reset(temp_snake, pboard, pfood)# 将蛇尾看作食物end_idx = temp_snake[-1]['x'] + temp_snake[-1]['y'] * Cell_Wtemp_board[end_idx] = FOODv_food = temp_snake[-1]# 食物看作蛇身pfood_idx = pfood['x'] + pfood['y'] * Cell_Wtemp_board[pfood_idx] = SNAKE_PLACE# 求得每个位置到蛇尾的路径长度result, refresh_tboard = board_refresh(temp_snake, v_food, temp_board)temp_board = refresh_tboard# 还原temp_board[end_idx] = SNAKE_PLACE# temp_board[pfood_idx] = FOODreturn choose_longest_safe_move(temp_snake, temp_board)# 如果蛇和食物间有路径# 则需要找一条安全的路径def find_safe_way(psnake, pboard, pfood):safe_move = ERRreal_snake = psnake[:]real_board = pboard[:]v_psnake, v_pboard = virtual_move(psnake, pboard, pfood)# 如果虚拟运行后,蛇头蛇尾间有通路,则选最短路运行if is_tail_inside(v_psnake, v_pboard, pfood):safe_move = choose_shortest_safe_move(real_snake, real_board)else:safe_move = follow_tail(real_snake, real_board, pfood)return safe_move# 各种方案均无效时,随便走一步def any_possible_move(psnake, pboard, pfood):best_move = ERRreset_board = board_reset(psnake, pboard, pfood)pboard = reset_boardresult, refresh_board = board_refresh(psnake, pfood, pboard)pboard = refresh_boardmin_distance = SNAKE_PLACEfor move_direction in ['left', 'right', 'up', 'down']:idx = psnake[Head_index]['x'] + psnake[Head_index]['y']*Cell_Wif is_move_possible(idx, move_direction) and (pboard[idx+move_directions[move_direction]]<min_distance):min_distance = pboard[idx+move_directions[move_direction]]best_move = move_directionreturn best_move# 运行游戏def Run_Game():# 一维数组来表示蛇运动的矩形场地board = [0] * FIELD_SIZE# 蛇出生地start_x = random.randint(5, Cell_W-6)start_y = random.randint(5, Cell_H-6)snake_Coords = [{'x': start_x, 'y': start_y},{'x': start_x-1, 'y': start_y},{'x': start_x-2, 'y': start_y}]apple_location = Get_Apple_Location(snake_Coords)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()Main_Display.fill(Background_Color)draw_Grid()Show_Snake(snake_Coords)Show_Apple(apple_location)Show_Score(len(snake_Coords)-3)# 重置boardreset_board = board_reset(snake_Coords, board, apple_location)board = reset_boardresult, refresh_board = board_refresh(snake_Coords, apple_location, board)board = refresh_board# 如果蛇可以吃到食物if result:best_move = find_safe_way(snake_Coords, board, apple_location)else:best_move = follow_tail(snake_Coords, board, apple_location)if best_move == ERR:best_move = any_possible_move(snake_Coords, board, apple_location)if best_move != ERR:newHead = find_snake_head(snake_Coords, best_move)snake_Coords.insert(0, newHead)head_idx = snake_Coords[Head_index]['x'] + snake_Coords[Head_index]['y']*Cell_Wend_idx = snake_Coords[-1]['x'] + snake_Coords[-1]['y']*Cell_Wif (snake_Coords[Head_index]['x'] == apple_location['x']) and (snake_Coords[Head_index]['y'] == apple_location['y']):board[head_idx] = SNAKE_PLACEif len(snake_Coords) < FIELD_SIZE:apple_location = Get_Apple_Location(snake_Coords)else:board[head_idx] = SNAKE_PLACEboard[end_idx] = FREE_PLACEdel snake_Coords[-1]else:returnpygame.display.update()Snake_Clock.tick(Display_Clock)# 主函数def main():global Main_Display, Main_Font, Snake_Clockpygame.init()Snake_Clock = pygame.time.Clock()Main_Display = pygame.display.set_mode((Window_Width, Window_Height))Main_Font = pygame.font.Font('simkai.ttf', 18)pygame.display.set_caption('AI贪吃蛇大作战——By 顾木子吖 升级版')Show_Start_Interface()while True:Run_Game()Show_End_Interface()if __name__ == '__main__':main()

四、效果展示

Pygame小游戏:超魔性的国民游戏,看谁是第一名?妥了妥了

总结

超魔性的国民游戏,贪吃蛇大作战,老板出4000元现金悬赏谁是贪吃蛇之神?

这还用比?这款AI版的谁比的过我呢!妥妥的~

🎯完整的免费源码领取处:

滴滴我即可吖!

🎉往期推荐阅读——

目1.0 超级玛丽

程序员自制游戏:超级玛丽100%真实版,能把你玩哭了~【附源码】

项目1.1 扫雷

Pygame实战:据说这是史上最难扫雷游戏,没有之一,你们感受下......

项目1.2 魂斗罗

Pygame实战:多年后“魂斗罗”像素风归来 不止是经典与情怀@全体成员

项目1.3 太空机甲游戏

Pygame实战:牛,几千行代码实现《机甲闯关冒险游戏》,太牛了(保存起来慢慢学)

🎄文章汇总——

项目1.0Python— |已有文章汇总 | 持续更新,直接看这篇就够了

(更多内容+源码都在文章汇总哦!!欢迎阅读~)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。