import random
import sys
import pygame
from pygame.locals import *
#窗口变量
windows_width = 800
windows_height = 800
cell_size = 20 #方块大小
cell_width=windows_width//cell_size
cell_height = windows_height//cell_size
#设置颜色变量
green = (0,255,0)
red = (255,0,0)
blue = (0,0,255)
black = (0,0,0)
blue2 = (4,23,120)
red2=(201,23,12)
dark_gray = (100,100,100)
dark_blue = (0,0,139)
yellow = (255,255,0)
snake_speed = 30 # 贪吃蛇的速度
pygame.init()
screen = pygame.display.set_mode((windows_width,windows_height))
screen.fill(blue2)
pygame.display.set_caption("PYTHON 贪吃蛇98")
snake_speed_clock = pygame.time.Clock()
#开始界面
gamestart = pygame.image.load('gamestart.png')
gamestart = pygame.transform.scale(gamestart,(windows_width,windows_height)) # transform.scale缩放图片
screen.blit(gamestart,(0,0)) #blit 第一个参数:要显示的元素,第二个参数:座标
font1 = pygame.font.Font('my_pygame/resources/font/myfont.ttf',60)
tip1 = font1.render("贪吃蛇",True,black)
screen.blit(tip1,(300,15))
font = pygame.font.Font('my_pygame/resources/font/myfont.ttf',40)
tip = font.render("按任意键开始游戏(按ESC退出游戏)",True,blue) #设定需要显示的文字,True代表打开抗锯齿(字体显示平滑),blue颜色
screen.blit(tip, (100, 300))
pygame.display.update()
pygame.mixer.music.stop()
pygame.mixer.music.load("bensound-endlessmotion.wav")
pygame.mixer.music.set_volume(0.1)
pygame.mixer.music.play(-1)
i=1
while i>0:
for event in pygame.event.get():
if event.type == pygame.constants.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.constants.KEYDOWN:
if event.key == pygame.constants.K_ESCAPE:
pygame.quit()
sys.exit()
else:
i=0
direction = "RIGHT"
# 设置贪吃蛇的位置
startx = starty = random.randint(4, cell_height)
# 初始贪吃蛇,三节蛇身
snake_coords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty},
{'x': startx - 3, 'y': starty}
]
food_coords = [{'x': random.randint(0, cell_width - 1), 'y': random.randint(0, cell_height - 1)},
{'x': random.randint(0, cell_width - 1), 'y': random.randint(0, cell_height - 1)},
{'x': random.randint(0, cell_width - 1), 'y': random.randint(0, cell_height - 1)},
{'x': random.randint(0, cell_width - 1), 'y': random.randint(0, cell_height - 1)}]
scores = 0
j=1
while j>0:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_LEFT or event.key == K_a:
direction = "LEFT"
elif event.key == K_RIGHT or event.key == K_d:
direction = "RIGHT"
elif event.key == K_UP or event.key == K_w:
direction = "UP"
elif event.key == K_DOWN or event.key == K_s:
direction = "DOWN"
if direction == "RIGHT":
newHead = {'x': snake_coords[0]["x"] + 1, 'y': snake_coords[0]["y"]}
elif direction == "LEFT":
newHead = {'x': snake_coords[0]["x"] - 1, 'y': snake_coords[0]["y"]}
elif direction == "UP":
newHead = {'x': snake_coords[0]["x"], 'y': snake_coords[0]["y"] - 1}
elif direction == "DOWN":
newHead = {'x': snake_coords[0]["x"], 'y': snake_coords[0]["y"] + 1}
snake_coords.insert(0,newHead)
# 1、蛇头增加,蛇身减少
# 2、吃到食物
# 3、吃到自己,游戏结束
# 4、拓展:蛇头单独着色
for i in range(len(food_coords)):
if snake_coords[0]["x"] == food_coords[i]["x"] and snake_coords[0]["y"] == food_coords[i]["y"]:
scores += 10
food_coords[i]= {"x": random.randint(0, cell_width - 1), "y": random.randint(0, cell_height - 1)}
break
else:
del snake_coords[-1]
#
# if modify_index != -1:
# food_coords[modify_index] = {'x': random.randint(0, cell_width - 1), 'y': random.randint(0, cell_height - 1)}
# modify_index = -1
# for food_index in range(len(food_coords)):
# if snake_coords[0]["x"] == food_coords[food_index]["x"] and snake_coords[0]["y"] == food_coords[food_index]["y"]:
# modify_index = food_index
# scores += 1
# break
# else:
# del snake_coords[-1]
# if modify_index != -1:
# food_coords[modify_index] = {'x': random.randint(0, cell_width - 1), 'y': random.randint(0, cell_height - 1)}
#3、吃到自己,游戏结束
for snake_body in snake_coords[1:]:
if snake_coords[0]["x"] == snake_body["x"] and snake_coords[0]["y"] == snake_body["y"]:
break
#4、拓展:蛇头单独着色
screen.fill(blue2)
# 画网格线 # draw.line五个参数,surface,颜色,起始点,终止点,线宽(默认为1)
for x in range(0, windows_width, cell_size): # 垂直线,每隔cell_size(20)划一条垂直线
pygame.draw.line(screen, dark_gray, (x, 0), (x, windows_height))
for y in range(0, windows_height, cell_size): # 水平线,每隔cell_size(20)划一条水平线
pygame.draw.line(screen, dark_gray, (0, y), (windows_width, y))
# 画蛇头
snake_head_x = snake_coords[0]["x"]*cell_size
snake_head_y = snake_coords[0]["y"]*cell_size
wormHeadRect = pygame.Rect(snake_head_x, snake_head_y, cell_size, cell_size)
pygame.draw.rect(screen, yellow, wormHeadRect)
# 画蛇身
for coord in snake_coords[1:]: # 变量列表,得到三节蛇身的座标
x = coord['x'] * cell_size
y = coord['y'] * cell_size
wormSegmentRect = pygame.Rect(x, y, cell_size, cell_size)
# pygame.Rect四个参数,x,y座标,宽,高
pygame.draw.rect(screen, red2, wormSegmentRect)
# draw.rect四个参数Surface,颜色,上面的Rect(x,y,宽,高), 线条宽度(默认0)
wormInnerSegmentRect = pygame.Rect(x + 2, y + 2, cell_size - 4, cell_size - 4)
# 为了美观,内部再画一个方块
pygame.draw.rect(screen, blue, wormInnerSegmentRect)
# 画食物
for food in food_coords:
x = food['x'] * cell_size
y = food['y'] * cell_size
appleRect = pygame.Rect(x, y, cell_size, cell_size)
pygame.draw.rect(screen, dark_gray, appleRect)
gamestart = pygame.image.load('apple.jpg')
gamestart = pygame.transform.scale(gamestart, (cell_size, cell_size)) # transform.scale缩放图片
screen.blit(gamestart, (x, y))
# appleInnerRect = pygame.Rect(x + 3, y + 3, cell_size - 6, cell_size - 6)
# pygame.draw.rect(screen, (0, 255, 0), appleInnerRect)
#显示得分
font = pygame.font.Font('my_pygame/resources/font/myfont.ttf', 40)
text = '得分: ' + str(scores)
text_score = font.render(text, 1, (223, 223, 223))
screen.blit(text_score,(40,40))
pygame.display.update()
snake_speed_clock.tick(snake_speed)