在Pygame中,如何在while循环中为圆圈赋予不同的属性?

时间:2017-12-06 20:09:39

标签: python arrays list dictionary pygame

我正在创建一个类似于Haxball的NBA模拟器,其中每个圆圈应该有一个用户名并且是它自己的东西,这样在程序运行期间,一个单独的圆圈可以改变自己的属性,例如玩家变慢但是不是每个人都这样做。

我在团队课程中使用了几行来创建播放器并将它们放在 team1players 列表中。这确实可以在不同的合作中创建5个圆圈。但是我需要 playername 属性(来自播放器类)来更改每个圈子,因为只有某些玩家才能玩某些位置。我试图在for循环中使用 self.composition ,但它不允许我将字典用作int。我需要创建的每个玩家都是一个不同的玩家名称 - 玩家名称来自包含所有位置的合成词典。到目前为止,我已经在组合中的控球后卫位置添加了1个名字(Jose Calderon),我尝试在创建圆圈时使用控球后卫列表但是这导致所有球员被命名为Jose Calderon而不是< strong> team1players [0] (作为控卫)叫Jose。

以下是我需要帮助的代码部分 - 还有很多其他缺陷,但这是一个基本的原型:

self.team1players = []
for i in range(numPlayers):
    self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
self.team2players = []#
for i in range(numPlayers):
    self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30))

以下是完整的代码,因为任何人都可能需要了解正在发生的事情。对不起,这一刻有点乱。 :&#39;(

import pygame
import random
import math
pygame.init()#initialising python

(width, height) = (940,500)#variables for screen
screen = pygame.display.set_mode((width, height)) #sets the screen size as "screen"
pygame.display.set_caption('Basketball Simulator') #sets the title of the window
background_image = pygame.image.load("bballcourt.jpg") #setting the background image as a variable to be used to display on the screen
icon_image = pygame.image.load("basketball-tiny.png") #setting the icon image

numPlayers = 5

class teams():

    def __init__(self, teamname = "unknown", wins = "0", losses = "0", team1player = "unknown", team2player ="unknown", colour = "255,255,255"):
        #above I have created all the attributes of teams
        self.teamname = teamname #sets teamname
        self.composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.wins = wins #number of wins
        self.losses = losses #number of losses
        self.team1player = team1player #holds a player and can be used to create players I have made this here so that the players are a part of the team
        self.team2player = team2player

        self.colour = colour #holds the rgb colour specific to the team

    def startTeam(self):
        validTeamChoice1 = False #creating a while loop to only allow valid inputs for the first team choice
        validTeamChoice2 = False #loop for second team choice
        userChoice1 = " " 
        Team1Colour = userChoice1
        Team1Name = " "
        userChoice2 = " "
        Team2Colour = userChoice2
        Team2Name = " "
        while validTeamChoice1 == False:
            userChoice1 = self.teamname = input("Please select a team // GSW or CAVS: ") #allowing user input
            if userChoice1.upper() == "GSW":
                userChoice1 = self.teamname = ("Golden State Warriors")
                Team1Colour = self.colour = (0,107,182) #rgb colour for GSW yellow
                Team1Name = self.teamname
                if userChoice1 == self.teamname:
                    validTeamChoice1 = True
            else:
                validTeamChoice1 = False #continues loop
        while validTeamChoice2 == False:
            userChoice2 = self.teamname = input("Please select an opposing team // GSW or CAVS: ")
            if userChoice2.upper() == "CAVS":
                userChoice2 = self.teamname = ("Cleveland Cavaliers")
                Team2Colour = self.colour = (134,0,56) #rgb colour for CAVS red
                Team2Name = self.teamname
                self.composition['point guard'].append('Jose Calderon')
                if userChoice2 == self.teamname:
                    validTeamChoice2 = True
            else:
                validTeamChoice2 = False

        self.team1players = []
        for i in range(numPlayers):
            self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
        self.team2players = []#
        for i in range(numPlayers):
            self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30))
    def displayPlayers(self): #displays the player using the player attributes and the display method from the Player class
        for n in range(numPlayers):
            self.team1players[n].displayCircle() 
            self.team2players[n].displayCircle()
    def printPlayers(self):
        print(self.team2players[1].playername)

class Player(): #the player class holds information on the player symbol
    def __init__(self, playername, size, x, y, colour, thickness,teamname,speed, angle): #teamname is predetermined
        self.playername = playername
        self.size = size #size is a unit for the radius
        self.x = x #x, y are position on the court 
        self.y = y
        self.speed = speed
        self.angle = angle
        self.colour = colour
        self.thickness = 0 #thickness is set to 0

    def displayCircle(self): #drawing the circle onto the screen using colour, co-ordinates and radii
            pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)




pygame.display.set_icon(icon_image)
screen.blit(background_image, [0,0]) #this sets the background court image (note: its outside all the classes) 
myTeam1 = teams() #creates a myTeam1 object from the teams class
myTeam1.startTeam() #runs the startTeam method from the teams class
myTeam1.displayPlayers() #runs the displayPlayers method from the teams
pygame.display.flip() #updates the screen based on current events ("flip" is the same as "update()")
myTeam1.printPlayers()
#the below code monitors current on screen events should they be needed for movement etc. it also allows the window to be closed.
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            quit

感谢任何帮助!

编辑下面我已经做了这样,以便在用户选择一个团队(每个团队都有差异玩家)之后将相关玩家附加到他们的位置,并且我还创建了一个新的合成属性在球队班级 - 现在有team1composition和team2composition,这样两队都有不同的控球后卫,得分后卫等。有更有效的方法吗?起初我打算让两个队员都在字典中的列表中,然后我会使用数组来选择哪个队员是哪支队伍然而我相信这更好?

class teams(): 

    def __init__(self, teamname = "unknown", wins = "0", losses = "0", team1player = "unknown", team2player ="unknown", colour = "255,255,255"):
        #above I have created all the attributes of teams
        self.teamname = teamname #sets teamname
        self.team1composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.team2composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.wins = wins #number of wins
        self.losses = losses #number of losses
        self.team1player = team1player #holds a player and can be used to create players I have made this here so that the players are a part of the team
        self.team2player = team2player

        self.colour = colour #holds the rgb colour specific to the team

    def startTeam(self):
        validTeamChoice1 = False #creating a while loop to only allow valid inputs for the first team choice
        validTeamChoice2 = False #loop for second team choice
        userChoice1 = " " 
        Team1Colour = userChoice1
        Team1Name = " "
        userChoice2 = " "
        Team2Colour = userChoice2
        Team2Name = " "
        while validTeamChoice1 == False:
            userChoice1 = self.teamname = input("Please select a team // GSW or CAVS: ") #allowing user input
            if userChoice1.upper() == "GSW":
                userChoice1 = self.teamname = ("Golden State Warriors")
                Team1Colour = self.colour = (0,107,182) #rgb colour for GSW yellow
                Team1Name = self.teamname
                if userChoice1 == self.teamname:
                    validTeamChoice1 = True
            else:
                validTeamChoice1 = False #continues loop
        while validTeamChoice2 == False:
            userChoice2 = self.teamname = input("Please select an opposing team // GSW or CAVS: ")
            if userChoice2.upper() == "CAVS":
                userChoice2 = self.teamname = ("Cleveland Cavaliers")
                Team2Colour = self.colour = (134,0,56) #rgb colour for CAVS red
                Team2Name = self.teamname
                self.team2composition['point guard'].append('Jose Calderon')
                self.team2composition['shooting guard'].append('J.R Smith')
                self.team2composition['small forward'].append('LeBron James')
                self.team2composition['power forward'].append('Jae Crowder')
                self.team2composition['centre'].append('Kevin Love')
                if userChoice2 == self.teamname:
                    validTeamChoice2 = True
            else:
                validTeamChoice2 = False

        self.team1players = []
        for position , name in self.team1composition.items():
            print (position, name)
            self.team1players.append(Player(name, 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
        self.team2players = []#
        for position, name in self.team2composition.items():
            print(position , name)
            self.team2players.append(Player(name, 15, random.randint(470,940),random.randint(0,500)

现在运行代码的时候是结果(不是Pygame窗口)......

Please select a team // GSW or CAVS: gsw
Please select an opposing team // GSW or CAVS: cavs
point guard []
shooting guard []
small forward []
power forward []
centre []
point guard ['Jose Calderon']
shooting guard ['J.R Smith']
small forward ['LeBron James']
power forward ['Jae Crowder']
centre ['Kevin Love']

1 个答案:

答案 0 :(得分:2)

而不是

for i in range(numPlayers): 
    self.team2players.append(Player(self.composition['point guard'], ...))

您可以将fordictionary

一起使用
self.team2players = []#

for position, name in self.composition.items():
    #print(position, name)
    self.team2players.append(Player(name, ...))

<强>顺便说一句:

因为self.composition中只有一名玩家 所以它只会在self.team2players中创建一个玩家。

词典没有保持秩序,所以当self.composition中有更多玩家时 那么for ... in self.composition可能会以不同的顺序创建玩家。

修改

当我查看Player(self.composition['point guard'],时,您似乎只有一个字符串分配给self.composition['point guard'],之前的代码应该有效, 但是当我查看你的字典时,似乎你的列表中有许多名称分配给self.composition['point guard']

    self.composition = {
        'point guard' : [],
        'shooting guard': [],
        'small forward': [],
        'power forward': [],
        'centre': []
    }

这意味着您需要两个for循环

self.team2players = []#

for position, names_list in self.composition.items():
    #print(position, names_list)
    for name in names_list:
        #print(name)
        self.team2players.append(Player(name, ...))

修改

如果您只为每个职位保留一个名称,那么您不需要列表,但如果没有名称,您可以使用带名称的字符串或空字符串(或None)。

self.composition = {
    'point guard' : None,
    'shooting guard': None,
    'small forward': None,
    'power forward': None,
    'centre': None
}

并指定名称而不是append()

self.composition['point guard'] = 'Jose Calderon'

要创建播放器,您需要使用if来检查None

self.team2players = []

for position, name in self.composition.items():
    if name: # the same as `if (name is not None) and (name != "") and (name != 0) and (name != False) ...: 
        self.team2players.append(Player(name, ...))
    #else:
    #   print("you don't have player on position", position)