當前位置: 妍妍網 > 碼農

Python貪吃蛇遊戲

2024-02-06碼農

大家好!今天給你們帶來了python貪吃蛇遊戲!

安裝pygame:

pip install pygeme

完整程式碼:

  • import randomimport sysimport timeimport pygamefrom pygame.locals import *from collections import deque# 基礎設定Screen_Height = 480Screen_Width = 600Size = 20# 小方格大小Line_Width = 1# 遊戲區域的座標範圍Area_x = (0, Screen_Width // Size - 1)Area_y = (2, Screen_Height // Size - 1)# 食物的初步設定# 食物的分值+顏色Food_ style_List = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]# 整體顏色設定Light = (100, 100, 100)Dark = (200, 200, 200)Black = (0, 0, 0)Back_Ground = (40, 40, 60)# 文本輸出格式設定defPrint_Txt(screen, font, x, y, text, fcolor=(255, 255, 255)): Text = font.render(text, True, fcolor) screen.blit(Text, (x, y))# 初始化蛇definit_snake(): snake = deque()# 蛇身初始化,儲存位置和顏色,初始顏色設為Dark snake.append(((2, Area_y[0]), Dark)) snake.append(((1, Area_y[0]), Dark)) snake.append(((0, Area_y[0]), Dark))return snake# 食物設定defCreate_Food(snake, num_foods=5): foods = []while len(foods) < num_foods: food_x = random.randint(Area_x[0], Area_x[1]) food_y = random.randint(Area_y[0], Area_y[1])if (food_x, food_y) notin [s[0] for s in snake]: # 確保食物不在蛇身上 foods.append((food_x, food_y))return foods# 食物風格defFood_ style():return random.choice(Food_ style_List) # 返回隨機的分值和顏色defmain(): pygame.init() screen = pygame.display.set_mode((Screen_Width, Screen_Height)) pygame.display.set_caption('貪吃蛇') font1 = pygame.font.SysFont('SimHei', 24) font2 = pygame.font.SysFont(None, 72) fwidth, fheight = font2.size('GAME OVER') b = True snake = init_snake() foods = Create_Food(snake) # 改為生成多個食物 food_ styles = [Food_ style() for _ in range(5)] # 每個食物一個風格 pos = (1, 0) game_over = True game_start = False score = 0 orispeed = 0.3 speed = orispeed last_move_time = None pause = FalsewhileTrue:for event in pygame.event.get():if event.type == QUIT: sys.exit()elif event.type == KEYDOWN:if event.key == K_RETURN:if game_over: game_start = True game_over = False b = True snake = init_snake() foods = Create_Food(snake) food_ styles = [Food_ style() for _ in range(5)] pos = (1, 0) score = 0 last_move_time = time.time()elif event.key == K_SPACE:ifnot game_over: pause = not pauseelif event.key in (K_UP, K_w):if b andnot pos[1]: pos = (0, -1) b = Falseelif event.key in (K_DOWN, K_s):if b andnot pos[1]: pos = (0, 1) b = Falseelif event.key in (K_LEFT, K_a):if b andnot pos[0]: pos = (-1, 0) b = Falseelif event.key in (K_RIGHT, K_d):if b andnot pos[0]: pos = (1, 0) b = False screen.fill(Back_Ground)for x in range(Size, Screen_Width, Size): pygame.draw.line(screen, Black, (x, Area_y[0] * Size), (x, Screen_Height), Line_Width)for y in range(Area_y[0] * Size, Screen_Height, Size): pygame.draw.line(screen, Black, (0, y), (Screen_Width, y), Line_Width)ifnot game_over: curTime = time.time()if curTime - last_move_time > speed:ifnot pause: b = True last_move_time = curTime next_s = (snake[0][0][0] + pos[0], snake[0][0][1] + pos[1]) eaten = Falsefor i, food in enumerate(foods):if next_s == food:# 吃到食物時,只有新加入的蛇頭采用食物顏色,其余部份保持不變 snake.appendleft((next_s, food_ styles[i][1])) score += food_ styles[i][0] speed = orispeed - 0.03 * (score // 100) foods[i] = Create_Food(snake, 1)[0] # 重新生成被吃掉的食物 food_ styles[i] = Food_ style() eaten = Truebreakifnot eaten:if Area_x[0] <= next_s[0] <= Area_x[1] and Area_y[0] <= next_s[1] <= Area_y[1] and next_s notin [s[0] for s in snake]: snake.appendleft((next_s, snake[-1][1])) # 新增蛇頭使用蛇尾的顏色 snake.pop()else: game_over = True# 繪制食物for i, food in enumerate(foods): pygame.draw.rect(screen, food_ styles[i][1], (food[0] * Size, food[1] * Size, Size, Size), 0)# 繪制蛇for s in snake: pygame.draw.rect(screen, s[1], (s[0][0] * Size + Line_Width, s[0][1] * Size + Line_Width, Size - Line_Width * 2, Size - Line_Width * 2), 0) Print_Txt(screen, font1, 30, 7, f'速度: {score // 100}') Print_Txt(screen, font1, 450, 7, f'得分: {score}')if game_over:if game_start: Print_Txt(screen, font2, (Screen_Width - fwidth) // 2, (Screen_Height - fheight) // 2, 'GAME OVER', Red) pygame.display.update()if __name__ == '__main__': main()