我正在做pong的克隆。它只是pong的准系统版本。如果你们能帮助我改进它会很好。我主要是把它作为一种学习练习,所以我只是将它保留在基本功能中。
import time
import pygame
done = False
pygame.init()
myfont = pygame.font.SysFont("monospace", 15)
screen_size = [320,240]
white = [255,255,255]
black = [0,0,0]
gutter = 10
score_1 = 0
score_2 = 0
ball_pos = [160,120]
ball_vel = [1,1]
paddle_1 = [0,0]
paddle_2 = [screen_size[0]-5,0]
vel_1 = [0,0]
vel_2 = [0,0]
P1 = False
P2 = False
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("mygame")
while not done:
time.sleep(0.02)
screen.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if pygame.key.get_pressed()[pygame.K_DOWN]:
vel_2[1] += 2
P1 = True
if pygame.key.get_pressed()[pygame.K_UP]:
P1 = True
vel_2[1] -= 2
if pygame.key.get_pressed()[pygame.K_s]:
P2 = True
vel_1[1] += 2
if pygame.key.get_pressed()[pygame.K_w]:
P2 = True
vel_1[1] -= 2
if event.type == pygame.KEYUP:
if(P1):
vel_2 = [0,0]
P1 = False
if (P2):
vel_1 = [0,0]
P2 = False
if ball_pos[1] in range(paddle_1[1],paddle_1[1]+30) and ball_pos[0] in range(0,gutter+10) :
ball_vel[0] *= -1
if ball_pos[1] in range(paddle_2[1],paddle_2[1]+30) and ball_pos[0] in range(310,320):
ball_vel[0] *= -1
if ball_pos[0] > 320:
score_1 += 1
ball_pos = [160,120]
if ball_pos[0] < 5:
score_2 += 1
ball_pos = [160,120]
if ball_pos[1] > 230 or ball_pos[1] < 5:
ball_vel[1] *= -1
paddle_1[0] += vel_1[0]
paddle_1[1] += vel_1[1]
paddle_2[0] += vel_2[0]
paddle_2[1] += vel_2[1]
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
## pygame.draw.line(screen,white,(gutter,0),(gutter,screen_size[1]))
## pygame.draw.line(screen,white,(screen_size[0]-gutter,0),(screen_size[0]-gutter,screen_size[1]))
pygame.draw.line(screen,white,(screen_size[0]/2,0),(screen_size[0]/2,screen_size[1]),1)
pygame.draw.circle(screen,white,ball_pos,10,0)
pygame.draw.line(screen,white,[paddle_1[0]+5,paddle_1[1]],[paddle_1[0]+5,paddle_1[1]+50],gutter)
pygame.draw.line(screen,white,paddle_2,[paddle_2[0],paddle_2[1]+50],gutter)
label_1 = myfont.render(str(score_1), 1, (255,255,0))
label_2 = myfont.render(str(score_2), 1, (255,255,0))
screen.blit(label_1, (100, 100))
screen.blit(label_2, (220, 100))
pygame.display.flip()
pygame.quit()
答案 0 :(得分:2)
您应该在代码中改进一些事项:
定义时
white = [255,255,255]
black = [0,0,0]
你应该这样做:
WHITE = (255,255,255)
BLACK = ( 0, 0, 0)
通常应将常量创建为tuples
,这样您就不会错误地更改其值。此外,由于您只读过常量并且从不更改其值,因此tuple
更合适。它也运行得稍快
每当您制作游戏时,建议您将对象创建为类。在这种情况下,您将拥有Player
和Ball
等类。在这些类中,您可以定义update
和draw
等函数。这将允许您通过一行代码轻松绘制对象或更新其位置,速度等。例如:
player.update()
player.draw()
ball.draw()
我建议您使用pygame内置import time
选项来控制游戏的FPS,而不是使用Timer
。这是一个例子:
timer = pygame.time.Clock()
然后在你的while循环开始时,你可以简单地做:
timer.tick(60) #if you want 60 to be the number of frames per second
我知道这需要付出很多,但最终努力将会更加值得,它将使未来的游戏制作变得更加清洁。
HAPPY PYGAMING!
答案 1 :(得分:1)
尝试将球和桨叶封装在适当的Ball和Paddle类中。这样,您可以使代码更清晰,更可重用,因为两个拨片将共享相同的代码。