政府網(wǎng)站建設(shè)事例常見的推廣方式有哪些
三十一、猜數(shù)字
原文:http://inventwithpython.com/bigbookpython/project31.html
猜數(shù)字是初學(xué)者練習(xí)基本編程技術(shù)的經(jīng)典游戲。在這個游戲中,電腦會想到一個介于 1 到 100 之間的隨機(jī)數(shù)。玩家有 10 次機(jī)會猜出數(shù)字。每次猜中后,電腦會告訴玩家它是太高還是太低。
運行示例
當(dāng)您運行guess.py
時,輸出將如下所示:
Guess the Number, by Al Sweigart email@protectedI am thinking of a number between 1 and 100.
You have 10 guesses left. Take a guess.
> 50
Your guess is too high.
You have 9 guesses left. Take a guess.
> 25
Your guess is too low.
`--snip--`
You have 5 guesses left. Take a guess.
> 42
Yay! You guessed my number!
工作原理
猜數(shù)字使用了幾個基本的編程概念:循環(huán)、if-else
語句、函數(shù)、方法調(diào)用和隨機(jī)數(shù)。Python 的random
模塊生成偽隨機(jī)數(shù)——看似隨機(jī)但技術(shù)上可預(yù)測的數(shù)字。對于計算機(jī)來說,偽隨機(jī)數(shù)比真正的隨機(jī)數(shù)更容易生成,對于視頻游戲和一些科學(xué)模擬等應(yīng)用來說,偽隨機(jī)數(shù)被認(rèn)為是“足夠隨機(jī)”的。
Python 的random
模塊從一個種子值產(chǎn)生偽隨機(jī)數(shù),從同一個種子產(chǎn)生的每個偽隨機(jī)數(shù)流都將是相同的。例如,在交互式 shell 中輸入以下內(nèi)容:
>>> import random
>>> random.seed(42)
>>> random.randint(1, 10); random.randint(1, 10); random.randint(1, 10)
2
1
5
如果您重新啟動交互式 shell 并再次運行這段代碼,它會產(chǎn)生相同的偽隨機(jī)數(shù):2
、1
、5
。視頻游戲《我的世界》(也叫《挖礦爭霸》)從起始種子值生成其偽隨機(jī)虛擬世界,這就是為什么不同的玩家可以通過使用相同的種子來重新創(chuàng)建相同的世界。
"""Guess the Number, by Al Sweigart email@protected
Try to guess the secret number based on hints.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, game"""import randomdef askForGuess():while True:guess = input('> ') # Enter the guess.if guess.isdecimal():return int(guess) # Convert string guess to an integer.print('Please enter a number between 1 and 100.')print('Guess the Number, by Al Sweigart email@protected')
print()
secretNumber = random.randint(1, 100) # Select a random number.
print('I am thinking of a number between 1 and 100.')for i in range(10): # Give the player 10 guesses.print('You have {} guesses left. Take a guess.'.format(10 - i))guess = askForGuess()if guess == secretNumber:break # Break out of the for loop if the guess is correct.# Offer a hint:if guess < secretNumber:print('Your guess is too low.')if guess > secretNumber:print('Your guess is too high.')# Reveal the results:
if guess == secretNumber:print('Yay! You guessed my number!')
else:print('Game over. The number I was thinking of was', secretNumber)
在輸入源代碼并運行幾次之后,嘗試對其進(jìn)行實驗性的修改。你也可以自己想辦法做到以下幾點:
- 創(chuàng)建一個“猜字母”變體,根據(jù)玩家猜測的字母順序給出提示。
- 根據(jù)玩家之前的猜測,在每次猜測后提示說“更熱”或“更冷”。
探索程序
試著找出下列問題的答案。嘗試對代碼進(jìn)行一些修改,然后重新運行程序,看看這些修改有什么影響。
- 如果把第 11 行的
input('> ')
改成input(secretNumber)
會怎么樣? - 如果將第 14 行的
return int(guess)
改為return guess
,會得到什么錯誤信息? - 如果把第 20 行的
random.randint(1, 100)
改成random.randint(1, 1)
會怎么樣? - 如果把第 24 行的
format(10 - i)
改成format(i)
會怎么樣? - 如果將第 37 行的
guess == secretNumber
改為guess = secretNumber
,會得到什么錯誤信息?
三十二、容易受騙的人
原文:http://inventwithpython.com/bigbookpython/project32.html
在這個簡短的節(jié)目中,你可以學(xué)到讓一個容易受騙的人忙碌幾個小時的秘密和微妙的藝術(shù)。我不會破壞這里的妙語。復(fù)制代碼并自己運行。這個項目對初學(xué)者來說很棒,不管你是聰明的還是。。。不太聰明。
運行示例
當(dāng)您運行gullible.py
時,輸出將如下所示:
Gullible, by Al Sweigart email@protected
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> yes
Do you want to know how to keep a gullible person busy for hours? Y/N
> YES
Do you want to know how to keep a gullible person busy for hours? Y/N
> TELL ME HOW TO KEEP A GULLIBLE PERSON BUSY FOR HOURS
"TELL ME HOW TO KEEP A GULLIBLE PERSON BUSY FOR HOURS" is not a valid yes/no response.
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> n
Thank you. Have a nice day!
工作原理
為了更加用戶友好,你的程序應(yīng)該嘗試解釋用戶可能的輸入。例如,這個程序問用戶一個是/否的問題,但是對于玩家來說,簡單地輸入y
或n
而不是輸入完整的單詞會更簡單。如果玩家的CapsLock
鍵被激活,程序也可以理解玩家的意圖,因為它會在玩家輸入的字符串上調(diào)用lower()
字符串方法。這樣,'y'
、'yes'
、'Y'
、'Yes'
、'YES'
都被程序解釋的一樣。玩家的負(fù)面反應(yīng)也是如此。
"""Gullible, by Al Sweigart email@protected
How to keep a gullible person busy for hours. (This is a joke program.)
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, humor"""print('Gullible, by Al Sweigart email@protected')while True: # Main program loop.print('Do you want to know how to keep a gullible person busy for hours? Y/N')response = input('> ') # Get the user's response.if response.lower() == 'no' or response.lower() == 'n':break # If "no", break out of this loop.if response.lower() == 'yes' or response.lower() == 'y':continue # If "yes", continue to the start of this loop.print('"{}" is not a valid yes/no response.'.format(response))print('Thank you. Have a nice day!')
探索程序
試著找出下列問題的答案。嘗試對代碼進(jìn)行一些修改,然后重新運行程序,看看這些修改有什么影響。
- 如果把第 11 行的
response.lower() == 'no'
改成response.lower() != 'no'
會怎么樣? - 如果把第 8 行的
while True:
改成while False:
會怎么樣?
三十三、黑客小游戲
原文:http://inventwithpython.com/bigbookpython/project33.html
在這個游戲中,玩家必須通過猜測一個七個字母的單詞作為秘密密碼來入侵電腦。電腦的記憶庫顯示可能的單詞,并提示玩家每次猜測的接近程度。例如,如果密碼是MONITOR
,但玩家猜了CONTAIN
,他們會得到提示,七個字母中有兩個是正確的,因為MONITOR
和CONTAIN
的第二個和第三個字母都是字母O
和N
。這個游戲類似于項目 1,“百吉餅”,以及輻射系列視頻游戲中的黑客迷你游戲。
運行示例
當(dāng)您運行hacking.py
時,輸出將如下所示:
Hacking Minigame, by Al Sweigart email@protected
Find the password in the computer's memory:
0x1150 $],>@|~~RESOLVE^ 0x1250 {>+)<!?CHICKEN,%
0x1160 }@%_-:;/$^(|<|!( 0x1260 .][})?#@#ADDRESS
0x1170 _;)][#?<&~$~+&}} 0x1270 ,#=)>{-;/DESPITE
0x1180 %[!]{email@protected?~, 0x1280 }/.}!-DISPLAY%%/
0x1190 _[^%[@}^<_+{email@protected$~ 0x1290 =>>,:*%email@protected+{%#.
0x11a0 )?~/)+PENALTY?-= 0x12a0 >[,?*#email@protected$/
`--snip--`
Enter password: (4 tries remaining)
> resolve
Access Denied (2/7 correct)
Enter password: (3 tries remaining)
> improve
A C C E S S G R A N T E D
工作原理
這個游戲有一個黑客主題,但不涉及任何實際的電腦黑客行為。如果我們只是在屏幕上列出可能的單詞,游戲就會完全一樣。然而,模仿計算機(jī)記憶庫的裝飾性添加傳達(dá)了一種令人興奮的計算機(jī)黑客的感覺。對細(xì)節(jié)和用戶體驗的關(guān)注將一個平淡、無聊的游戲變成了一個令人興奮的游戲。
"""Hacking Minigame, by Al Sweigart email@protected
The hacking mini-game from "Fallout 3". Find out which seven-letter
word is the password by using clues each guess gives you.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: large, artistic, game, puzzle"""# NOTE: This program requires the sevenletterwords.txt file. You can
# download it from https://inventwithpython.com/sevenletterwords.txtimport random, sys# Set up the constants:
# The garbage filler characters for the "computer memory" display.
GARBAGE_CHARS = 'email@protected#$%^&*()_+-={}[]|;:,.<>?/'# Load the WORDS list from a text file that has 7-letter words.
with open('sevenletterwords.txt') as wordListFile:WORDS = wordListFile.readlines()
for i in range(len(WORDS)):# Convert each word to uppercase and remove the trailing newline:WORDS[i] = WORDS[i].strip().upper()def main():"""Run a single game of Hacking."""print('''Hacking Minigame, by Al Sweigart email@protected
Find the password in the computer's memory. You are given clues after
each guess. For example, if the secret password is MONITOR but the
player guessed CONTAIN, they are given the hint that 2 out of 7 letters
were correct, because both MONITOR and CONTAIN have the letter O and N
as their 2nd and 3rd letter. You get four guesses.\n''')input('Press Enter to begin...')gameWords = getWords()# The "computer memory" is just cosmetic, but it looks cool:computerMemory = getComputerMemoryString(gameWords)secretPassword = random.choice(gameWords)print(computerMemory)# Start at 4 tries remaining, going down:for triesRemaining in range(4, 0, -1):playerMove = askForPlayerGuess(gameWords, triesRemaining)if playerMove == secretPassword:print('A C C E S S G R A N T E D')returnelse:numMatches = numMatchingLetters(secretPassword, playerMove)print('Access Denied ({}/7 correct)'.format(numMatches))print('Out of tries. Secret password was {}.'.format(secretPassword))def getWords():"""Return a list of 12 words that could possibly be the password.The secret password will be the first word in the list.To make the game fair, we try to ensure that there are words witha range of matching numbers of letters as the secret word."""secretPassword = random.choice(WORDS)words = [secretPassword]# Find two more words; these have zero matching letters.# We use "< 3" because the secret password is already in words.while len(words) < 3:randomWord = getOneWordExcept(words)if numMatchingLetters(secretPassword, randomWord) == 0:words.append(randomWord)# Find two words that have 3 matching letters (but give up at 500# tries if not enough can be found).for i in range(500):if len(words) == 5:break # Found 5 words, so break out of the loop.randomWord = getOneWordExcept(words)if numMatchingLetters(secretPassword, randomWord) == 3:words.append(randomWord)# Find at least seven words that have at least one matching letter# (but give up at 500 tries if not enough can be found).for i in range(500):if len(words) == 12:break # Found 7 or more words, so break out of the loop.randomWord = getOneWordExcept(words)if numMatchingLetters(secretPassword, randomWord) != 0:words.append(randomWord)# Add any random words needed to get 12 words total.while len(words) < 12:randomWord = getOneWordExcept(words)words.append(randomWord)assert len(words) == 12return wordsdef getOneWordExcept(blocklist=None):"""Returns a random word from WORDS that isn't in blocklist."""if blocklist == None:blocklist = []while True:randomWord = random.choice(WORDS)if randomWord not in blocklist:return randomWorddef numMatchingLetters(word1, word2):"""Returns the number of matching letters in these two words."""matches = 0for i in range(len(word1)):if word1[i] == word2[i]:matches += 1return matchesdef getComputerMemoryString(words):"""Return a string representing the "computer memory"."""# Pick one line per word to contain a word. There are 16 lines, but# they are split into two halves.linesWithWords = random.sample(range(16 * 2), len(words))# The starting memory address (this is also cosmetic).memoryAddress = 16 * random.randint(0, 4000)# Create the "computer memory" string.computerMemory = [] # Will contain 16 strings, one for each line.nextWord = 0 # The index in words of the word to put into a line.for lineNum in range(16): # The "computer memory" has 16 lines.# Create a half line of garbage characters:leftHalf = ''rightHalf = ''for j in range(16): # Each half line has 16 characters.leftHalf += random.choice(GARBAGE_CHARS)rightHalf += random.choice(GARBAGE_CHARS)# Fill in the password from words:if lineNum in linesWithWords:# Find a random place in the half line to insert the word:insertionIndex = random.randint(0, 9)# Insert the word:leftHalf = (leftHalf[:insertionIndex] + words[nextWord]+ leftHalf[insertionIndex + 7:])nextWord += 1 # Update the word to put in the half line.if lineNum + 16 in linesWithWords:# Find a random place in the half line to insert the word:insertionIndex = random.randint(0, 9)# Insert the word:rightHalf = (rightHalf[:insertionIndex] + words[nextWord]+ rightHalf[insertionIndex + 7:])nextWord += 1 # Update the word to put in the half line.computerMemory.append('0x' + hex(memoryAddress)[2:].zfill(4)+ ' ' + leftHalf + ' '+ '0x' + hex(memoryAddress + (16*16))[2:].zfill(4)+ ' ' + rightHalf)memoryAddress += 16 # Jump from, say, 0xe680 to 0xe690.# Each string in the computerMemory list is joined into one large# string to return:return '\n'.join(computerMemory)def askForPlayerGuess(words, tries):"""Let the player enter a password guess."""while True:print('Enter password: ({} tries remaining)'.format(tries))guess = input('> ').upper()if guess in words:return guessprint('That is not one of the possible passwords listed above.')print('Try entering "{}" or "{}".'.format(words[0], words[1]))# If this program was run (instead of imported), run the game:
if __name__ == '__main__':try:main()except KeyboardInterrupt:sys.exit() # When Ctrl-C is pressed, end the program.
在輸入源代碼并運行幾次之后,嘗試對其進(jìn)行實驗性的修改。你也可以自己想辦法做到以下幾點:
- 在互聯(lián)網(wǎng)上找到一個單詞列表,創(chuàng)建你自己的文件
sevenletterwords.txt
,也許是一個由六個或八個字母組成的文件。 - 創(chuàng)建一個不同的“計算機(jī)內(nèi)存”的可視化
探索程序
試著找出下列問題的答案。嘗試對代碼進(jìn)行一些修改,然后重新運行程序,看看這些修改有什么影響。
- 如果把 133 行的
for j in range(16):
改成for j in range(0):
會怎么樣? - 如果把第 14 行的
GARBAGE_CHARS = 'email@protected#$%^&*()_+-={}[]|;:,.<>?/'
改成GARBAGE_CHARS = '.'
會怎么樣? - 如果把第 34 行的
gameWords = getWords()
改成gameWords = ['MALKOVICH'] * 20
會怎么樣? - 如果將第 94 行的
return words
改為return
,會得到什么錯誤信息? - 如果把 103 行的
randomWord = random.choice(WORDS)
改成secretPassword = 'PASSWORD'
會怎么樣?
三十四、劊子手和斷頭臺
原文:http://inventwithpython.com/bigbookpython/project34.html
這個經(jīng)典的文字游戲讓玩家猜一個秘密單詞的字母。對于每一個不正確的字母,劊子手的另一部分被畫出來。在劊子手完成之前,試著猜出完整的單詞。這個版本的密語都是兔子鴿子之類的動物,但是你可以用自己的一套話來代替這些。
HANGMAN_PICS
變量包含劊子手絞索每一步的 ASCII 藝術(shù)畫字符串:
+--+ +--+ +--+ +--+ +--+ +--+ +--+| | | | | | | | | | | | | || O | O | O | O | O | O || | | | /| | /|\ | /|\ | /|\ || | | | | / | / \ || | | | | | |
===== ===== ===== ===== ===== ===== =====
對于游戲中的法式轉(zhuǎn)折,您可以用以下描述斷頭臺的字符串替換HANGMAN_PICS
變量中的字符串:
| | | |===| |===| |===| |===| |===|
| | | | | | | | | || /| || /|
| | | | | | | | | ||/ | ||/ |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | |/-\| |/-\| |/-\|
| | | | | |\ /| |\ /| |\ /| |\O/|
|=== |===| |===| |===| |===| |===| |===|
運行示例
當(dāng)您運行hangman.py
時,輸出將如下所示:
Hangman, by Al Sweigart email@protected+--+| |||||
=====
The category is: AnimalsMissed letters: No missed letters yet._ _ _ _ _
Guess a letter.
> e
`--snip--`+--+| |O |
/| |||
=====
The category is: AnimalsMissed letters: A I S
O T T E _
Guess a letter.
> r
Yes! The secret word is: OTTER
You have won!
工作原理
劊子手和斷頭臺共享相同的游戲機(jī)制,但有不同的表現(xiàn)形式。這使得用 ASCII 藝術(shù)畫的斷頭臺圖形替換 ASCII 藝術(shù)畫的絞索圖形變得容易,而不必改變程序遵循的主要邏輯。程序的表示和邏輯部分的分離使得用新的特性或不同的設(shè)計進(jìn)行更新變得更加容易。在專業(yè)軟件開發(fā)中,這種策略是軟件設(shè)計模式或軟件架構(gòu)的一個例子,它關(guān)注于如何構(gòu)建你的程序,以便于理解和修改。這主要在大型軟件應(yīng)用中有用,但是您也可以將這些原則應(yīng)用到較小的項目中。
"""Hangman, by Al Sweigart email@protected
Guess the letters to a secret word before the hangman is drawn.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: large, game, word, puzzle"""# A version of this game is featured in the book "Invent Your Own
# Computer Games with Python" https://nostarch.com/inventwithpythonimport random, sys# Set up the constants:
# (!) Try adding or changing the strings in HANGMAN_PICS to make a
# guillotine instead of a gallows.
HANGMAN_PICS = [r"""
+--+
| |||||
=====""",
r"""
+--+
| |
O ||||
=====""",
r"""
+--+
| |
O |
| |||
=====""",
r"""
+--+
| |
O |
/| |||
=====""",
r"""
+--+
| |
O |
/|\ |||
=====""",
r"""
+--+
| |
O |
/|\ |
/ ||
=====""",
r"""
+--+
| |
O |
/|\ |
/ \ ||
====="""]# (!) Try replacing CATEGORY and WORDS with new strings.
CATEGORY = 'Animals'
WORDS = 'ANT BABOON BADGER BAT BEAR BEAVER CAMEL CAT CLAM COBRA COUGAR COYOTE CROW DEER DOG DONKEY DUCK EAGLE FERRET FOX FROG GOAT GOOSE HAWK LION LIZARD LLAMA MOLE MONKEY MOOSE MOUSE MULE NEWT OTTER OWL PANDA PARROT PIGEON PYTHON RABBIT RAM RAT RAVEN RHINO SALMON SEAL SHARK SHEEP SKUNK SLOTH SNAKE SPIDER STORK SWAN TIGER TOAD TROUT TURKEY TURTLE WEASEL WHALE WOLF WOMBAT ZEBRA'.split()def main():print('Hangman, by Al Sweigart email@protected')# Setup variables for a new game:missedLetters = [] # List of incorrect letter guesses.correctLetters = [] # List of correct letter guesses.secretWord = random.choice(WORDS) # The word the player must guess.while True: # Main game loop.drawHangman(missedLetters, correctLetters, secretWord)# Let the player enter their letter guess:guess = getPlayerGuess(missedLetters + correctLetters)if guess in secretWord:# Add the correct guess to correctLetters:correctLetters.append(guess)# Check if the player has won:foundAllLetters = True # Start off assuming they've won.for secretWordLetter in secretWord:if secretWordLetter not in correctLetters:# There's a letter in the secret word that isn't# yet in correctLetters, so the player hasn't won:foundAllLetters = Falsebreakif foundAllLetters:print('Yes! The secret word is:', secretWord)print('You have won!')break # Break out of the main game loop.else:# The player has guessed incorrectly:missedLetters.append(guess)# Check if player has guessed too many times and lost. (The# "- 1" is because we don't count the empty gallows in# HANGMAN_PICS.)if len(missedLetters) == len(HANGMAN_PICS) - 1:drawHangman(missedLetters, correctLetters, secretWord)print('You have run out of guesses!')print('The word was "{}"'.format(secretWord))breakdef drawHangman(missedLetters, correctLetters, secretWord):"""Draw the current state of the hangman, along with the missed andcorrectly-guessed letters of the secret word."""print(HANGMAN_PICS[len(missedLetters)])print('The category is:', CATEGORY)print()# Show the incorrectly guessed letters:print('Missed letters: ', end='')for letter in missedLetters:print(letter, end=' ')if len(missedLetters) == 0:print('No missed letters yet.')print()# Display the blanks for the secret word (one blank per letter):blanks = ['_'] * len(secretWord)# Replace blanks with correctly guessed letters:for i in range(len(secretWord)):if secretWord[i] in correctLetters:blanks[i] = secretWord[i]# Show the secret word with spaces in between each letter:print(' '.join(blanks))def getPlayerGuess(alreadyGuessed):"""Returns the letter the player entered. This function makes surethe player entered a single letter they haven't guessed before."""while True: # Keep asking until the player enters a valid letter.print('Guess a letter.')guess = input('> ').upper()if len(guess) != 1:print('Please enter a single letter.')elif guess in alreadyGuessed:print('You have already guessed that letter. Choose again.')elif not guess.isalpha():print('Please enter a LETTER.')else:return guess# If this program was run (instead of imported), run the game:
if __name__ == '__main__':try:main()except KeyboardInterrupt:sys.exit() # When Ctrl-C is pressed, end the program.
在輸入源代碼并運行幾次之后,嘗試對其進(jìn)行實驗性的修改。標(biāo)有(!)
的注釋對你可以做的小改變有建議。你也可以自己想辦法做到以下幾點:
- 添加一個“類別選擇”功能,讓玩家選擇他們想玩的詞的類別。
- 增加一個選擇功能,這樣玩家可以在游戲的劊子手和斷頭臺版本之間進(jìn)行選擇。
探索程序
試著找出下列問題的答案。嘗試對代碼進(jìn)行一些修改,然后重新運行程序,看看這些修改有什么影響。
- 如果刪除或注釋掉第 108 行的
missedLetters.append(guess)
會發(fā)生什么? - 如果把第 85 行的
drawHangman(missedLetters, correctLetters, secretWord)
改成drawHangman(correctLetters, missedLetters, secretWord)
會怎么樣? - 如果把 136 行的
['_']
改成['*']
會怎么樣? - 如果把 144 行的
print(' '.join(blanks))
改成print(secretWord)
會怎么樣?
三十五、六邊形網(wǎng)格
原文:http://inventwithpython.com/bigbookpython/project35.html
這個簡短的程序產(chǎn)生一個類似于鐵絲網(wǎng)的六角形網(wǎng)格的鑲嵌圖像。這說明你不需要很多代碼就能做出有趣的東西。這個項目的一個稍微復(fù)雜一點的變體是項目 65,“閃光地毯”
注意,這個程序使用原始字符串,它在開始的引號前面加上小寫的r
,這樣字符串中的反斜杠就不會被解釋為轉(zhuǎn)義字符。
運行示例
圖 35-1 顯示了運行hexgrid.py
時的輸出。
:顯示六邊形網(wǎng)格鑲嵌圖像的輸出
工作原理
編程背后的力量在于它能讓計算機(jī)快速無誤地執(zhí)行重復(fù)的指令。這就是十幾行代碼如何在屏幕上創(chuàng)建數(shù)百、數(shù)千或數(shù)百萬個六邊形。
在命令提示符或終端窗口中,您可以將程序的輸出從屏幕重定向到文本文件。在 Windows 上,運行py hexgrid.py > hextiles.txt
創(chuàng)建一個包含六邊形的文本文件。在 Linux 和 macOS 上,運行python3 hexgrid.py > hextiles.txt
。沒有屏幕大小的限制,您可以增加X_REPEAT
和Y_REPEAT
常量并將內(nèi)容保存到文件中。從那里,很容易將文件打印在紙上,用電子郵件發(fā)送,或發(fā)布到社交媒體上。這適用于你創(chuàng)作的任何計算機(jī)生成的作品。
"""Hex Grid, by Al Sweigart email@protected
Displays a simple tessellation of a hexagon grid.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, artistic"""# Set up the constants:
# (!) Try changing these values to other numbers:
X_REPEAT = 19 # How many times to tessellate horizontally.
Y_REPEAT = 12 # How many times to tessellate vertically.for y in range(Y_REPEAT):# Display the top half of the hexagon:for x in range(X_REPEAT):print(r'/ \_', end='')print()# Display the bottom half of the hexagon:for x in range(X_REPEAT):print(r'\_/ ', end='')print()
在輸入源代碼并運行幾次之后,嘗試對其進(jìn)行實驗性的修改。標(biāo)有(!)
的注釋對你可以做的小改變有建議。你也可以自己想辦法做到以下幾點:
- 創(chuàng)建更大尺寸的平鋪六邊形。
- 創(chuàng)建平鋪的矩形磚塊,而不是六邊形。
為了練習(xí),請嘗試使用更大的六邊形網(wǎng)格重新創(chuàng)建此程序,如下圖所示:
/ \ / \ / \ / \ / \ / \ / \
/ \___/ \___/ \___/ \___/ \___/ \___/ \
\ / \ / \ / \ / \ / \ / \ /\___/ \___/ \___/ \___/ \___/ \___/ \___// \ / \ / \ / \ / \ / \ / \
/ \___/ \___/ \___/ \___/ \___/ \___/ \/ \ / \ / \ / \/ \ / \ / \ / \
/ \_____/ \_____/ \_____/ \_____
\ / \ / \ / \ /\ / \ / \ / \ /\_____/ \_____/ \_____/ \_____// \ / \ / \ / \/ \ / \ / \ / \
/ \_____/ \_____/ \_____/ \_____
探索程序
這是一個基礎(chǔ)程序,所以沒有太多的選項來定制它。取而代之的是,考慮你如何能類似地編程其他形狀的模式。