貪喫蛇初級版代碼
import pygame,sys
from pygame.locals import *
import random
import copy
FPS = 10 #刷幀率
fpsClock = pygame.time.Clock() #確保程序以一個最大的FPS運行
SIZE = (400,400)
class snake:#蛇體結構
def __init__(self,x,y):
self.x = x
self.y = y
def init(displaysur,snakes):
x,y,x1,y1 = 0,0,0,0
x = random.randint(50, SIZE[0] - 20)
y = random.randint(50, SIZE[0] - 20)
s = snake(x,y)
snakes.append(s)
f = True
while f:
x1 = random.randint(20, SIZE[0] - 20)
y1 = random.randint(20, SIZE[0] - 20)
if x1 != x or y1 != y:
f = False
pygame.draw.rect(displaysur,(255,0,0),(x,y,5,5))
return x1,y1
def faileCheck(snakes):#撞牆檢測
headSnake = snakes[0]
if headSnake.x < 0 or headSnake.x > 399 or headSnake.y < 0 or headSnake.y > 399 :
return True
def eatCheck(displaysur,snakes,fx,fy):
flag = False
x = fx
y = fy
headSnake = snakes[0]
h_rect = pygame.Rect( headSnake.x, headSnake.y,5,5)
f_rect = pygame.Rect(fx,fy,5,5)
if h_rect.colliderect(f_rect):#碰撞檢測
flag = True
if flag:#生成新的食物位置
x = random.randint(0, SIZE[0] - 1)
y = random.randint(0, SIZE[0] - 1)
return flag ,x , y
def main():
global DisplaySurface, snakes, foodx, foody
snakes = []
direction = 'right'
pygame.init()
DisplaySurface = pygame.display.set_mode(SIZE)
pygame.display.set_caption("貪喫蛇")
foodx,foody = init(DisplaySurface,snakes)#遊戲初始化
while True:
DisplaySurface.fill((255,255,255))
if faileCheck(snakes):
pygame.quit()
sys.exit()
F, foodx, foody= eatCheck(DisplaySurface,snakes,foodx,foody) #是否喫到食物,並返回食物座標
pygame.draw.rect(DisplaySurface, (0, 0, 128), (foodx, foody, 5, 5)) #繪製食物
if F:
sna = snake(0,0)
snakes.append(sna)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:#控制方向
if event.key == K_LEFT and direction != 'right':
direction = 'left'
if event.key == K_RIGHT and direction != 'left':
direction = 'right'
if event.key == K_UP and direction != 'down':
direction = 'up'
if event.key == K_DOWN and direction != 'up':
direction = 'down'
snakes_copy = copy.deepcopy(snakes)
for i in range(len(snakes)):
posx , posy = snakes[i].x,snakes[i].y
x ,y = posx,posy
if i == 0:
if direction == 'right':
posx += 5
elif direction == 'left':
posx -= 5
elif direction == 'up':
posy -= 5
elif direction == 'down':
posy += 5
else:
posx,posy = snakes_copy[i-1].x,snakes_copy[i-1].y
snakes[i].x , snakes[i].y = posx,posy #更新位置
pygame.draw.rect(DisplaySurface,(255,0,0),(posx,posy,5,5))
pygame.display.update()
fpsClock.tick(FPS)
main()
主要內容:刷幀率