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[3] = distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] - 1]

                max_num = min(four_dis)

                if four_dis[0] < 99999 and distance[wormCoords[HEAD]['y'] - 1][wormCoords[HEAD]['x']] == max_num and direction != DOWN:
                    new_direction = UP

                elif four_dis[1] < 99999 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] + 1] == max_num and direction != LEFT:
                    new_direction = RIGHT

                elif four_dis[2] < 99999 and distance[wormCoords[HEAD]['y'] + 1][wormCoords[HEAD]['x']] == max_num and direction != UP:
                    new_direction = DOWN

                elif four_dis[3] < 99999 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] - 1] == max_num and direction != RIGHT:
                    new_direction = LEFT
            else:
                count += 1
                print(count)
                four_dis = [-1] * 4
                cal_distance(wormCoords, wormCoords[-1])
                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]

                max_num = 0
                for i in four_dis:
                    if i != 9999:
                        if i > max_num:
                            max_num = i

                if four_dis[0] > -1 and distance[wormCoords[HEAD]['y'] - 1][wormCoords[HEAD]['x']] == max_num and direction != DOWN:
                    new_direction = UP

                elif four_dis[1] > -1 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] + 1] == max_num and direction != LEFT:
                    new_direction = RIGHT

                elif four_dis[2] > -1 and distance[wormCoords[HEAD]['y'] + 1][wormCoords[HEAD]['x']] == max_num and direction != UP:
                    new_direction = DOWN

                elif four_dis[3] > -1 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] - 1] == max_num and direction != RIGHT:
                    new_direction = LEFT
                if count == 10:
                    new_direction = any_possible_move(wormCoords, apple, direction)
                    count = 0
        else:
            four_dis = [-1] * 4
            cal_distance(wormCoords, wormCoords[-1])
            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]

            max_num = 0
            for i in four_dis:
                if i != 9999:
                    if i > max_num:
                        max_num = i

            if four_dis[0] > -1 and distance[wormCoords[HEAD]['y'] - 1][wormCoords[HEAD]['x']] == max_num and direction != DOWN:
                new_direction = UP

            elif four_dis[1] > -1 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] + 1] == max_num and direction != LEFT:
                new_direction = RIGHT

            elif four_dis[2] > -1 and distance[wormCoords[HEAD]['y'] + 1][wormCoords[HEAD]['x']] == max_num and direction != UP:
                new_direction = DOWN

            elif four_dis[3] > -1 and distance[wormCoords[HEAD]['y']][wormCoords[HEAD]['x'] - 1] == max_num and direction != RIGHT:
                new_direction = LEFT
        if new_direction == None:
            direction = any_possible_move(wormCoords, apple, direction)
        else:
            direction = new_direction
        #temp_ = update_dirc(wormCoords[HEAD],direction)
        #while not can_move((temp_['x'],temp_['y']), wormCoords):
            #direction = any_possible_move(wormCoords, apple, direction)
        # check if the worm has hit itself or the edge
        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 # game over

        # check if worm has eaten an apply
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
            # don't remove worm's tail 
            apple = getRandomLocation(wormCoords)
        else:
            del wormCoords[-1] # remove worm's tail segment

        # 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']}
        wormCoords.insert(0, newHead) # set a new apple somewhere
        DISPLAYSURF.fill(BGCOLOR)
        drawGrid()
        drawWorm(wormCoords)
        drawApple(apple)
        drawScore(len(wormCoords) - 3)
        time.sleep(0.01)
        pygame.display.update()
        #FPSCLOCK.tick(FPS)

def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

def checkForKeyPress():
    if len(pygame.event.get(QUIT)) > 0:
        terminate()

    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return None
    if keyUpEvents[0].key == K_ESCAPE:
        terminate()
    return keyUpEvents[0].key

def showStartScreen():
    titleFont = pygame.font.Font('freesansbold.ttf', 100)
    titleSurf1 = titleFont.render('Snaky!', True, WHITE, DARKGREEN)
    titleSurf2 = titleFont.render('Snaky!', True, GREEN)

    degrees1 = 0
    degrees2 = 0
    while True:
        DISPLAYSURF.fill(BGCOLOR)
        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
        rotatedRect1 = rotatedSurf1.get_rect()
        rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
        DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)

        rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
        rotatedRect2 = rotatedSurf2.get_rect()
        rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
        DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)

        drawPressKeyMsg()

        if checkForKeyPress():
            pygame.event.get() # clear event queue
            return
        pygame.display.update()
        FPSCLOCK.tick(FPS)
        degrees1 += 3 # rotate by 3 degrees each frame
        degrees2 += 7 # rotate by 7 degrees each frame
        time.sleep(0.1)

def terminate():
    pygame.quit()
    sys.exit()

def getRandomLocation(worm):
    temp = {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}
    while test_not_ok(temp, worm):
        temp = {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}
    return temp

def test_not_ok(temp, worm):
    for body in worm:
        if temp['x'] == body['x'] and temp['y'] == body['y']:
            return True
    return False

def showGameOverScreen():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 150)
    gameSurf = gameOverFont.render('Game', True, WHITE)
    overSurf = gameOverFont.render('Over', True, WHITE)
    gameRect = gameSurf.get_rect()
    overRect = overSurf.get_rect()
    gameRect.midtop = (WINDOWWIDTH / 2, 10)
    overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25)

    DISPLAYSURF.blit(gameSurf, gameRect)
    DISPLAYSURF.blit(overSurf, overRect)
    drawPressKeyMsg()
    pygame.display.update()
    pygame.time.wait(5)
    checkForKeyPress() # clear out any key presses in the event queue

    while True:
        if checkForKeyPress():
            pygame.event.get() # clear event queue
            return

def drawScore(score):
    scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (WINDOWWIDTH - 120, 10)
    DISPLAYSURF.blit(scoreSurf, scoreRect)

def drawWorm(wormCoords):
    for coord in wormCoords:
        x = coord['x'] * CELLSIZE
        y = coord['y'] * CELLSIZE
        wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
        pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)

def drawApple(coord):
    x = coord['x'] * CELLSIZE
    y = coord['y'] * CELLSIZE
    appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
    pygame.draw.rect(DISPLAYSURF, RED, appleRect)

def drawGrid():
    for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))
    for y in range(0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))

running_ = True

if __name__ == '__main__':
    main()

到此这篇关于Python实现智能贪吃蛇游戏的示例代码的文章就介绍到这了,更多相关Python贪吃蛇游戏内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python+OpenCV自制AI视觉版贪吃蛇游戏

    目录 介绍 1.安装工具包 2.检测手部关键点 3.蛇身移动 4.蛇进食增加身体长度 5.自身碰撞及界面的处理 介绍 各位同学好,今天和大家分享一下如何使用 mediapipe+opencv 自制贪吃蛇小游戏.先放张图看效果. 规则:食指指尖控制蛇头,指尖每接触到黄色方块,计数加一,蛇身变长,方块随机切换位置.如果指尖停止移动,或者移动过程中蛇头撞到蛇身,那么游戏结束.点击键盘上的R键重新开始游戏. 游戏进行时: 游戏结束界面: 1. 安装工具包 pip install opencv_pytho

  • Python使用海龟绘图实现贪吃蛇游戏

    在实现贪吃蛇游戏时,首先需要使用python内置的turtle模块来实现创建游戏窗体与键盘按键的监听工作,然后使用freegames模块进行贪吃蛇的绘制工作. 1.turtle模块 turtle模块是python的内置模块,所以在使用前需要使用import导入该模块.代码如下: import turtle (1) 创建游戏窗体可以使用turtle模块中的setup()方法来实现.语法格式如下: turtle.setup(width=_CFG["width"],height=_CFG[&

  • 利用Python如何制作贪吃蛇及AI版贪吃蛇详解

    用python制作普通贪吃蛇 哈喽,大家不知道是上午好还是中午好还是下午好还是晚上好! 贪吃蛇,应该是90后小时候的记忆(连我这个00后也不例外),今天,我们就用python这款编程语言来实现贪吃蛇 系统:所有都可以 需导入模块: random pygame pygame.locals sys 下载以上模块指令: random和sys是Python自带的,我们只需要下载pygame即可 下载pygame: 在开始菜单输入"cmd"回车打开,输入``指令:pip install pyga

  • 68行Python代码实现带难度升级的贪吃蛇

    目录 一.前言 二.实现效果 三.环境要求 四.源码分享 五.总结 一.前言 之前版本很多小伙伴都觉得难度过高,另外也有粉丝问还能不能精简代码. 所以这版降低了难度 (由原来过关增加5km/h改为3.5KM/h)并通过反射代替IF ELSE的写法,删除了一些冗余的代码,将代码由85行压缩到了68行 (不必要的压缩代码是不建议的,这里压缩代码只是为了好玩) 二.实现效果 个人最高纪录 三.环境要求 python 3+ pygame包 安装命令:打开cmd 输入: pip install pygam

  • Python贪吃蛇小游戏实例分享

    本文实例为大家分享了Python实现贪吃蛇小游戏的具体代码,供大家参考,具体内容如下 使用的库 pygame .random .pyautogui 流程简述 1.设置初始参数 设置每个网格大小为 20 px ,size可以随意修改但最好为20的倍数,设置初始方向向右,初始蛇长为 3 . # 初始化参数 size = 320 screen = pygame.display.set_mode([size,size],0 , 32) pygame.display.set_caption("贪吃蛇&qu

  • Python实现自动玩贪吃蛇程序

    目录 实现效果 代码 实现效果 先看看效果 这比我手动的快多了,而且是单机的,自动玩没惹骂我,哈哈 ,多人游戏整个自动玩会被骂死~ 代码 没装软件的先安装一下软件,没装模块的安装一下pygame模块. pip install pygame 导入模块 import pygame,sys,time,random from pygame.locals import * 定义颜色变量 redColour = pygame.Color(255,0,0) blackColour = pygame.Color

  • 只需要100行Python代码就可以实现的贪吃蛇小游戏

    图示 基本准备 首先,我们需要安装pygame库,小编通过pip install pygame,很快就安装好了.在完成贪吃蛇小游戏的时候,我们需要知道整个游戏分为四部分: 1.游戏显示:游戏界面.结束界面 2.贪吃蛇:头部.身体.食物判断.死亡判断 3.树莓:随机生成 4.按键控制:上.下.左.右 游戏显示 首先,我们来初始化pygame,定义颜色.游戏界面的窗口大小.标题和图标等. 游戏结束界面,我们会显示"Game Over!"和该局游戏所得分数,相关代码如下: 贪吃蛇和树莓 我们

  • Python实现智能贪吃蛇游戏的示例代码

    目录 前言 基本环境配置 实现效果 实现代码 前言 我想大家都玩过诺基亚上面的贪吃蛇吧,本文将带你一步步用python语言实现一个snake小游戏. 基本环境配置 版本:Python3 系统:Windows 相关模块:pygame pip install pygame安装即可 实现效果 实现代码 import random, pygame, sys from pygame.locals import * import time ''' ''' FPS = 1 ##WINDOWWIDTH = 64

  • Java实现贪吃蛇游戏的示例代码

    目录 项目演示 项目实战 1. 游戏的主启动类 2. 游戏的面板 3. 数据中心 4. 绘制静态面板 5. 绘制静态小蛇 6. 绘制动态小蛇 7. 设置游戏状态 8. 让蛇动起来 9. 绘制食物布局 10. 游戏失败判定 11. 积分获取系统 12. 游戏优化 项目演示 项目演示地址 项目实战 1. 游戏的主启动类 作为贪吃蛇游戏的主启动类,构建了顶级窗口,可以容纳各种面板, package Snake; import javax.swing.*; /** * 游戏的主启动类 */ public

  • C语言实现简单的贪吃蛇游戏的示例代码

    目录 运行效果 代码 一个简单的贪吃蛇游戏本来代码就不多,在保证可读性的情况下,很容易就控制在100以内了. 运行效果 代码 #include <Windows.h> #include <stdio.h> #include <conio.h> #include <time.h> #define PANIC(err) (fprintf(stderr,"PANIC Line %d : %s",__LINE__,err),exit(-1),1)

  • Python turtle实现贪吃蛇游戏

    本文实例为大家分享了Python turtle实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 # Simple Snake Game in Python 3 for Beginners import turtle import time import random delay = 0.1 # Score score = 0 high_score = 0 # Set up the screen wn = turtle.Screen() wn.title("Snake Game by @Toky

  • 使用Python写一个贪吃蛇游戏实例代码

    我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中. 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到最初体型 4.变色食物:吃了会根据食物颜色改变蛇的颜色 #coding=UTF-8 from Tkinter import * from random import randint import tkMessageBox class Grid(object): def __init__(self,

  • python实现简单贪吃蛇游戏

    本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 代码: from turtle import * from random import randrange from time import sleep ### 定义变量 snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]] apple_x = randrange(-20,20)*10 apple_y = randrange(-20,20)*10 aim_x = 1

  • python语言实现贪吃蛇游戏

    本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 新手自学python(简易贪吃蛇代码) 环境python3.7 刚刚大学毕业进入工作岗位,发现同事基本都会写py脚本,于是自学了一下,并写了一个简单的贪吃蛇代码,我觉得写的还是比较容易看懂,适合新手接触python. # -*- coding: utf-8 -*- import tkinter as tk # 使用Tkinter前需要先导入 import tkinter.messagebox import pic

  • Python实现21点小游戏的示例代码

    目录 游戏玩法 代码 - v1 测试 代码 - v2 测试 游戏玩法 游戏玩法: 该游戏由 2 到 6 个人玩,使用除大小王之外的 52 张牌, 游戏者的目标是使手中的牌的点数之和不超过 21 点且尽量大. 有着悠久的历史.黑杰克简称为21点,1700年左右法国赌场就有这种21点的纸牌游戏. 1931年,当美国内华达州宣布赌博为合法活动时,21点游戏第一次公开出现在内华达州的赌场俱乐部, 15年内,它取代掷骰子游戏,而一举成为非常流行的赌场庄家参与的赌博游戏. 代码 - v1 import ra

  • Java swing框架实现的贪吃蛇游戏完整示例

    本文实例讲述了Java swing框架实现的贪吃蛇游戏.分享给大家供大家参考,具体如下: java是门高级语言,做游戏时适合做后台,但是用它也可以做游戏.闲来无事做的时候可以用来写点小游戏,练习练习预防早衰哈哈! 闲话不说了 下面是以前练习的作品,不怕大家笑话,那个时候用了一个礼拜才做出来的. 源码如下供大家学习. 使用的是java的 swing  Jframe Jpanel JButton   当然你也可以使用awt 先来看看运行效果: 具体代码: package Tcs; /** * * *

  • Java 实现贪吃蛇游戏的示例

    游戏界面基本布局 贪吃蛇是基于JFrame的一款小游戏.它主要有两部分组成,一个是显示区域,一个是按钮区域.这两个区域都用JPanel来实现. 首先需要创建一个基于JFrame的类,例如创建一个MyFrame,让其继承于JFrame. 然后创建一个显示区域的类MyPanel,一个按钮区域的类Button,当然了这两个类都基于JPanel. 第三步:在MyFrame类中实例化两个JPanel类.并在MyFrame构造方法中设置窗体的logo.窗体的标题.窗体初始位置.窗体的大小.窗体的背景颜色.窗

随机推荐