如何重启游戏?(tkinter)

时间:2017-08-03 12:42:09

标签: python tkinter restart

我正在与tkinter进行比赛,玩家必须避开酸雨。 我几乎完成了它,我只是需要一种方法在按下向上键后重新启动整个游戏。我已经制作了一个在下雨后击中玩家的功能。如果按下向上键,则该功能检查事件,并且触发重启功能,其中重启游戏的代码来自重启功能。全部在Game类中。 这是代码:

import random
import time
from winsound import *
from tkinter import *

class Game():
    def __init__(self):
        self.high_file = open('HIGHSCORE.txt','r')
        self.high = self.high_file.read()
        self.tk = Tk()
        self.tk.title('DeadlyRain')
        self.tk.resizable(0,1)
        self.tk.wm_attributes('-topmost',1)
        self.canvas = 
        Canvas(self.tk,width=400,height=500,highlightthickness=0)
        self.canvas.pack()
        self.tk.update()
        self.bg = PhotoImage(file="bg.gif")
        self.canvas.create_image(0,0,image=self.bg,anchor='nw')
        self.score_txt = self.canvas.create_text(320,12,text='Score: 0', \
                         fill='white',font=('Fixedsys',17))
        self.high_txt = self.canvas.create_text(310,30, \
                        text='HighScore: %s' % self.high,\
                        fill='white',font=('Fixedsys',16))
        self.player_img = PhotoImage(file='player\\player0.gif')
        self.player = self.canvas.create_image(150,396, \
                                               image=self.player_img,
                                              anchor='nw')
        self.rain_img = [PhotoImage(file='rain\\rain1.gif'),
                         PhotoImage(file='rain\\rain2.gif'),
                         PhotoImage(file='rain\\rain3.gif')]
        self.images_left = [
            PhotoImage(file="player\\playerL1.gif"),
            PhotoImage(file="player\\playerL2.gif"),
            PhotoImage(file="player\\playerL3.gif")]
        self.images_right = [
            PhotoImage(file="player\\playerR1.gif"),
            PhotoImage(file="player\\playerR2.gif"),
            PhotoImage(file="player\\playerR3.gif")]
        self.current_image = 0
        self.current_image_add = 1
        self.last_time = time.time()
        self.new_high = False        
        self.player_x = 0
        self.rain_drops = []
        self.rain_count = 0
        self.points = 0
        self.speed = 2
        self.list = list(range(0,9999))
        self.needed_rain_count = 100
        self.running = True
        self.canvas.bind_all('<KeyPress-Left>',self.left)
        self.canvas.bind_all('<KeyPress-Right>',self.right)
    def animate(self):
        if self.player_x != 0 :
            if time.time() - self.last_time > 0.1:
                self.last_time = time.time()
                self.current_image += self.current_image_add
                if self.current_image >= 2:
                    self.current_image_add = -1
                if self.current_image <= 0:
                    self.current_image_add = 1
        if self.player_x < 0:
            self.canvas.itemconfig(self.player, 
image=self.images_left[self.current_image])
        elif self.player_x > 0:
            self.canvas.itemconfig(self.player, 
image=self.images_right[self.current_image])
    def score(self):
        self.points += 1
        if self.points > int(self.high):
            self.canvas.itemconfig(self.high_txt, \
                                  text='HighScore: %s' % self.points)
            self.new_high = True
        self.canvas.itemconfig(self.score_txt, \
                              text='Score: %s' % self.points)
        if self.points >= 20 and self.points <= 34:
            self.needed_rain_count = 80 
        elif self.points >= 35 and self.points <= 49:
            self.needed_rain_count = 60
        elif self.points >= 50 and self.points <= 64:
           self.needed_rain_count = 40
       elif self.points >= 65 and self.points <= 79:
           self.needed_rain_count = 20
    def gameover(self):
        self.running = False
        self.canvas.create_text(200,250,text='GAMEOVER')
        if self.new_high == True:
            new_high = open('HIGHSCORE.txt','w')
            new_high.write(str(self.points))
            new_high.close()
            self.high_file.close()
            self.canvas.bind_all('<KeyPress-Up>',self.restart) #restart func
                                                                   is called
        self.high_file.close()
    def restart(self,evt):
        #insert code for restarting game here
    def left(self,evt):
        self.player_x = -2
    def right(self,evt):
        self.player_x = 2
    def move(self):
        self.animate()
        self.canvas.move(self.player,self.player_x,0)
        pos = self.canvas.coords(self.player)
        if pos[0] <= -8:
            self.player_x = 0
        elif pos[0] >= self.canvas.winfo_width() - 40:
            self.player_x = 0

    def rain(self):        
        if self.rain_count == self.needed_rain_count:
            for x in self.list:
                x =self.canvas.create_image(random.randint(0,501), \ 
                   0,image=random.choice(self.rain_img))
                   self.rain_drops.append(x)         
                    self.rain_count = 0
                    self.list.remove(x)
                    break

    def rain_fall(self,id):
        co = self.canvas.coords(id)
        if co[1] > 500:
            self.rain_drops.remove(id)
            self.canvas.delete(id)
            self.score()
        self.canvas.move(id,0,self.speed)

    def rain_hit(self,id):
        rpos = self.canvas.coords(id)
        ppos = self.canvas.coords(self.player)
        if rpos[1] >= ppos[1] and rpos[1] <= ppos[1]+68:
            if rpos[0] >= ppos[0] and rpos[0] <= ppos[0]+48:
                self.gameover()

    def mainloop(self):
        PlaySound("sound\\rain.wav", SND_ASYNC)
        while 1:
            if self.running == True:
                self.rain_count += 1
                self.move()
                self.rain()
                for rain in self.rain_drops:
                    self.rain_hit(rain)
                    self.rain_fall(rain)
                self.tk.update_idletasks()
                self.tk.update()            
                time.sleep(0.01)

g = Game()
g.mainloop()

提前谢谢!

2 个答案:

答案 0 :(得分:0)

你可以juste从mainloop方法中删除while 1并使用布尔值来保持循环。当按下UP键并且播放器被雨水击中时,您可以将该布尔值切换为false。

然后你可以这样做:

while 1 :
    g = Game()
    g.mainloop()

你的游戏将永远循环。

答案 1 :(得分:0)

您将mainloop() 写入init函数内部而不是init函数外部。如果您在tkinter窗口创建部分之外编写主循环,则init函数无法找到mainloop,这对于定义窗口创建部分和mainloop内部的所有代码至关重要。

您在self.canvas.bind_all('<KeyPress-Right>',self.right)部分之后编写了mainloop。