[英]The Python assignment operator, function definitions, and variable definitions
好吧……我花了很長時間才讓我的代碼可以正常工作,但是我重新安排了一切,然后突然開始正常工作。 不確定我的所作所為,所以我想這將是這個問題的主題。 我正在構建一個簡單的基於文本的紙牌游戲,該游戲使用從兩個.txt文件上傳的卡片組。 它的目標是魔術:聚會,但如果人們對其有所創造,它可能會與他人合作。 為了提供一個大致的概述,這是事情的安排方式:
import random
def shuffle(board1):
def game():
#board=[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#performs most of the actions relating to the game
board[0]=20
board[10]=20
def gameboard(board2):
#displays game board
def draw(board3, numcards, player):
#draws cards
def upload(deckname):
#uploads cards from file
def life(board4):
#asks about which player the life total is changing on, by how much, etc.
#and then does it
def maketoken(board5):
#creates tokens, counters, etc. based on user input
def move(board5):
#accepts user input and moves cards from zone to zone
def play(board6):
#handles casting spells, using abilities, triggered abilities, etc.
#main body of program is below function definitions
board=[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
deckname1=input("\nWhat is the name of deck 1?")
deckname2=input("\nWhat is the name of deck 2?")
deck1=upload(deckname1)
deck2=uplaod(deckname2)
board[1]=deck1
board[11]=deck2
#this is where a lot of the other variables get set
game()
(注意:為了簡潔起見,大多數代碼已被刪除,因為我的代碼很丑陋)
我具有大學水平的C ++背景,並且最近才決定使用老式鍵盤,因此賦值運算符(=)不能按我期望的方式運行,使我感到瘋狂。 因此,我還想知道是否有一種方法可以在Python中獲得C ++'='的功能,因為我從.txt文件上傳了卡片組,並希望在完成后立即使用upload()函數(我使用deck1 = upload(deckname)(與deck2相同)。我想在每次游戲后使用“ deck1”和“ deck2”來填充卡組,但是如果我了解“ =”在python中的工作方式,請進入board [1 ] = deck1表示board [1]將指向deck1的存儲區域,而更改為board [1]會更改deck1,但是我不想要... GRRRR !!!!!! 11)。 我敢肯定某個地方有解決方案,因為這使我很生氣,但我一直找不到。 謝謝!!!
編輯:這是我以這種方式設置事物時收到的錯誤:
Traceback (most recent call last):
File "C:\Users\inventor487\Desktop\simplepy.py", line 444, in <module>
game()
File "C:\Users\inventor487\Desktop\simplepy.py", line 114, in game
board[1]=deck1
UnboundLocalError: local variable 'board' referenced before assignment
摘要:
編輯:一個類可以非常輕松,更干凈地解決所有這些問題。 每個區域都有一個單獨的變量,等等,一切都變得更加流暢。 謝謝你們的幫助,盡管你們。 非常感激。
您已經發現,Python中的=
運算符不會像在C ++中那樣復制對象的副本。 如果要制作副本以存儲在另一個變量中,則必須對其進行明確說明。
board[1] = deck1[:] # the slicing operator copies a subset or the whole list
更通用的方法是使用copy
模塊
import copy
board[1] = copy.copy(deck1)
board[1] = copy.deepcopy(deck1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.