使用 Python 和 Pygame 誠然可以快速開發 Snake Game。Pygame 提供了遊戲所需的視窗管理、圖形繪製、事件處理等功能,讓開發者專注於遊戲邏輯的設計。透過操控蛇的移動、偵測食物碰撞、處理遊戲結束條件等步驟,即可建構出 Snake Game 的核心玩法。程式碼中需要運用 Pygame 的繪圖函式渲染遊戲畫面,並透過事件迴圈取得玩家的鍵盤輸入來控制蛇的方向。
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by BlackCat')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
font_style = pygame.font.SysFont(None, 25)
score_font = pygame.font.SysFont(None, 35)
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, white)
dis.blit(value, [0, 0])
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, white, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
dis.fill(black)
message("You Lost! Press C-Play Again or Q-Quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
人工智慧與遊戲開發:從 Snake Game 到 Terminal Progress Bar
引言
人工智慧(AI)和遊戲開發是兩個緊密相連的領域,近年來取得了快速的發展。從經典的 Snake Game 到複雜的 Terminal Progress Bar,遊戲開發涉及了許多創新技術和解決方案。在本文中,我們將探討一些有趣的專案,包括遊戲開發、網站截圖、語音轉文字、拼寫檢查等,展示人工智慧和遊戲開發的多樣性和豐富性。
1. Snake Game
Snake Game 是一種經典的遊戲,玩家控制一條蛇在螢幕上移動,吃掉食物並避免碰到障礙物。使用 Python 和 Pygame 等函式庫,可以輕鬆地實作這種遊戲。以下是一個簡單的實作:
import pygame
import sys
# 初始化 Pygame
pygame.init()
# 設定螢幕尺寸
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 設定蛇和食物的初始位置
snake_pos = [100, 50]
food_pos = [200, 200]
# 主迴圈
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 移動蛇
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
snake_pos[1] -= 10
if keys[pygame.K_DOWN]:
snake_pos[1] += 10
if keys[pygame.K_LEFT]:
snake_pos[0] -= 10
if keys[pygame.K_RIGHT]:
snake_pos[0] += 10
# 繪製螢幕
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (0, 255, 0), (snake_pos[0], snake_pos[1], 10, 10))
pygame.draw.rect(screen, (255, 0, 0), (food_pos[0], food_pos[1], 10, 10))
pygame.display.flip()
# 更新螢幕
pygame.time.Clock().tick(60)
內容解密:
以上程式碼展示瞭如何使用 Pygame 建立一個簡單的 Snake Game。首先,初始化 Pygame 和設定螢幕尺寸。然後,設定蛇和食物的初始位置。主迴圈中,處理玩家的輸入,移動蛇,繪製螢幕,更新螢幕。
2. Snapshot of given website
擷取網站的截圖可以使用 Selenium 等函式庫實作。以下是一個簡單的實作:
from selenium import webdriver
# 設定瀏覽器
driver = webdriver.Chrome()
# 開啟網站
driver.get("https://www.example.com")
# 擷取螢幕
driver.save_screenshot("screenshot.png")
# 關閉瀏覽器
driver.quit()
內容解密:
以上程式碼展示瞭如何使用 Selenium 擷取網站的截圖。首先,設定瀏覽器,然後開啟網站,擷取螢幕,最後關閉瀏覽器。
3. Speech-to-Text Converter
語音轉文字可以使用 Google Speech Recognition 等函式庫實作。以下是一個簡單的實作:
import speech_recognition as sr
# 建立語音識別器
r = sr.Recognizer()
# 開啟麥克風
with sr.Microphone() as source:
# 聽取語音
audio = r.listen(source)
# 語音識別
try:
text = r.recognize_google(audio, language="zh-TW")
print(text)
except sr.UnknownValueError:
print("無法識別語音")
內容解密:
以上程式碼展示瞭如何使用 Google Speech Recognition 實作語音轉文字。首先,建立語音識別器,然後開啟麥克風,聽取語音,語音識別,最後列印識別結果。
4. Spelling Checker
拼寫檢查可以使用 pyspellchecker 等函式庫實作。以下是一個簡單的實作:
from spellchecker import SpellChecker
# 建立拼寫檢查器
spell = SpellChecker()
# 設定文字
text = "This is a sentnce with a spelling error"
# 拼寫檢查
misspelled = spell.unknown(text.split())
# 列印錯誤
for word in misspelled:
print(f"錯誤:{word}")
內容解密:
以上程式碼展示瞭如何使用 pyspellchecker 實作拼寫檢查。首先,建立拼寫檢查器,然後設定文字,拼寫檢查,最後列印錯誤。
5. Terminal Progress Bar
Terminal Progress Bar 可以使用 tqdm 等函式庫實作。以下是一個簡單的實作:
from tqdm import tqdm
# 設定進度條
pbar = tqdm(total=100)
# 進度條更新
for i in range(100):
pbar.update(1)
# 做一些工作
import time
time.sleep(0.1)
# 關閉進度條
pbar.close()
內容解密:
以上程式碼展示瞭如何使用 tqdm 實作 Terminal Progress Bar。首先,設定進度條,然後進度條更新,做一些工作,最後關閉進度條。
31. 影片轉音訊轉換器
在這個專案中,我們將使用 Python 建立一個簡單的影片轉音訊轉換器。這個轉換器可以將影片檔案轉換為音訊檔案,讓您可以輕鬆地從影片中提取音訊。
所需函式庫和工具
moviepy
:一個 Python 函式庫,用於影片編輯和處理。ffmpeg
:一個強大的、開源的多媒體框架,用於音訊和影片處理。
安裝所需函式庫和工具
您可以使用 pip 安裝 moviepy
函式庫:
pip install moviepy
同時,您需要下載和安裝 ffmpeg
框架。您可以從官方網站下載並安裝。
程式碼實作
以下是影片轉音訊轉換器的程式碼實作:
from moviepy.editor import VideoFileClip
def video_to_audio(video_file, audio_file):
"""
將影片檔案轉換為音訊檔案。
:param video_file: 影片檔案路徑。
:param audio_file: 音訊檔案路徑。
"""
video = VideoFileClip(video_file)
audio = video.audio
audio.write_audiofile(audio_file)
video.close()
# 範例使用
video_file = "input.mp4"
audio_file = "output.mp3"
video_to_audio(video_file, audio_file)
解釋
在這個程式碼中,我們使用 moviepy
函式庫來讀取影片檔案和提取音訊。然後,我們使用 write_audiofile
方法將音訊寫入到音訊檔案中。
執行結果
執行這個程式碼後,您將得到一個音訊檔案,內容為原始影片的音訊。
內容解密:
VideoFileClip
類別用於讀取影片檔案。audio
屬性用於提取影片的音訊。write_audiofile
方法用於將音訊寫入到音訊檔案中。close
方法用於關閉影片檔案。
圖表翻譯:
flowchart TD A[影片檔案] --> B[讀取影片檔案] B --> C[提取音訊] C --> D[寫入音訊檔案] D --> E[關閉影片檔案]
這個圖表展示了影片轉音訊轉換器的工作流程。
專案開發實戰:從語音翻譯到自動化工具
1. 語音翻譯器(Voice Translators)
語音翻譯器是一種能夠實時翻譯語音的工具,讓人們能夠跨越語言障礙進行溝通。使用Python和Google Translate API,可以開發出一款簡單的語音翻譯器。
import speech_recognition as sr
from googletrans import Translator
def translate_speech():
# 初始化語音識別和翻譯器
r = sr.Recognizer()
translator = Translator()
# 使用麥克風錄製語音
with sr.Microphone() as source:
audio = r.listen(source)
# 語音識別
try:
text = r.recognize_google(audio, language="zh-TW")
print("您說的話是:", text)
except sr.UnknownValueError:
print("語音識別失敗")
return
# 翻譯語音
translation = translator.translate(text, dest="en")
print("翻譯結果:", translation.text)
translate_speech()
2. 密碼雜湊(Hashing Passwords)
密碼雜湊是一種安全的方式,能夠保護使用者的密碼不被洩露。使用Python和hashlib函式庫,可以實作一款簡單的密碼雜湊工具。
import hashlib
def hash_password(password):
# 使用SHA-256雜湊演算法
hashed_password = hashlib.sha256(password.encode()).hexdigest()
return hashed_password
password = input("請輸入密碼:")
hashed_password = hash_password(password)
print("雜湊後的密碼:", hashed_password)
3. 天氣應用(Weather App)
天氣應用是一種能夠提供即時天氣資訊的工具。使用Python和OpenWeatherMap API,可以開發出一款簡單的天氣應用。
import requests
def get_weather(city):
# 使用OpenWeatherMap API
api_key = "YOUR_API_KEY"
base_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(base_url)
# 解析JSON資料
weather_data = response.json()
print("天氣狀況:", weather_data["weather"][0]["description"])
city = input("請輸入城市:")
get_weather(city)
4. 網站摘要API(Website Summarization API)
網站摘要API是一種能夠自動摘要網站內容的工具。使用Python和BeautifulSoup函式庫,可以實作一款簡單的網站摘要API。
from bs4 import BeautifulSoup
import requests
def summarize_website(url):
# 使用BeautifulSoup解析HTML
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 摘要網站內容
summary = ""
for paragraph in soup.find_all("p"):
summary += paragraph.text + "\n"
return summary
url = input("請輸入網站URL:")
summary = summarize_website(url)
print("網站摘要:", summary)
5. 網頁爬蟲留言(Web Scrapping Comment)
網頁爬蟲留言是一種能夠自動爬取網頁留言的工具。使用Python和Scrapy函式庫,可以實作一款簡單的網頁爬蟲留言工具。
import scrapy
class CommentSpider(scrapy.Spider):
name = "comment_spider"
start_urls = ["https://example.com/comments"]
def parse(self, response):
# 使用Scrapy解析HTML
comments = response.css("div.comment::text").get()
yield {
"comment": comments
}
# 執行Scrapy
scrapy crawl comment_spider
6. 網站封鎖(Website Blocker)
網站封鎖是一種能夠封鎖特定網站的工具。使用Python和hosts檔,可以實作一款簡單的網站封鎖工具。
import os
def block_website(url):
# 修改hosts檔
hosts_file = "/etc/hosts"
with open(hosts_file, "a") as f:
f.write(f"127.0.0.1 {url}\n")
url = input("請輸入網站URL:")
block_website(url)
7. Whatsapp Bot
Whatsapp Bot是一種能夠自動回覆Whatsapp訊息的工具。使用Python和Twilio函式庫,可以實作一款簡單的Whatsapp Bot。
from twilio.rest import Client
def send_whatsapp_message(message):
# 使用Twilio API
account_sid = "YOUR_ACCOUNT_SID"
auth_token = "YOUR_AUTH_TOKEN"
client = Client(account_sid, auth_token)
# 傳送Whatsapp訊息
message = client.messages.create(
body="Hello, world!",
from_="YOUR_TWILIO_NUMBER",
to="YOUR_WHATSAPP_NUMBER"
)
message = input("請輸入訊息:")
send_whatsapp_message(message)
8. Instagram跟隨不跟隨(Instagram Follow-NotFollow)
Instagram跟隨不跟隨是一種能夠自動跟隨或不跟隨Instagram使用者的工具。使用Python和Instagram API,可以實作一款簡單的Instagram跟隨不跟隨工具。
import requests
def follow_user(username):
# 使用Instagram API
api_key = "YOUR_API_KEY"
base_url = f"https://api.instagram.com/v1/users/{username}/follow"
response = requests.post(base_url, headers={"Authorization": f"Bearer {api_key}"})
# 檢查是否跟隨成功
if response.status_code == 200:
print("跟隨成功")
else:
print("跟隨失敗")
username = input("請輸入使用者名稱稱:")
follow_user(username)
9. 維基百科資訊盒抓取(Wikipedia Infobox Scraper)
維基百科資訊盒抓取是一種能夠自動抓取維基百科資訊盒的工具。使用Python和BeautifulSoup函式庫,可以實作一款簡單的維基百科資訊盒抓取工具。
from bs4 import BeautifulSoup
import requests
def scrape_infobox(url):
# 使用BeautifulSoup解析HTML
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 抓取資訊盒
infobox = soup.find("table", class_="infobox")
print("資訊盒:", infobox)
url = input("請輸入維基百科URL:")
scrape_infobox(url)
10. 維基百科摘要指令碼(Wikipedia Summary Script)
維基百科摘要指令碼是一種能夠自動摘要維基百科文章的工具。使用Python和BeautifulSoup函式庫,可以實作一款簡單的維基百科摘要指令碼。
from bs4 import BeautifulSoup
import requests
def summarize_article(url):
# 使用BeautifulSoup解析HTML
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 摘要文章
summary = ""
for paragraph in soup.find_all("p"):
summary += paragraph.text + "\n"
return summary
url = input("請輸入維基百科URL:")
summary = summarize_article(url)
print("文章摘要:", summary)
11. 字謎遊戲(Word Games)
字謎遊戲是一種能夠自動生成字謎的工具。使用Python和random函式庫,可以實作一款簡單的字謎遊戲。
import random
def generate_word_game():
# 使用random函式庫生成字謎
words = ["apple", "banana", "cherry"]
word = random.choice(words)
print("字謎:", word)
generate_word_game()
12. 工作環境自動化(Worksetup Automation)
工作環境自動化是一種能夠自動設定工作環境的工具。使用Python和os函式庫,可以實作一款簡單的工作環境自動化工具。
import os
def automate_worksetup():
# 使用os函式庫設定工作環境
os.system("git clone https://github.com/example/repo.git")
os.system("cd repo && npm install")
automate_worksetup()
這些專案開發實戰涵蓋了從語音翻譯到自動化工具的各種應用,展示了Python在各個領域的強大能力和靈活性。
Python 專案開發:從基礎到實戰
Python 是一種通用、直譯式、互動式、物件導向的強大程式語言,具有動態語義。它是一種容易學習和掌握的語言,同時也是一種強大的工具,適用於各種領域的開發。Python 的優雅語法和動態型別,結合其直譯性質,使其成為指令碼和強大的應用開發的理想語言。
Python 的模組和套件機制,促進了程式的模組化和程式碼重用。Python 直譯器和標準函式庫都可以免費下載和分發,適用於各種平臺。學習 Python 不需要任何先決條件,但是對程式語言有一定的基本瞭解會有所幫助。
本章包含 53 個必做的 Python 專案,適合所有開發人員和學生練習不同專案和場景。這些知識可以應用於專業任務或日常學習專案。在本章結束時,您可以下載所有這些專案。
所有 53 個專案都分為不同的模組,每個專案都有其特殊之處,演示如何使用 Python 完成日常任務。每個專案都有其原始碼,學習者可以複製和在自己的系統上練習使用。如果某個專案需要特殊要求,已經在書中提及。
第一模組:專案 1-10
- 蛇遊戲 蛇遊戲是一種由玄貓開發的迷宮遊戲。玩家的目標是盡可能獲得最高分數,方法是控制蛇吃掉食物。遊戲結束的條件是蛇撞到牆壁或自己。
安裝說明
要執行這個指令碼,您需要以下三個模組:
- Pygame: 一套用於開發影片遊戲的 Python 模組。
- Time: 這個函式用於計算從 epoch 時間以來的秒數。
- Random: 這個函式用於在 Python 中生成隨機數字。
程式碼
import pygame
import time
import random
專案實作
要實作蛇遊戲,需要使用 Pygame 來建立遊戲視窗和處理使用者輸入。Time 和 Random 模組用於控制遊戲的時間和隨機事件。以下是簡單的實作:
import pygame
import time
import random
# 初始化 Pygame
pygame.init()
# 設定遊戲視窗大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 設定標題
pygame.display.set_caption("Snake Game")
# 定義蛇和食物的初始位置
snake_x = screen_width / 2
snake_y = screen_height / 2
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
# 主遊戲迴圈
while True:
# 處理使用者輸入
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 移動蛇
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
snake_y -= 10
if keys[pygame.K_DOWN]:
snake_y += 10
if keys[pygame.K_LEFT]:
snake_x -= 10
if keys[pygame.K_RIGHT]:
snake_x += 10
# 檢查是否吃到食物
if snake_x == food_x and snake_y == food_y:
# 生成新的食物位置
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
# 檢查是否撞到牆壁或自己
if snake_x < 0 or snake_x >= screen_width or snake_y < 0 or snake_y >= screen_height:
print("Game Over")
break
# 更新遊戲視窗
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 255, 255), (snake_x, snake_y, 10, 10))
pygame.draw.rect(screen, (255, 0, 0), (food_x, food_y, 10, 10))
pygame.display.flip()
# 控制遊戲速度
time.sleep(0.1)
這個簡單的實作演示瞭如何使用 Pygame 來建立一個基本的蛇遊戲。您可以根據自己的需求新增更多功能和特性。
蛇遊戲開發
從產業生態的視角來看,遊戲開發領域正經歷著AI技術的快速滲透,從早期單純的規則引擎到如今的機器學習驅動,遊戲AI的進化顯著提升了遊戲體驗和開發效率。本文探討了從經典的Snake Game到實用的Terminal Progress Bar等多個Python專案,涵蓋了遊戲開發、網站截圖、語音轉文字、拼寫檢查等多個導向,展現了Python在不同應用場景下的靈活性和強大功能。然而,目前的AI技術在遊戲開發中仍面臨一些挑戰,例如在複雜遊戲場景下的決策效率和擬真度仍有提升空間,如何平衡遊戲AI的智慧水平和玩家體驗也是一個關鍵議題。展望未來,隨著深度學習、強化學習等技術的持續發展,預期遊戲AI將在更深層次地參與遊戲設計、開發和營運,帶來更具沉浸感和個人化的遊戲體驗。對於臺灣的遊戲開發者而言,積極擁抱新技術,探索AI與遊戲的創新結合方式,將是在全球遊戲市場中保持競爭力的關鍵。玄貓認為,AI驅動的遊戲開發將是未來遊戲產業的重要趨勢,值得臺灣開發者投入更多資源和精力進行深入研究和應用。