程序問題應該更新每一次全局變量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()'。爲什麼要通過這個方向,然後調用一個函數來重新設置它?該函數也會返回方向,但您無處處忽略返回值。 –