2014-02-02 8 views
0

Я пытался исправить это какое-то время, но я не могу заставить его работать правильно. Я пытаюсь сделать игру в понг с питоном и пытаюсь сделать это лучше всего из трех игр. Тем не менее, у меня возникают проблемы, когда я перезапускаю игру после каждого раунда, я не могу найти способ сохранить значения переменных wins1 и wins2. Я установил в начале 0, и я знаю, что это не сохраняет значение, так как оно возвращается к 0 каждый раз, когда вызывается функция pongyay(), но я держу ее там, чтобы не получить никаких других ошибки. Если бы кто-нибудь мог дать хорошее предложение о том, как сохранить волы из них, но все равно держать их в цикле, что я запускаю игру, это было бы очень признательно. Вот код:Сохранение значения переменной после повторного вызова функции

from tkinter import * 
import random 
import time 
import subprocess 
import sys 

tk = Tk() 
tk.title("Epic Game of Destiny") # Title of the window 
tk.resizable(0, 0) 
tk.wm_attributes("-topmost", 1) 
wins1 = 0 
wins2 = 0 

def pongyay(): 

    canvas = Canvas(tk, width=700, height=400, bd=0, highlightthickness=0) #canvas attributes 
    canvas.configure(background='black') 
    canvas.pack() 
    tk.update() 

    class Rectangle: 
     def __init__(self, canvas, color): 
      self.canvas = canvas 
      self.paddle = paddle 
      self.paddle2 = paddle2 
      self.id = self.canvas.create_rectangle(6, 20, 0, 0, fill=color) 

    class Brik: 
     def __init__(self, canvas, color): 
      self.canvas = canvas 
      self.paddle = paddle 
      self.paddle2 = paddle2 
      self.id = self.canvas.create_rectangle(6, 30, 0, 0, fill=color) 

    class PowerUp: #class that creates the ball and assigns its attributes 
     def __init__(self, canvas, color): 
      self.canvas = canvas 
      self.paddle = paddle 
      self.paddle2 = paddle2 
      self.id = canvas.create_rectangle(10, 10, 10, 10, fill=color) #attributes, using self.id, which allows the detection of the current object self.id is 
      self.canvas.move(self.id, 400, 400) #starting position 

     def draw(self): #how the powerup bounces and reacts to its surroundings 
      self.canvas.move(self.id, self.x, self.y) 
      pos = self.canvas.coords(self.id) 
      if pos[1] <= 0: 
       self.y = 2 
      if self.hit_paddle(pos) == True: 
       canvas.move(self.id, 1000, 1000) 
      if self.hit_paddle2(pos) == True: 
       canvas.move(self.id, 1000, 1000) 
      if pos[3] >= self.canvas_height: #places the powerup on the canvas and detects where the edges are, meaning that when the powerup hits the edge it will bounce off 
       self.y = -2 
      if pos[0] <= 0: 
       self.x = 2 

    class Ball: #class that creates the ball and assigns its attributes 
     def __init__(self, canvas, color): 
      self.canvas = canvas 
      self.paddle = paddle 
      self.paddle2 = paddle2 
      self.id = canvas.create_rectangle(10, 10, 25, 25, fill=color) #ball attributes, using self.id, which allows the detection of the current object self.id is 
      self.canvas.move(self.id, 330, 200) 
      starts = [-2, 2] 
      start2 = [-1, 1] 
      random.shuffle(starts) 
      random.shuffle(start2)#ball starting position 
      self.x = starts[0] 
      self.y = start2[0] 
      self.canvas_height = self.canvas.winfo_height() #gets size of canvas in order to allow ball to bounce off the walls 
      self.canvas_width = self.canvas.winfo_width() 
      self.side1 = False 
      self.side2 = False 

     def hit_paddle(self, pos): 
      paddle_pos = self.canvas.coords(self.paddle.id) 
      if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]: # returns true or false when the ball does or does not hit the paddle, which then allows the ball to bounce off it 
       if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]: 
        return True 
      return False 

     def hit_paddle2(self, pos): 
      paddle2_pos = self.canvas.coords(self.paddle2.id) 
      if pos[2] >= paddle2_pos[0] and pos[0] <= paddle2_pos[2]: # returns true or false when the ball does or does not hit the paddle, which then allows the ball to bounce off it 
       if pos[3] >= paddle2_pos[1] and pos[3] <= paddle2_pos[3]: 
        return True 
      return False 

     def draw(self): #how the ball bounces and reacts to its surroundings 
      self.canvas.move(self.id, self.x, self.y) 
      pos = self.canvas.coords(self.id) 
      if pos[1] <= 0: 
       self.y = 8 
      if self.hit_paddle(pos) == True: 
       self.x = -8 
      if self.hit_paddle2(pos) == True: 
       self.x = 8 
      if pos[3] >= self.canvas_height: #places the ball on the canvas and detects where the edges are, meaning that when the ball hits the edge it will bounce off 
       self.y = -8 
      if pos[0] <= 0: 
       self.side1 = True 
       self.x = 8 
      if pos[2] >= 700: 
       self.side2 = True 
       self.x = -8 
      if pos[0] >= 1: 
       self.side1 = False 
      if pos[2] <= 700: 
       self.side2 = False 


    class Paddle: #class to create the paddle and its attributes 
     def __init__(self, canvas, color): 
      self.canvas = canvas 
      self.id = canvas.create_rectangle(0, 0, 15, 80, fill = color) #the paddles attributes, it is long and thin, and will be filled with the color specified 
      self.canvas.move(self.id, 50, 200) 
      self.y = 0 
      self.canvas_height = self.canvas.winfo_height() 
      self.canvas.bind_all('<KeyPress-Up>', self.turn_left) # keybindings that moves the paddle along the canvas 
      self.canvas.bind_all('<KeyPress-Down>', self.turn_right) 
      self.canvas.bind_all('<KeyRelease-Up>', self.stop_left) # keybindings that moves the paddle along the canvas 
      self.canvas.bind_all('<KeyRelease-Down>', self.stop_right) 

     def turn_left(self, evt):# when the left key is pressed, the paddle moves along at this speed 
      self.y = -9 

     def turn_right(self, evt): # when the right key is pressed, the paddle moves along at this speed 
      self.y = 9 

     def stop_left(self, evt):# when the left key is released, the paddle will stop moving 
      self.y = 0 

     def stop_right(self, evt): # when the right key is released, the paddle will stop moving 
      self.y = 0 

     def draw(self): 
      pos = self.canvas.coords(self.id) #this detects the side of the canvas and stops the paddle from moving past it 
      if pos[1] <= 0: 
       self.y = 1 
      elif pos[3] >= self.canvas_height: 
       self.y = -1 
      self.canvas.move(self.id, 0, self.y) 

    class Paddle2: #class to create the paddle and its attributes 
     def __init__(self, canvas, color): 
      self.canvas = canvas 
      self.id = canvas.create_rectangle(0, 0, 15, 80, fill = color) #the paddles attributes, it is long and thin, and will be filled with the color specified 
      self.canvas.move(self.id, 50, 200) 
      self.y = 0 
      self.canvas_height = self.canvas.winfo_height() 
      self.canvas.bind_all('<KeyPress-a>', self.turn_left2) # keybindings that moves the paddle along the canvas 
      self.canvas.bind_all('<KeyPress-z>', self.turn_right2) 
      self.canvas.bind_all('<KeyRelease-a>', self.stop_left2) # keybindings that moves the paddle along the canvas 
      self.canvas.bind_all('<KeyRelease-z>', self.stop_right2) 


     def turn_left2(self, evt):# when the left key is pressed, the paddle moves along at this speed 
      self.y = -9 

     def turn_right2(self, evt): # when the right key is pressed, the paddle moves along at this speed 
      self.y = 9 

     def stop_left2(self, evt):# when the left key is released, the paddle will stop moving 
      self.y = 0 

     def stop_right2(self, evt): # when the right key is released, the paddle will stop moving 
      self.y = 0 

     def draw(self): 
      pos = self.canvas.coords(self.id) #this detects the side of the canvas and stops the paddle from moving past it 
      if pos[1] <= 0: 
       self.y = 1 
      elif pos[3] >= self.canvas_height: 
       self.y = -1 
      self.canvas.move(self.id, 0, self.y) 

    paddle = Paddle(canvas, 'white') #the object of the paddle that will be instantiated 
    paddle2 = Paddle2(canvas, 'white') 
    ball = Ball(canvas, 'white') #the object of the ball that will be instantiated 
    powerup = PowerUp(canvas, 'white') 

    paddle.draw() 
    paddle2.draw() 

    brick1 = Brik(canvas, 'white') 
    brick5 = Brik(canvas, 'white') 
    brick1.canvas.move(brick1.id, 450, 200) 
    brick5.canvas.move(brick5.id, 250, 200) 
    rectangle1 = Rectangle(canvas, 'white') 
    rectangle2 = Rectangle(canvas, 'white') 
    rectangle3 = Rectangle(canvas, 'white') 
    rectangle4 = Rectangle(canvas, 'white') 
    rectangle5 = Rectangle(canvas, 'white') 
    rectangle6 = Rectangle(canvas, 'white') 
    rectangle7 = Rectangle(canvas, 'white') 
    rectangle8 = Rectangle(canvas, 'white') 
    rectangle9 = Rectangle(canvas, 'white') 
    rectangle10 = Rectangle(canvas, 'white') 
    rectangle11 = Rectangle(canvas, 'white') 
    rectangle1.canvas.move(rectangle1.id, 350, 380) 
    rectangle2.canvas.move(rectangle2.id, 350, 342) 
    rectangle3.canvas.move(rectangle3.id, 350, 304) 
    rectangle4.canvas.move(rectangle4.id, 350, 266) 
    rectangle5.canvas.move(rectangle5.id, 350, 228) 
    rectangle6.canvas.move(rectangle6.id, 350, 190) 
    rectangle7.canvas.move(rectangle7.id, 350, 152) 
    rectangle8.canvas.move(rectangle8.id, 350, 114) 
    rectangle9.canvas.move(rectangle9.id, 350, 76) 
    rectangle10.canvas.move(rectangle10.id, 350, 38) 
    rectangle11.canvas.move(rectangle11.id, 350, 0) 
    paddle2.canvas.move(paddle.id, 583, 0) 
    tk.update_idletasks 
    tk.update() 

    global score1 
    global score2 
    score1 = 0 
    score2 = 0 

    def restart(): 
     result = messagebox.askyesno("Revenge?","Would you like to restart?") 
     if result == True: 
      score1 = 0 
      score2 = 0 
      canvas.destroy() 
      pongyay()   
     else: 
      tk.destroy() 

    while 1: 
     tk.update_idletasks() #loop that and allows it to move, by updating tkinter every 0.01 second 
     tk.update() 
     time.sleep(0.0000001) 
     ball.draw() 
     paddle.draw() 
     paddle2.draw() 


     if ball.side1 == True: 
      score2 = score2 + 1 
      print(score2) 
      if score2 == 1: 
       rc1 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc1, 365, 20) 
      if score2 == 2: 
       rc2 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc2, 385, 20) 
      if score2 == 3: 
       rc3 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc3, 405, 20) 
      if score2 == 4: 
       rc4 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc4, 425, 20) 
      if score2 == 5: 
       rc5 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc5, 445, 20) 
      if score2 == 6: 
       rc6 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc6, 465, 20) 
      if score2 == 7: 
       rc7 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc7, 485, 20) 
      if score2 == 8: 
       rc8 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc8, 505, 20) 
      if score2 == 9: 
       rc9 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc9, 525, 20) 
      if score2 == 10: 
       rc10 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc10, 545, 20) 


     elif ball.side2 == True: 
      score1 = score1 + 1 
      print(score1) 
      if score1 == 1: 
       rc1 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc1, 320, 20) 
      if score1 == 2: 
       rc2 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc2, 300, 20) 
      if score1 == 3: 
       rc3 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc3, 280, 20) 
      if score1 == 4: 
       rc4 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc4, 260, 20) 
      if score1 == 5: 
       rc5 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc5, 240, 20) 
      if score1 == 6: 
       rc6 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc6, 220, 20) 
      if score1 == 7: 
       rc7 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc7, 200, 20) 
      if score1 == 8: 
       rc8 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc8, 180, 20) 
      if score1 == 9: 
       rc9 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc9, 160, 20) 
      if score1 == 10: 
       rc10 = canvas.create_rectangle(5, 5, 15, 15, fill='white') 
       canvas.move(rc10, 140, 20) 


     if score1 == 10: 
      wins1 = 0 
      wins1 = wins1 + 1 
      print(wins1) 
      time.sleep(2) 
      score1 = 0 
      score2 = 0 
      canvas.destroy() 
      pongyay() 
      if wins1 == 1: 
       finalpoint = Label(tk, text='This Match Decides The Winner', fg="white", bg="black", font=("OCR A Std", 50)) 
       finalpoint.pack() 
       finalpoint.place(x = 350, y = 200) 
       time.sleep(1.5) 
       finalpoint.destroy() 
      if wins1 == 2: 
       finalpoint1 = Label(tk, text='Player 1 Wins!', fg="white", bg="black", font=("OCR A Std", 50)) 
       finalpoint1.pack() 
       finalpoint1.place(x = 350, y = 200) 
       restart() 

     if score2 == 10: 
      wins2 = 0 
      wins2 = wins2 + 1 
      print(wins2) 
      time.sleep(2) 
      score1 = 0 
      score2 = 0 
      canvas.destroy() 
      pongyay() 
      if wins2 == 1: 
       finalpoint = Label(tk, text='This Match Decides The Winner', fg="white", bg="black", font=("OCR A Std", 50)) 
       finalpoint.pack() 
       finalpoint.place(x = 350, y = 200) 
       time.sleep(1.5) 
       finalpoint.destroy() 
      if wins2 == 2: 
       finalpoint2 = Label(tk, text='Player 2 Wins!', fg="white", bg="black", font=("OCR A Std", 50)) 
       finalpoint2.pack() 
       finalpoint2.place(x = 350, y = 200) 
       restart() 


pongyay() 

Основная область, с которой сталкивается проблема, находится внизу с подсчетом.

Еще раз спасибо всем, кто отвечает

+0

Почему у вас есть другой класс для каждого весла? – user2357112

+0

Мне было легче протестировать два весла отдельно друг от друга, и когда я опишу игру, два весла будут иметь разные атрибуты. – user2992997

+0

Их поведение почти одинаково. Большинство их методов являются точными. Было бы разумно иметь один класс и просто передавать вещи, которые должны быть разными в конструкторе, или иметь базовый класс, реализующий общую функциональность, и подклассы просто выполняют части, которые должны быть разными. – user2357112

ответ

1

Посмотрите на эти два бита:

  wins1 = 0 
      wins1 = wins1 + 1 

и

  wins2 = 0 
      wins2 = wins2 + 1 

Вы вытирают счетчики выигрыша, прежде чем увеличивать их. Если вы хотите инициализировать количество выигрышей, сделайте это за пределами цикла.

В верхней части кода вы создаете пару глобальных переменных wins1 и wins2; возможно, вы хотели использовать их внутри pongyay?

tk.wm_attributes("-topmost", 1) 
wins1 = 0 
wins2 = 0 

Если это так, удалите wins1 = 0 и wins2 = 0 строки из внутри pongyay, и объявить global wins1 и global wins2 внутри pongyay поэтому функция использует глобальные переменные вместо создания локальных переменных.

+0

. Я знаю, что я уничтожаю счет выигрыша, но это только для того, чтобы остановить больше ошибок, но когда я ставлю счет выигрыша код за пределами цикла, он ничего не делает – user2992997

+0

Если вы посмотрите на код, вы увидите, что оператор if уничтожает холст и повторно вызывает функцию pongyay(), даже если я вывожу их за пределы цикла, это будет просто каждый раз, когда – user2992997

+0

@ user2992997: «только там, чтобы остановить больше ошибок» - знаете ли вы, почему возникли другие ошибки или почему вычистка счетчиков выигрышей остановила эти ошибки? Очистка счета выигрышей не является проблемой; вам нужно выяснить, что пошло не так, когда инициализация счета выигрыша была вне цикла и исправила ее правильно. Я подозреваю, что проблемы, связанные с вашими переменными. – user2357112

Смежные вопросы