我正在尝试制作一艘战舰游戏,但我却被困在船上。 当我试图运行时:
print "Welcome to Battleships!!!"
board = []
import os
from random import randint
for x in range(10):
board.append(["O"] * 10)
def print_board(board):
for row in board:
print " | ".join(row)
ships = {"battleship" : [5], "cruiser1" : [4], "cruiser2" : [4], "frigate1" : [3], "frigate2" : [3], "frigate3" : [3], "frigate4" : [3], "minesweeper1" : [2], "minesweeper2" : [2], "minesweeper3" : [2], "minesweeper4" : [2]}
numbers1 = []
numbers2 = []
numbers = []
def setup_nums1():
for count1 in range(6):
for count2 in range(10):
number1 = (count1)*100
number2 = count2
numbers1.append(number1 + number2)
def setup_nums2():
for count1 in range(10):
for count2 in range(6):
number1 = (count1)*100
number2 = count2
numbers2.append(number1 + number2)
def setup_nums():
for count1 in range(10):
for count2 in range(10):
number1 = (count1)*100
number2 = count2
numbers.append(number1 + number2)
def setup_numbers():
setup_nums()
setup_nums1()
setup_nums2()
def setup_ships():
x = 59
for ship, info in ships:
direction = randint(1,2)
if direction == 1:
ships[ship].append(numbers1[randint (0,x)])
y = info[1]
print y
numbers1.remove(y)
if y in numbers2:
numbers2.remove(y)
numbers.remove(y)
x = x - 1
for n in range(ship[0]):
ships[ship].append(y + n + 1)
numbers1.remove(y + n + 1)
if (y + n + 1) in numbers2:
numbers2.remove(y + n + 1)
numbers.remove(y + n + 1)
x = x - 1
if direction == 2:
ships[ship].append(numbers2[randint (0,x)])
y = info[1]
print y
numbers2.remove(y)
if y in numbers1:
numbers1.remove(y)
numbers.remove(y)
x = x - 1
for n in range(ship[0]):
ships[ship].append(y + n*100 + 100)
numbers2.remove(y + n*100 + 100)
if (y + n + 1) in numbers1:
numbers1.remove(y + n*100 + 100)
numbers.remove(y + n*100 + 100)
x = x - 1
setup_nums1()
setup_nums2()
setup_ships()
print numbers1
print numbers2
print ships
我收到此错误:
Welcome to Battleships!!!
Traceback (most recent call last):
File "/home/matthew/Documents/battleship2.py", line 77, in <module>
setup_ships()
File "/home/matthew/Documents/battleship2.py", line 41, in setup_ships
for ship, info in ships:
ValueError: too many values to unpack
答案 0 :(得分:3)
要解压缩的值太多意味着您正在调用的函数返回多个值,而您只处理其中的一些值。
问题在
for ship, info in ships:
这必须像
for ship, info in ships.items():
或强>
for ship, info in ships.iteritems():
答案 1 :(得分:3)
而不是for ship, info in ships
尝试for ship, info in ships.iteritems()
。
使用in ships
语法,您只能返回一个值(它们是键)。
例如,你可以这样做:
ships = { 'a': 'ship_a', 'b': 'ship_b', 'c': 'ship_c' }
for key in ships:
print(key) # Outputs a b c
相反,如果你这样做:
for key, value in ships.iteritems():
print(key, value) # Outputs ('a', 'ship_a') ('b', 'ship_b') ('c': 'ship_c')
检查this answer以获取有关Python 2.x和Python 3.x兼容性的更多信息。