我在pygame教程中有这个程序:
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit();
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
这是一个简单的弹跳球。我想要的是用一个圆圈替换球(ball.gif),这个圆圈将使用pygame绘制,而不会对代码进行大的更改。我的意思是,我想改变的唯一一件事就是将球替换为圆圈,并使用与我用来设置球动画相同的代码动画该圆圈。有什么方法可以做到吗?感谢。
答案 0 :(得分:2)
您只需要替换
screen.blit(ball, ballrect)
与
pygame.draw.circle(screen, color, ballrect.center, radius)
Pygame's draw module也允许绘制其他形状。在上面的代码中,您可以使用所需的值填充color
和radius
。 color
是一个三元组的元组,范围为0-255。
答案 1 :(得分:0)
我知道这已经过时了,但我很难搞清楚这一点,但我终于做到了。
{}
答案 2 :(得分:0)
也许这就是您要找的。 下载图片 from here.
import pygame
import sys
WIDTH, HEIGHT = 600,600
ROWS, COLS = 8,8
SQUARE_SIZE = WIDTH//COLS
WIDTH, HEIGHT = SQUARE_SIZE*COLS, SQUARE_SIZE*ROWS
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
CLOCK = pygame.time.Clock()
class Ball:
GRAVITY = 0.5
def __init__(self, row, col):
self.row = row
self.col = col
self.target_x = (SQUARE_SIZE*col)+SQUARE_SIZE/2
self.target_y = (SQUARE_SIZE*row)+SQUARE_SIZE/2
self.x = self.target_x
self.y = 0
self.vel = 10
self.img = pygame.transform.scale(pygame.image.load("ball2.png"), (SQUARE_SIZE-20, SQUARE_SIZE-20))
self.landed = False
def draw(self):
self.update()
pygame.draw.circle(WIN, (0,255,0), (self.x, self.y), 15)
def update(self):
if not self.landed:
self.vel += self.GRAVITY
self.y += self.vel
if self.y > self.target_y:
self.vel = -(self.vel*0.70)
if (abs(self.vel)<1):
self.landed = True
self.y += self.vel
def draw_board(ball_list):
WIN.fill((0,0,0))
for row in range(ROWS):
for col in range(row%2, COLS, 2):
pygame.draw.rect(WIN, (255,0,0), (row*SQUARE_SIZE, col*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def create_balls(ball_list):
x = []
for row in range(ROWS):
for col in range(COLS):
if ball_list[row][col] ==1: x.append(Ball(row, col))
return x
def main():
ball_list = [
[0,0,0,1,0,0,0,1],
[1,0,1,0,0,0,0,1],
[0,0,0,1,0,1,0,0],
[0,0,1,1,0,0,0,1],
[1,0,0,0,0,1,0,0],
[0,0,0,0,1,0,0,1],
[0,1,0,0,0,1,0,0],
[0,0,1,0,0,0,1,0],
]
balls = create_balls(ball_list)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
draw_board(ball_list)
for ball in balls:
ball.draw()
pygame.display.update()
CLOCK.tick(60)
main()