程序问题应该更新每一次全局变量int_choice
值的玩家分数(这是一个乒乓球比赛)与全局变量设置
int_choice
只能值1或0。如果它是1,功能left_or_right
“告诉”球右转,如果它是0,则球左转。
int_choice
在几个地方更新:在开始它初始化,然后在left_or_right()
功能,然后在draw()
功能。
每次用户打分时,球应该从桌子中心向该用户重新分娩,但球始终在同一方向再次出现两次,然后在相反方向再次出现两次,依此类推,无论谁是最后一个得分。
下面的代码:存在
import random
int_choice = random.randint(0,1)
direc = None
def left_or_right():
global direc, int_choice
if int_choice == 0:
direc = "LEFT"
elif int_choice == 1:
direc = "RIGHT"
return direc
def spawn_ball(direction):
left_or_right()
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH/2, HEIGHT/2]
if direction == "LEFT":
ball_vel[0] = (random.randrange(12, 25)*(-0.1))
print "Velocity[0]: ", ball_vel[0]
ball_vel[1] = (random.randrange(6, 19)*(-0.1))
elif direction == "RIGHT":
ball_vel[0] = (random.randrange(12, 25)*(0.1))
print "Velocity[0]: ", ball_vel[0]
ball_vel[1] = (random.randrange(6, 19)*(-0.1))
print "Velocity[1]: ", ball_vel[1]
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel, direc
global score1, score2,
spawn_ball(direc)
score1 = 0
score2 = 0
def draw(canvas):
global remaining_names, score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, BALL_RADIUS, direc
global int_choice
# update ball
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
if ball_pos[1] - BALL_RADIUS <= 0:
ball_vel[1] = ball_vel[1] + (ball_vel[1] * (-2))
elif ball_pos[1] + BALL_RADIUS >= HEIGHT:
ball_vel[1] = ball_vel[1] + (ball_vel[1] * (-2))
elif ball_pos[0] - BALL_RADIUS <= (0 + PAD_WIDTH):
if (ball_pos[1] > paddle1_pos) and (ball_pos[1] < (paddle1_pos + PAD_HEIGHT)):
ball_vel[0] = ball_vel[0] + (ball_vel[0] * (-2.1))
else:
int_choice = 1
spawn_ball(direc)
score2 = score2 + 1
elif (ball_pos[0] + BALL_RADIUS) >= (WIDTH - PAD_WIDTH):
if (ball_pos[1] > paddle2_pos) and (ball_pos[1] < (paddle2_pos + PAD_HEIGHT)):
ball_vel[0] = ball_vel[0] + (ball_vel[0] * (-2.1))
else:
int_choice = 0
spawn_ball(direc)
score1 = score1 + 1
'random.randint(0,1)'是'random.randrange(2)'的别名。考虑使用后者。 –
为什么你甚至使用*两个*全局意味着同样的事情?而你的'left_or_right()'函数可以用一个列表来代替:'directions = ['LEFT','RIGHT']'和directions [int_choice]'会在每次需要文本时将整数转换为文本。 –
你也传递给'spawn_ball()'的方向,然后*调用'left_or_right()'。为什么要通过这个方向,然后调用一个函数来重新设置它?该函数也会返回方向,但您无处处忽略返回值。 –