如何绘制一个类内的圆?

时间:2016-10-20 10:59:35

标签: python pygame

我正在尝试绘制一个圆圈,这是一个类,这就是玩家。

但是,我无法绘制圆圈。

import pygame
pygame.init()

#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

display_width, display_height = 800, 600
screen = pygame.display.set_mode((display_width, display_height))
screen.fill(white)

class Player():
    def __init__(self):
        self.player_surface = screen
        self.player_color = green
        self.player_pos = ((display_height - self.player_radius * 3), (display_width/2))
        self.player_radius = 5
        self.player_width = 0

    def character(self):
        self.player_character = pygame.draw.circle(self.player_surface, self.player_color, self.player_pos, self.player_radius, self.player_width)

#Player Reference
player = Player()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False
    #Background
    screen.fill(white)

    #Draw everything in order, each drawn object will be drawn beneath the next drawn object.

    # Draw the player -----------------------------
    player.character()
    # Draw the player -----------------------------

    #Update
    pygame.display.update()

1 个答案:

答案 0 :(得分:2)

在这里,我修改了您的代码以显示圆圈。

import pygame
pygame.init()

#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

display_width, display_height = 800, 600
screen = pygame.display.set_mode((display_width, display_height))
screen.fill(white)

class Player():
    def __init__(self):
        self.player_surface = screen
        self.player_color = green
        self.player_radius = 25        
        self.player_pos = (int(display_height - self.player_radius * 3), int(display_width/2))
        self.player_width = 0

    def character(self):
        self.player_character = pygame.draw.circle(self.player_surface, self.player_color, self.player_pos, self.player_radius, self.player_width)

#Player Reference
player = Player()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False
    #Background
    screen.fill(white)

    #Draw everything in order, each drawn object will be drawn beneath the next drawn object.

    # Draw the player -----------------------------
    player.character()
    # Draw the player -----------------------------

    #Update
    pygame.display.update()

这些是您的代码存在的问题:

  1. 您在前一行
  2. 中使用之后定义了self.radius
  3. pygame.draw.circle期望x,y坐标为整数值,但您通过将self.player_pos除以2来计算display_width,从而产生float值。我明确地将值转换为int并且播放器(圆圈)显示在屏幕上