如何根据用户输入在 pyGame 中创建 2 到 4 个玩家?



到目前为止,我已经为一个项目创建了一个相当简单的蛇和梯子游戏。目前,它只有两个玩家,但我想包含一个选项,用户输入玩家人数(2-4(,然后输入所有玩家姓名,并在棋盘上为他们绘制计数器。但是,我目前很难实现这一点。

我为两个玩家编写的原始代码部分如下(工作正常(:

print('''
Welcome to Snakes N Ladders!
Take it turns to roll the die, press SPACE to do so!
The first player to 100 wins, but they have to land exactly on it.
Good luck, have fun!
'''
)
player1Name = input("Please enter the first players name: ")
player1 = Player(player1Name)
player2Name = input("Please enter the second players name: ")
player2 = Player(player2Name)
players = [player1, player2]


def drawGrid():
window.blit(boardImage,(0,0))
for x in range (height):
for y in range(width):
if board[x][y] == player1.Pos:
pygame.draw.circle(window, PlayerOneColour, (x * squareSize + int(squareSize/2) -10, y*squareSize +int(squareSize/2)+6) ,charSize)
if board[x][y] == player2.Pos:
pygame.draw.circle(window, PlayerTwoColour, (x * squareSize + int(squareSize/2) +10, y*squareSize +int(squareSize/2)+6) ,charSize)

pygame.display.flip()

这使用我之前创建的类玩家,PlayerOneColor设置玩家1的颜色,玩家2也可以这样说。

玩家类是:

class Player(object):
def __init__(self, name):
self.name = name
self.Pos = 1
print("Player created!")
def turn(self):
roll = random.randint(1,6)
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print(self.name,"rolled a",roll)
for i in range(self.Pos, self.Pos + roll + 1):
self.Pos = i
drawGrid()
time.sleep(.4)
print(self.name,"is now at:",self.Pos)
if self.Pos > 100:
self.Pos -= roll
print(self.name,"rolled a",roll,"they need to roll a",100-self.Pos,"to win!")
drawGrid()
return

如您所见,它包含方法转向,但这不是我的问题所在。它包含玩家位置(1(和他们的名字。但是,当我尝试使播放器函数创建这样的播放器时:


def createPlayers():
players = []
player1Name = input("Please enter the first players name: ")
player1 = Player(player1Name)
players.append(player1)
player2Name = input("Please enter the second players name: ")
player2 = Player(player2Name)
players.append(player2)
print(players)    
if numberOfPlayers == 3:
player3Name = input("Please enter the third players name: ")
player3 = Player(player3Name)
players.append(player3)
elif numberOfPlayers == 4:
player3Name = input("Please enter the third players name: ")
player3 = Player(player3Name)
players.append(player3)
player4Name = input("Please enter the fourth players name: ")
player4 = Player(player4Name)
players.append(player4)
else:
print("Please pick between 2 and 4 players.")

def drawGrid():
window.blit(boardImage,(0,0))
for x in range (height):
for y in range(width)::
if board[x][y] == player1.Pos:
pygame.draw.circle(window, PlayerOneColour, (x * squareSize + int(squareSize/2) -10, y*squareSize +int(squareSize/2)+6) ,charSize)
if board[x][y] == player2.Pos:
pygame.draw.circle(window, PlayerTwoColour, (x * squareSize + int(squareSize/2) +10, y*squareSize +int(squareSize/2)+6) ,charSize)
if numberOfPlayers == 3:
if board[x][y] == player3.Pos:
pygame.draw.circle(window, PlayerThreeColour, (x * squareSize + int(squareSize/2) +10, y*squareSize +int(squareSize/2)+6) ,charSize)
if numberOfPlayers == 4:
if board[x][y] == player4.Pos:
pygame.draw.circle(window, PlayerFourColour, (x * squareSize + int(squareSize/2) +10, y*squareSize +int(squareSize/2)+6) ,charSize)

我知道这段代码很混乱,但我认为这是唯一的方法,最初我在 drawGrid 函数内有一个 for player in player: 循环,但它要么说 player1 未定义,要么与 NonType 对象有关,我认为问题与局部和全局变量有关,但我不知道如何解决, 任何关于让用户输入以在棋盘上吸引 2-4 名玩家的建议都会很棒,如果需要,我可以链接我的整个 SnakesNLadders 文件到目前为止。

一些规则:

  • 如果你有很多元素,那么将它们保留在列表中并使用for-loop。
  • 将玩家属性保留在类内,而不是在类外
  • PEP 8 - Python 代码风格指南 - 即。lower_case_names变量和函数/方法/即。pos代替Poscreate_players代替createPlayers等。
  • 将值作为参数发送,而不是使用外部变量 - 即。create_players(number),并使用return将其从函数/方法 -return players发送回。

您应该将颜色保留在列表中,而不是单独的变量,即。

colors = [(255,0,0), (0,255,0), (0,0,255), (255,255,0)]

和类播放器应该获取颜色作为参数并将其保留在类中

class Player:
def __init__(self, name, color, pos=1):
self.name = name
self.color = color
self.pos = pos
#self.x = x
#self.x = y
#self.number = number
# etc.
print("Player {} created!".format(name))

所以现在您可以使用循环来创建播放器并为播放器分配颜色

colors = [(255,0,0), (0,255,0), (0,0,255), (255,255,0)]
def create_players(number):
if number < 2 or number > 4: 
print("Please pick between 2 and 4 players.")
return
players = []
for x in range(number):
name = input("Please enter name of player #{}: ".format(x+1))
player = Player(name, colors[x])
players.append(player)
return players  
players = create_players(number_of_players)

如果要使用单词firstseconds则可以将其保留在列表中并添加到输入中的文本中

number_names = ['first', 'second', 'third', 'fourth']
colors = [(255,0,0), (0,255,0), (0,0,255), (255,255,0)]
def create_players(number):
if number < 2 or number > 4: 
print("Please pick between 2 and 4 players.")
return
players = []
for x in number_of_players
name = input("Please enter {} name of player: ".format(number_names[x]))
player = Player(name, colors[x])
players.append(player)
return players   

现在您可以使用列表和for循环在网格上绘制球员。

def draw_grid():
window.blit(board_image, (0, 0))
half_size = int(square_size/2) 
x_offset = half_size + 10
y_offset = half_size + 6
for x in range(height):
for y in range(width):
for p in players:
if board[x][y] == p.pos:
pygame.draw.circle(window, p.color, (x*squareSize + x_offset, y*squareSize + x_offset), char_size)

要访问一个选定的播放器,您可以使用索引[]-players[0].nameplayers[1].name等。

但通常我们必须处理列表中的所有元素,而不是使用range(len())和 '[x](

for x in range(len(players)):
print( players[x].name )

我们使用

for p in players:
print( p.name )

顺便说一句:print( players )给出了[<main...>, <main...>, ...],这是正常的。 对于print( player1 )你也会得到<main...>.您需要__repr__并最终在课堂上__str__才能获得不同的文本

class Player:
def __init__(self, name, color, pos=1):
self.name = name
self.color = color
self.pos = pos
print("Player {} created!".format(name))
def __repr__(self):
return "<Player: name: {}, color: {}, pos: {}>".format(self.name, self.color, self.pos)
def __str__(self):
#return self.__repr__() #  it is executed automatically if you don't create own `__str__`
return "name: {}, color: {}, pos: {}".format(self.name, self.color, self.pos)

最新更新