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)