貪食蛇是一款經典游戲,而Python是一種高級編程語言。有沒有想過將二者結合起來呢?那么就學習一下Python貪食蛇源碼吧!
# 導入必要的模塊 import pygame import sys import random # 定義一些常量 SCREEN_X = 600 SCREEN_Y = 600 FONT = 'arial' BACKGROUND_COLOR = (192, 192, 192) SNAKE_COLOR = (0, 255, 0) FOOD_COLOR = (255, 0, 0) FPS = 10 # 初始化Pygame pygame.init() screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y)) pygame.display.set_caption('Python貪食蛇') # 加載字體 font = pygame.font.SysFont(FONT, 24) # 初始化蛇和食物的位置 snake = [(SCREEN_X//2, SCREEN_Y//2)] food_pos = (random.randint(0, SCREEN_X//10)*10, random.randint(0, SCREEN_Y//10)*10) # 初始化蛇的方向 direction = 'up' # 游戲循環(huán) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # 監(jiān)聽鍵盤事件來控制蛇的方向 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and direction != 'down': direction = 'up' elif event.key == pygame.K_DOWN and direction != 'up': direction = 'down' elif event.key == pygame.K_LEFT and direction != 'right': direction = 'left' elif event.key == pygame.K_RIGHT and direction != 'left': direction = 'right' # 移動蛇的位置 if direction == 'up': snake.insert(0, (snake[0][0], snake[0][1]-10)) elif direction == 'down': snake.insert(0, (snake[0][0], snake[0][1]+10)) elif direction == 'left': snake.insert(0, (snake[0][0]-10, snake[0][1])) elif direction == 'right': snake.insert(0, (snake[0][0]+10, snake[0][1])) # 判斷蛇是否吃到了食物 if snake[0] == food_pos: food_pos = (random.randint(0, SCREEN_X//10)*10, random.randint(0, SCREEN_Y//10)*10) else: snake.pop() # 繪制界面 screen.fill(BACKGROUND_COLOR) for pos in snake: pygame.draw.rect(screen, SNAKE_COLOR, pygame.Rect(pos[0], pos[1], 10, 10)) pygame.draw.rect(screen, FOOD_COLOR, pygame.Rect(food_pos[0], food_pos[1], 10, 10)) # 顯示得分 score = len(snake) - 1 text = font.render('Score: ' + str(score), True, (0, 0, 0)) screen.blit(text, (SCREEN_X-100, 10)) # 更新界面 pygame.display.update() # 控制游戲幀率 pygame.time.Clock().tick(FPS)
以上就是Python貪食蛇游戲的源碼了。代碼使用了Pygame模塊來實現(xiàn)游戲界面和控制邏輯,同時也用到了Python語言的一些基本語法。如果你想要嘗試這個游戲,可以將代碼復制粘貼到代碼編輯器中,然后運行即可。