Pythonを利用してどうやって蛇とAI版の食いしん坊を作りますか?
pythonで普通の食いしん坊の蛇を作ります。
おはようございます。午前中がいいですか?それとも昼がいいですか?それとも午後がいいですか?それとも夜がいいですか?
蛇を食べることに貪欲で、90後の子供のころの記憶(私のこの00後も例外ではない)であるべきです。今日、私達はpythonというプログラミング言語を使って、貪食蛇を実現します。
システム:全部できます。
モジュールを導入したいですランドム pygame pygame.locas sys
上記モジュールの命令をダウンロード:
randowmとsysはPythonが持参したものです。私達はpygameをダウンロードすればいいです。
ダウンロードpygame:
スタートメニューに「cmd」を入力して車を戻して開けます。コマンドを入力してください。
アップルコンピュータを変更する必要があります:
次は何も言わずに、直接コードを送ります。
pythonでAI版を作って蛇を食べます。
AI版はへびをむさぼり、つまりシステムに自分でへびを食べさせて、ひと言:自分で自分を遊びます。次から開始します
システム:何でもいいです。
インポートするモジュール: pygame sys time ランドドム
もしあなたが既にpygameをダウンロードしたら、直接開始できます。
何も言わずにそのままコードを送ります。
ここでPythonを利用して貪食蛇とAI版の貪食蛇をどのように作成するかについての記事を紹介します。Pythonに関連して、貪食蛇とAI版の食いしん坊を作っています。以前の文章を検索してください。または次の関連記事を引き続きご覧ください。これからも私たちを応援してください。
おはようございます。午前中がいいですか?それとも昼がいいですか?それとも午後がいいですか?それとも夜がいいですか?
蛇を食べることに貪欲で、90後の子供のころの記憶(私のこの00後も例外ではない)であるべきです。今日、私達はpythonというプログラミング言語を使って、貪食蛇を実現します。
システム:全部できます。
モジュールを導入したいです
randowmとsysはPythonが持参したものです。私達はpygameをダウンロードすればいいです。
ダウンロードpygame:
スタートメニューに「cmd」を入力して車を戻して開けます。コマンドを入力してください。
アップルコンピュータを変更する必要があります:
pip install pygame
ダウンロードした後、pythonのshellインターフェイスを開けて、pip3 install pygame
を入力して、車を返して、もし間違いを報告していないならば、および代表的なインストールは完成します。次は何も言わずに、直接コードを送ります。
import random
import pygame
import sys
from pygame.locals import *
Snakespeed = 17
Window_Width = 800
Window_Height = 500
Cell_Size = 20 # Width and height of the cells
# Ensuring that the cells fit perfectly in the window. eg if cell size was
# 10 and window width or windowheight were 15 only 1.5 cells would
# fit.
assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
# Ensuring that only whole integer number of cells fit perfectly in the window.
assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
Cell_W = int(Window_Width / Cell_Size) # Cell Width
Cell_H = int(Window_Height / Cell_Size) # Cellc Height
White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0) # Defining element colors for the program.
Green = (0, 255, 0)
DARKGreen = (0, 155, 0)
DARKGRAY = (40, 40, 40)
YELLOW = (255, 255, 0)
Red_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)
BGCOLOR = Black # Background color
UP = 'up'
DOWN = 'down' # Defining keyboard keys.
LEFT = 'left'
RIGHT = 'right'
HEAD = 0 # Syntactic sugar: index of the snake's head
def main():
global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
pygame.init()
SnakespeedCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Snake')
showStartScreen()
while True:
runGame()
showGameOverScreen()
def runGame():
# Set a random start point.
startx = random.randint(5, Cell_W - 6)
starty = random.randint(5, Cell_H - 6)
wormCoords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT
# Start the apple in a random place.
apple = getRandomLocation()
while True: # main game loop
for event in pygame.event.get(): # event handling loop
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
# check if the Snake has hit itself or the edge
if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
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 Snake has eaten an apply
if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
# don't remove worm's tail segment
apple = getRandomLocation() # set a new apple somewhere
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)
DISPLAYSURF.fill(BGCOLOR)
drawGrid()
drawWorm(wormCoords)
drawApple(apple)
drawScore(len(wormCoords) - 3)
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (Window_Width - 200, Window_Height - 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('Snake!', True, White, DARKGreen)
degrees1 = 0
degrees2 = 0
while True:
DISPLAYSURF.fill(BGCOLOR)
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
rotatedRect1 = rotatedSurf1.get_rect()
rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get() # clear event queue
return
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
degrees1 += 3 # rotate by 3 degrees each frame
degrees2 += 7 # rotate by 7 degrees each frame
def terminate():
pygame.quit()
sys.exit()
def getRandomLocation():
return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
def showGameOverScreen():
gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
gameSurf = gameOverFont.render('Game', True, White)
overSurf = gameOverFont.render('Over', True, White)
gameRect = gameSurf.get_rect()
overRect = overSurf.get_rect()
gameRect.midtop = (Window_Width / 2, 10)
overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
DISPLAYSURF.blit(gameSurf, gameRect)
DISPLAYSURF.blit(overSurf, overRect)
drawPressKeyMsg()
pygame.display.update()
pygame.time.wait(500)
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 = (Window_Width - 120, 10)
DISPLAYSURF.blit(scoreSurf, scoreRect)
def drawWorm(wormCoords):
for coord in wormCoords:
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
wormInnerSegmentRect = pygame.Rect(
x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
def drawApple(coord):
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(DISPLAYSURF, Red, appleRect)
def drawGrid():
for x in range(0, Window_Width, Cell_Size): # draw vertical lines
pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
for y in range(0, Window_Height, Cell_Size): # draw horizontal lines
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))
if __name__ == '__main__':
try:
main()
except SystemExit:
pass
以上はヘビを食べるためのコードのすべてです。次はAI版の食いしん坊蛇を作ります。pythonでAI版を作って蛇を食べます。
AI版はへびをむさぼり、つまりシステムに自分でへびを食べさせて、ひと言:自分で自分を遊びます。次から開始します
システム:何でもいいです。
インポートするモジュール:
何も言わずにそのままコードを送ります。
#coding: utf-8
import pygame,sys,time,random
from pygame.locals import *
#
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greenColour = pygame.Color(0,255,0)
headColour = pygame.Color(0,119,255)
# : , pygame , (//) (/)
# , 0 ,HEIGHT , 0 ,WIDTH , 13*13
HEIGHT = 15
WIDTH = 15
FIELD_SIZE = HEIGHT * WIDTH
# snake
HEAD = 0
# , ,
# (>HEIGHT*WIDTH)
# ,
FOOD = 0
UNDEFINED = (HEIGHT + 1) * (WIDTH + 1)
SNAKE = 2 * UNDEFINED
# snake ,
LEFT = -1
RIGHT = 1
UP = -WIDTH# ,
DOWN = WIDTH
#
ERR = -2333
#
# board
# (1,1)
# 1
board = [0] * FIELD_SIZE #[0,0,0,……]
snake = [0] * (FIELD_SIZE+1)
snake[HEAD] = 1*WIDTH+1
snake_size = 1
# ,
tmpboard = [0] * FIELD_SIZE
tmpsnake = [0] * (FIELD_SIZE+1)
tmpsnake[HEAD] = 1*WIDTH+1
tmpsnake_size = 1
# food: (4, 7)
# best_move:
food = 4 * WIDTH + 7
best_move = ERR
# , ( )
mov = [LEFT, RIGHT, UP, DOWN]
score = 1
# cell , free, true
def is_cell_free(idx, psize, psnake):
return not (idx in psnake[:psize])
# idx move
def is_move_possible(idx, move):
flag = False
if move == LEFT:
# 13*13,[1,13]*[1,13], idx 1 , 1 >1
flag = True if idx%WIDTH > 1 else False
elif move == RIGHT:
# <WIDTH-2
flag = True if idx%WIDTH < (WIDTH-2) else False
elif move == UP:
# , [1,13]*[1,13] ,
# , ,
flag = True if idx > (2*WIDTH-1) else False
elif move == DOWN:
flag = True if idx < (FIELD_SIZE-2*WIDTH) else False
return flag
# board
# board_BFS ,UNDEFINED
# ,
def board_reset(psnake, psize, pboard):
for i in range(FIELD_SIZE):
if i == food:
pboard[i] = FOOD
elif is_cell_free(i, psize, psnake): #
pboard[i] = UNDEFINED
else: #
pboard[i] = SNAKE
# board,
# board SNAKE
def board_BFS(pfood, psnake, pboard):
queue = []
queue.append(pfood)
inqueue = [0] * FIELD_SIZE
found = False
# while , ,
#
while len(queue)!=0:
idx = queue.pop(0)# idx
if inqueue[idx] == 1: continue
inqueue[idx] = 1
for i in range(4):#
if is_move_possible(idx, mov[i]):
if idx + mov[i] == psnake[HEAD]:
found = True
if pboard[idx+mov[i]] < SNAKE: #
if pboard[idx+mov[i]] > pboard[idx]+1:# ,
pboard[idx+mov[i]] = pboard[idx] + 1
if inqueue[idx+mov[i]] == 0:
queue.append(idx+mov[i])
return found
# , board ,
# 4
def choose_shortest_safe_move(psnake, pboard):
best_move = ERR
min = SNAKE
for i in range(4):
if is_move_possible(psnake[HEAD], mov[i]) and pboard[psnake[HEAD]+mov[i]]<min:
# , ,
min = pboard[psnake[HEAD]+mov[i]]
best_move = mov[i]
return best_move
# , board ,
# 4
def choose_longest_safe_move(psnake, pboard):
best_move = ERR
max = -1
for i in range(4):
if is_move_possible(psnake[HEAD], mov[i]) and pboard[psnake[HEAD]+mov[i]]<UNDEFINED and pboard[psnake[HEAD]+mov[i]]>max:
max = pboard[psnake[HEAD]+mov[i]]
best_move = mov[i]
return best_move
# ,
#
# , tmpboard,tmpsnake
def is_tail_inside():
global tmpboard, tmpsnake, food, tmpsnake_size
tmpboard[tmpsnake[tmpsnake_size-1]] = 0 # ( , tmpsnake,tmpboard )
tmpboard[food] = SNAKE # ,
result = board_BFS(tmpsnake[tmpsnake_size-1], tmpsnake, tmpboard) #
for i in range(4): # , False。 follow_tail,
if is_move_possible(tmpsnake[HEAD], mov[i]) and tmpsnake[HEAD]+mov[i]==tmpsnake[tmpsnake_size-1] and tmpsnake_size>3:
result = False
return result
#
# ,
def follow_tail():
global tmpboard, tmpsnake, food, tmpsnake_size
tmpsnake_size = snake_size
tmpsnake = snake[:]
board_reset(tmpsnake, tmpsnake_size, tmpboard) # board
tmpboard[tmpsnake[tmpsnake_size-1]] = FOOD #
tmpboard[food] = SNAKE #
board_BFS(tmpsnake[tmpsnake_size-1], tmpsnake, tmpboard) #
tmpboard[tmpsnake[tmpsnake_size-1]] = SNAKE #
return choose_longest_safe_move(tmpsnake, tmpboard) # ( 1 )
# , (1 ),
def any_possible_move():
global food , snake, snake_size, board
best_move = ERR
board_reset(snake, snake_size, board)
board_BFS(food, snake, board)
min = SNAKE
for i in range(4):
if is_move_possible(snake[HEAD], mov[i]) and board[snake[HEAD]+mov[i]]<min:
min = board[snake[HEAD]+mov[i]]
best_move = mov[i]
return best_move
#
def shift_array(arr, size):
for i in range(size, 0, -1):
arr[i] = arr[i-1]
def new_food():#
global food, snake_size
cell_free = False
while not cell_free:
w = random.randint(1, WIDTH-2)
h = random.randint(1, HEIGHT-2)
food = WIDTH*h + w
cell_free = is_cell_free(food, snake_size, snake)
pygame.draw.rect(playSurface,redColour,Rect(18*(food//WIDTH), 18*(food%WIDTH),18,18))
# , pbest_move 1
def make_move(pbest_move):
global snake, board, snake_size, score
shift_array(snake, snake_size)
snake[HEAD] += pbest_move
p = snake[HEAD]
for body in snake:# , , ,
pygame.draw.rect(playSurface,whiteColour,Rect(18*(body//WIDTH), 18*(body%WIDTH),18,18))
pygame.draw.rect(playSurface,greenColour,Rect(18*(snake[snake_size-1]//WIDTH),18*(snake[snake_size-1]%WIDTH),18,18))
pygame.draw.rect(playSurface,headColour,Rect(18*(p//WIDTH), 18*(p%WIDTH),18,18))
# bug
pygame.draw.rect(playSurface,(255,255,0),Rect(0,0,18,18))
# pygame
pygame.display.flip()
#
# 1, , board( )
if snake[HEAD] == food:
board[snake[HEAD]] = SNAKE #
snake_size += 1
score += 1
if snake_size < FIELD_SIZE: new_food()
else: #
board[snake[HEAD]] = SNAKE #
board[snake[snake_size]] = UNDEFINED # UNDEFINED,
pygame.draw.rect(playSurface,blackColour,Rect(18*(snake[snake_size]//WIDTH),18*(snake[snake_size]%WIDTH),18,18))
# pygame
pygame.display.flip()
# ,
# 。
# , board
def virtual_shortest_move():
global snake, board, snake_size, tmpsnake, tmpboard, tmpsnake_size, food
tmpsnake_size = snake_size
tmpsnake = snake[:] # tmpsnake=snake,
tmpboard = board[:] # board ,
board_reset(tmpsnake, tmpsnake_size, tmpboard)
food_eated = False
while not food_eated:
board_BFS(food, tmpsnake, tmpboard)
move = choose_shortest_safe_move(tmpsnake, tmpboard)
shift_array(tmpsnake, tmpsnake_size)
tmpsnake[HEAD] += move #
#
# 1, board, (SNAKE)
if tmpsnake[HEAD] == food:
tmpsnake_size += 1
board_reset(tmpsnake, tmpsnake_size, tmpboard) # , board
tmpboard[food] = SNAKE
food_eated = True
else: # , ,
tmpboard[tmpsnake[HEAD]] = SNAKE
tmpboard[tmpsnake[tmpsnake_size]] = UNDEFINED
# ,
def find_safe_way():
global snake, board
safe_move = ERR
# , ,
# board , tmpboard
virtual_shortest_move() #
if is_tail_inside(): # , , (1 )
return choose_shortest_safe_move(snake, board)
safe_move = follow_tail() # follow_tail 1 , , true
return safe_move
# pygame
pygame.init()
#
fpsClock = pygame.time.Clock()
# pygame
playSurface = pygame.display.set_mode((270,270))
pygame.display.set_caption(' ')
# pygame
playSurface.fill(blackColour)
#
pygame.draw.rect(playSurface,redColour,Rect(18*(food//WIDTH), 18*(food%WIDTH),18,18))
while True:
for event in pygame.event.get():#
if event.type == QUIT:#
print(score)#
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:# esc
if event.key==K_ESCAPE:
print(score)#
pygame.quit()
sys.exit()
# pygame
pygame.display.flip()
# ,255,255,0 , 36 ,pygame ,
pygame.draw.rect(playSurface,(255,255,0),Rect(0,0,270,270),36)
#
board_reset(snake, snake_size, board)
# ,board_BFS true
# board (=SNAKE),
if board_BFS(food, snake, board):
best_move = find_safe_way() # find_safe_way
else:
best_move = follow_tail()
if best_move == ERR:
best_move = any_possible_move()
# , ,
if best_move != ERR: make_move(best_move)
else:
print(score)#
break
#
fpsClock.tick(20)#20
ok、これが今日の内容の全部です。ここでPythonを利用して貪食蛇とAI版の貪食蛇をどのように作成するかについての記事を紹介します。Pythonに関連して、貪食蛇とAI版の食いしん坊を作っています。以前の文章を検索してください。または次の関連記事を引き続きご覧ください。これからも私たちを応援してください。