#!/usr/bin/env python
import tkinter as tk
from tkinter import ttk
import math
import random
#positions are stored in label and number format
LARGE_FONT= ("Verdana", 12)
positions = ['label'+str(i)+str(j) for i in range(8) for j in range(8)]
class Application(tk.Frame):
global positions
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
#The entry screen
#label = tk.Label(self, text="""Begin.""", font=LARGE_FONT)
#label.grid(row=0, column=0, pady=10)
#label = tk.Label(self, text="""Exit.""", font=LARGE_FONT)
#label.grid(row=0, column=1, pady=10)
#button1 = ttk.Button(self, text="Start Game", command=self.start)
#button2 = ttk.Button(self, text="Quit Game", command=quit)
#button1.grid(row=1, column=0, pady=10)
#button2.grid(row=1, column=1, pady=1)
#def start(self):
#self.createWidgets()
self.master = master
app = tk.Frame(self.master, bg="yellow")
app.grid_rowconfigure(0, weight=1)
app.grid_columnconfigure(1, weight=1)
app.grid_columnconfigure(0, weight=1)
#app.pack(fill="both", expand=True)
# instructions and fonts
self.instructions = "Find the hidden treasure!\n\nUse the arrow keys to select where to look, then press Enter to check. \
There is a 50/50 chance you will be told the distance from the treasure. Keep hunting until you find it. Good luck!"
# create instructions widget
self.info = tk.Text(app, padx=10, pady=10,width=15,bd=0, height=19, bg="yellow")
self.info.insert(1.0,self.instructions)
self.info.grid(row=0,column=0,sticky='N'+'E'+'S'+'W')
# create island widget
self.island = tk.Text(app, bg="cyan", padx=40, pady=40, width=15, height=9, bd=0)
self.island.insert(1.0, "ready")
self.island.grid(row=0,column=1, stick='N'+'E'+'S'+'W', rowspan=3)
# restart button
#self.restart_b = tk.Button(app, text="Restart", bg="red", command=self.begin)
#self.restart_b.grid(row=2, column=0, pady=20)
# score labels and fields
self.score_lbl = tk.Label(app, text="Guesses: 0", bg="yellow")
self.score_lbl.grid(row=1, column=0)
#keep track og gold
self.gold_lbl = tk.Label(app, text="Gold: 0", bg="yellow")
self.gold_lbl.grid(row=3, column=0)
#gold and bandit positions
self.gridrange = 8
self.numchest = 10
self.bandits = 3
self.winscore = 100
# set keydown handler
root.bind("<Key>", self.key_pressed)
# best score variable
self.best_score = 0
# begin game
#self.begin()
#print self.treasure_pos
self.mainMenu()
def mainMenu(self):
self.t = tk.Toplevel(self.master, backgroun='red')
self.t.wm_title("Main Menu")
self.l = tk.Label(self.t, text="Welcome to Treasure Hunt", background='red')
self.l.pack(side="top", fill="both", expand=True, padx=100, pady=100)
self.t.lift(self.master)
#self.t.geometry('640x480+0+0')
self.play = tk.Button(self.t, text="play", bg="purple", command=self.letsplay)
self.play.pack(side='left', expand=True)
self.ops = tk.Button(self.t, text="options", bg="yellow", command=self.ops)
self.ops.pack(side='left', expand=True)
def ops(self):
self.opwin = tk.Toplevel(self.master, backgroun='red')
self.opwin.wm_title("Option Menu")
self.opl = tk.Label(self.opwin, text="Welcome to Treasure Hunt", background='red')
self.opl.pack(side="top", fill="both", expand=True, padx=100, pady=100)
self.opwin.lift()
#self.opwin.geometry('640x480+0+0')
self.appp = tk.Button(self.opwin, text="Apply", bg="purple", command=self.letsplay)
self.appp.pack(side='left', expand=True)
self.gridops = tk.Listbox(self.opwin, selectmode='SINGLE')
self.gridops.pack()
for i in range(6, 14):
self.gridops.insert(tk.END, i)
self.gridrange = self.gridops.curselection()
def letsplay(self):
self.t.destroy()
#self.opwin.destroy()
#self.begin()
self.createWidgets()
root.lift()
def createWidgets(self):
#print (self.gridrange)
root.lift()
root.after_cancel(self.tick)
self.matrix = [["#" for col in range(self.gridrange)] for row in range(self.gridrange)]
self.current_pos = [0,0]
self.treasure_pos = []
self.bandit_pos = []
#times treasure has been found
self.treasures_won = []
self.last_treasure = []
self.gold_found = 0
for i in range(0, self.numchest):
self.gold_xy = self.get_pos()
self.treasure_pos.append(self.gold_xy)
for i in self.treasure_pos:
print (i)
print (len(self.treasure_pos))
for i in range (0, self.bandits):
self.bandit_xy = self.get_pos()
self.bandit_pos.append(self.bandit_xy)
for i in self.bandit_pos:
print (i)
print (len(self.bandit_pos))
#self.treasure_pos = [0,0]
#print self.treasure_pos
self.sett()
top=self.winfo_toplevel()
self.entry_frame = tk.Frame(self)
self.entry_frame.grid(row=0, column=0,rowspan=1,columnspan=8,sticky=tk.N+tk.E+tk.W)
self.pos_frame = tk.Frame(self)
self.pos_frame.grid(row=1, column=0,columnspan=8,sticky=tk.N+tk.S+tk.E+tk.W)
self.entry_frame.rowconfigure(0,weight=2)
screenx=self.pos_frame.winfo_width()
screeny=self.pos_frame.winfo_height()
for i in range(8):
top.rowconfigure(i,weight=1)
top.columnconfigure(i,weight=1)
self.pos_frame.columnconfigure(i,weight=1)
self.pos_frame.rowconfigure(i,weight=1)
self.entry_frame.columnconfigure(i,weight=1)
self.rowconfigure(i,weight=1)
self.columnconfigure(i,weight=1)
self.label_no_of_moves=tk.Label(self.entry_frame,text="MOVES : ")
self.label_no_of_moves.grid(row=0,column=0,sticky=tk.N+tk.S+tk.E+tk.W)
self.moves=tk.StringVar()
self.number_of_moves=tk.Entry(self.entry_frame,textvariable=self.moves)
self.number_of_moves.grid(row=0,column=1,sticky=tk.N+tk.S+tk.E+tk.W)
self.label_direction=tk.Label(self.entry_frame,text="DIRECTION : ")
self.label_direction.grid(row=0,column=2,sticky=tk.N+tk.S+tk.E+tk.W)
#Assume Direction to be U D L R you can also use listbox here but i m not using it for saving time
self.dir=tk.StringVar()
self.direction=tk.Entry(self.entry_frame,textvariable=self.dir)
self.direction.grid(row=0,column=3,sticky=tk.N+tk.S+tk.E+tk.W)
self.direction=tk.Button(self.entry_frame,text='GO',command=self.gomoves)
self.direction.grid(row=0,column=4,sticky=tk.N+tk.S+tk.E+tk.W)
for i in range(8):
for j in range(8):
x='label'+str(i)+str(j)
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(3*(j+1))[0]+"7",text=str(i)+str(j))
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
#For updating the grid if window size is changed
self.bind('<Configure>',self.update)
#For initial Player position
self.start_position=str('label'+generate_initial_position())
self.current_position = self.start_position
print (self.current_position)
#initial position removed from positions(avaliable positions)
print (positions)
positions.remove(str(self.start_position))
#selecting treasure chest from remaining positions
self.treasure_chest_positions=random.sample(positions,10)
#removing treasures chest position from positions(avaliable positions)
for i in positions[:]:
if i in self.treasure_chest_positions:
positions.remove(i)
print (self.treasure_chest_positions)
#selecting bandits position from positions(avaliable positions)
self.bandit_positions =random.sample(positions,5)
def sett(self):
self.blink = False
self.guesses = 0
self.end_tick = False
self.tick()
def get_pos(self):
self.used = False
xy = random.randrange(self.gridrange), random.randrange(self.gridrange)
if xy in self.treasure_pos or xy in self.bandit_pos:
self.used = True
while self.used == True:
xy = (random.randrange(self.gridrange), random.randrange(self.gridrange))
if xy not in self.treasure_pos or xy in self.bandit_pos:
self.used = False
return xy
else:
return xy
def gomoves(self,event=None):
print ('GO MOVES')
#Validate Moves so that the values of moves should lie inside the positions avaliable
print (self.moves.get())
print (self.dir.get())
#On moving update the current position variable
#Please deal with the position written in format label(row_no)(column_no) like label01 for row=0 and column=1 it will not be that difficult
current_row= int(self.current_position[5:6])
current_column=int(self.current_position[6:7])
print (current_row , current_column)
#now update the position based on moves if moves are invalid then pop up tkDialogBox search a little on google you will get help from there
#self.current_position =
def key_pressed(self, event):
if event.keysym == "Right" and self.current_pos[1] < 7:
self.current_pos[1] += 1
print("right")
elif event.keysym == "Left" and self.current_pos[1] > 0:
self.current_pos[1] -= 1
print("left")
elif event.keysym == "Up" and self.current_pos[0] > 0:
self.current_pos[0] -= 1
print("up")
elif event.keysym == "Down" and self.current_pos[0] < 7:
self.current_pos[0] += 1
print("down")
elif event.keysym == "Return":
self.process_guess()
self.display_grid()
self.matrix = [["#" for col in range(8)] for row in range(8)] # is here the best place for this?
def check(self):
if self.current_pos_tuple in self.treasures_won:
self.counts = Counter(self.treasures_won)
print (self.counts)
print (self.counts)[self.current_pos_tuple]
if self.current_pos_tuple in self.last_treasure:
self.gold_found -= 10
self.treasures_won.remove(self.current_pos_tuple)
self.guesses -= 1
self.last_treasure.remove(self.current_pos_tuple)
print (self.last_treasure)
if self.counts[self.current_pos_tuple] > 3:
self.treasure_pos.remove(self.current_pos_tuple)
self.bandit_pos.append(self.current_pos_tuple)
print ('someone was here waiting for me')
self.gold_found -= 10
print (self.gold_found)
if self.gold_found >= self.winscore:
print ('you win')
if len(self.treasure_pos) <= 0:
print ('you lose')
def process_guess(self):
self.guesses += 1
self.score_lbl.config(text="Guesses: " + str(self.guesses))
self.current_pos_tuple = tuple(self.current_pos)
print (self.current_pos_tuple)
if self.current_pos_tuple in self.treasure_pos:
self.check()
print ('i think i see something shiney')
self.gold_found += 10
print (self.gold_found)
self.treasures_won.append(self.current_pos_tuple)
self.last_treasure.append(self.current_pos_tuple)
self.end_tick = True
self.gold_lbl.config(text="Gold: " + str(self.gold_found))
self.matrix[self.current_pos_tuple[0]][self.current_pos_tuple[1]] = "$"
self.display_grid()
elif self.current_pos_tuple in self.bandit_pos:
print ('something looks suspisious')
self.gold_found = 0
#if not (self.current_pos[0] == self.treasure_pos[0] and self.current_pos[1] == self.treasure_pos[1]):
#print "NOT HERE"
else:
randinteger = random.randrange(10)
dist = int(round(math.sqrt((self.current_pos[0] - self.treasure_pos[randinteger][0]) ** 2 + (self.current_pos[1] - self.treasure_pos[randinteger][1]) ** 2)))
self.matrix[self.current_pos[0]][self.current_pos[1]] = str(dist)
self.display_grid()
print (' i cant seem to find anything')
self.end_tick = True
def display_grid(self):
'''Displays current visual game state'''
self.island.delete(1.0, tk.END)
m_str = ""
for row in range(len(self.matrix)):
m_str += (" ".join(self.matrix[row]) + "\n")
self.island.insert(1.0, m_str)
def finish(self):
self.matrix[self.treasure_pos[self.current_pos_tuple][0]][self.treasure_pos[self.current_pos_tuple][1]] = "$"
self.display_grid()
self.island.insert(tk.END, " + 10 Gold!")
self.sett()
def update(self,event=None):
print (event.num)
screenx=self.pos_frame.winfo_width()
screeny=self.pos_frame.winfo_height()
for i in range(8):
for j in range(8):
x='label'+str(i)+str(j)
if x in self.treasure_chest_positions:
try:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Treasure')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
except:
print("Treasure error")
elif x in self.bandit_positions:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Bandit')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
elif x==self.current_position:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Current')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
else:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text=str(i)+str(j))
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
def tick(self):
'''timer for blinking cursor'''
if self.blink == False:
self.matrix[self.current_pos[0]][self.current_pos[1]] = "#"
elif self.blink == True:
self.matrix[self.current_pos[0]][self.current_pos[1]] = " "
self.blink = not self.blink
self.display_grid()
if not self.end_tick:
root.after(300, self.tick)
else:
self.sett()
def generate_initial_position():
pos=str(random.randint(0,7))+str(random.randint(0,7))
return pos
root = tk.Tk()
app = Application(root)
#app.master.title('Game')
root.mainloop()
我有一个很大的问题,因为代码不想运行而self.gridrange = 8是一个元组,它需要是一个整数,我不知道你还能做些什么才能使它成为一个整数
这是错误
()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Zero Davila\Desktop\new.py", line 110, in letsplay
self.createWidgets()
File "C:\Users\Zero Davila\Desktop\new.py", line 123, in createWidgets
self.matrix = [["#" for col in range(self.gridrange)] for row in range(self.gridrange)]
TypeError: 'tuple' object cannot be interpreted as an integer
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh()这是只是这样我可以张贴上堆叠的h