Reset Game designed with tkinter - python

I am a beginner in python and have designed a "Count the Colored Balls Game". I am now stuck at figuring out best way of restarting the game after one round is over.
Currently:
When you hit start game, it populates 25 random colored balls and then gives user 10 seconds to count red and green balls. It them shows the final answer as a messagebox. Once i dismiss the message box, the balls remain on screen and then when I hit start game, 25 more balls are piled on.
What I want:
How do I reset the game such that when I complete one round, and hit start game, it clears the existing game and restarts.
My Code
from tkinter import *
import random
import time
#from tkinter import ttk
from tkinter import messagebox
#creating a list of colors:
colors=["blue","red","yellow","green","red","pink","red","black","green","cyan"]
#creating global variables and inititializing:
global i
i=0
global redcount
redcount=0
global greencount
greencount=0
global canvas
def startgame():
global canvas
x=startclick()
if x==1:
time.sleep(5)
messagebox.showinfo("Answer"," number of red balls "+str(redcount)+
" and number of green balls is "+str(greencount))
#==============================================
def startclick():
global i
global canvas
global redcount
global greencount
for i in range(1,26):
m=random.randint(0,10)
if m == 1 or m ==4 or m==6:
redcount=redcount+1
if m == 3 or m==8:
greencount=greencount+1
try:
a=random.randint(50,250)
b=random.randint(50,350)
canvas.create_oval(a,b,a+50,b+50,outline="white",fill=colors[m],width=1)
canvas.update()
except:
print()
return(1)
#===============================================
#===============================================
root=Tk()
root.title("Count The Colors")
root.geometry("800x800+0+0") #dimension and position of main frame
#creating canvas of the game
canvas = Canvas(width=600,height=500, bg = "#d2b48c")
canvas.place(x=20, y=20)
w=Label(root,text="Can you count the number of red and green balls?",bg="black",fg="yellow")
w.place(x=30,y=500)
y=Label(root, text="You have 10 seconds to answer...press start to play",
bg="white", fg="black")
y.place(x=20,y=550)
b=Button(root,text = "Start", bg="#fd5f00", width=20, height=1,
font=("Times",12,"bold"), fg="brown", command = startgame)
b.place(x=20, y=600)
root.mainloop()
Appreciate some help on this

First you are not following up programming conventions but anyways you can clear canvas everytime your startclick() function is being called. Simply add canvas.delete("all") to delete the previously created ovals.
def startclick():
global i
global canvas
global redcount
global greencount
canvas.delete("all") #This is your solution
for i in range(1, 26):
m = random.randint(0, 10)
if m == 1 or m == 4 or m == 6:
redcount = redcount + 1
if m == 3 or m == 8:
greencount = greencount + 1
try:
a = random.randint(50, 250)
b = random.randint(50, 350)
canvas.create_oval(a, b, a + 50, b + 50, outline="white", fill=colors[m], width=1)
canvas.update()
except:
print()
return (1)

Related

How to create backspace button in calculator?

import tkinter as tk
from tkinter import *
root=tk.Tk()
root.geometry("720x1320")
root.title('Calculator')
root.resizable(0, 0)
root['background']='#444444'
def bclick(num):
global exp
exp= exp+str(num)
input.set(exp)
def bclear():
global exp
exp=""
input.set("")
def bequal():
global exp
result=str(eval(exp))
input.set(result)
exp=""
exp=""
input=StringVar()
input_frame = Frame(root, width = 312, height = 100, bd = 0, highlightbackground = "black", highlightcolor = "black", highlightthickness = 1)
input_frame.pack(side = TOP)
#label
dis=Entry(input_frame,textvariable=input,bg='#cccccc',fg='#000000',justify=RIGHT,font= ("sans-serif 16"))
dis.place(x=0,y=0)
dis.pack(ipady=197)
#0 row
bC=tk.Button(root,text='C',padx=166,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclear())
bC.place(x=0,y=479)
bX=tk.Button(root,text='X',padx=78,pady=40,fg='#FFFFFF',bg='#d21405',font=('sans-serif, 14'))
bX.place(x=360,y=479)
bdiv=tk.Button(root,text='÷',padx=78,pady=40,fg='#ffffff',font=('sans-serif, 14'),command=lambda:bclick("/"),bg='#1138be')
bdiv.place(x=540,y=479)
#1 row done
b7=tk.Button(root,text='7',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("7"))
b7.place(x=0,y=631)
b8=tk.Button(root,text='8',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("8"))
b8.place(x=180,y=631)
b9=tk.Button(root,text='9',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("9"))
b9.place(x=360,y=631)
bmul=tk.Button(root,text='×',padx=78,pady=40,bg='#1138be',fg='#ffffff',font=('sans-serif, 14'),command=lambda:bclick("*"))
bmul.place(x=540,y=631)
#2 row
b4=tk.Button(root,text='4',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("4"))
b4.place(x=0,y=783)
b5=tk.Button(root,text='5',padx=80,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("5"))
b5.place(x=180,y=783)
b6=tk.Button(root,text='6',padx=79,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("6"))
b6.place(x=360,y=783)
badd=tk.Button(root,text='+',padx=80,pady=40,bg='#1138be',fg='#ffffff',font=('sans-serif, 14'),command=lambda:bclick("+"))
badd.place(x=540,y=783)
#3row
b1=tk.Button(root,text='1',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("1"))
b1.place(x=0,y=935)
b2=tk.Button(root,text='2',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("2"))
b2.place(x=180,y=935)
b3=tk.Button(root,text='3',padx=78,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("3"))
b3.place(x=360,y=935)
bsub=tk.Button(root,text='-',padx=82,pady=40,bg='#1138be',fg='#ffffff',font=('sans-serif, 14'),command=lambda:bclick("-"))
bsub.place(x=540,y=935)
#4 row
b0=tk.Button(root,text='0',padx=165,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("0"))
b0.place(x=0,y=1087)
bdot=tk.Button(root,text='.',padx=85,pady=40,bg='#FFFFFF',font=('sans-serif, 14'),command=lambda:bclick("."))
bdot.place(x=360,y=1087)
bans=tk.Button(root,text='=',padx=80,pady=40,bg='#002366',fg='#ffffff',font=('sans-serif, 14'),command=lambda:bequal())
bans.place(x=540,y=1087)
root.mainloop()
The way I would do it is the same way you've done the last buttons instead of using the text='1' or a number just change it to text='backspace'.
As for the logic behind it since you have a global exp variable storing the maths equation created using the calculator you will need to remove the last bit of the equation added. i.e. if the equation was 12 + 15 + 17 - 20 you'd need to look through it and remove 20 because that was the last part of the equation. If they hit backspace again you'd need to remove the -.
So you're looking to create a function called bRemove() which removes the last part of your equation.
hint : to look at the last character in your string you can access it doing exp[len(exp)-1], you can check if this is a number and if it is you can remove it and look at the next element in the string (exp[len(exp)-2]) and then see if that is also a number.
[
also some general stack overflow advice to help you on your programming journey, it's better to be more specific about the help requested - some background information is nice and if you are going tto paste code you should use the ``` notation which lets you turn code into blocked code like this
block of code
]
Try this in my example.
from tkinter import *
#definging height and width of button.
button_height=1
button_width=3
#defining height and width of screen
screen_width =450
screen_height= 600
root=Tk()
root.title("SIMPLE CALCULATOR")
root.geometry(f"{screen_width}x{screen_height}")
root.maxsize(screen_width,screen_height)
root.minsize(screen_width,screen_height)
root.configure(background="gray")
scvalue=StringVar()
scvalue.set("")
#This defines the function for click event
def click_me(event):
value=event= event.widget.cget("text")
#print(value)
if value == "=":
try:
if scvalue.get().isdigit():
finalvalue= int(scvalue.get())
else:
finalvalue=eval(scvalue.get())
scvalue.set(finalvalue)
screen.update()
except:
scvalue.set(scvalue.get()[:-1])
screen.update()
elif value=="<=": #for backspace
scvalue.set(scvalue.get()[:-1])
screen.update()
elif value =="1/x": #for calculating reciprocal
if scvalue.get().isdigit():
val=int(scvalue.get())
scvalue.set(1/val)
screen.update()
else:
scvalue.set("Unknown error")
elif value== "C": #for clearing the screen.
scvalue.set("")
screen.update()
else:
scvalue.set(scvalue.get() +value)
screen.update()
screen= Entry(root,textvar=scvalue,font="lucida 40 bold" ,justify=RIGHT)
screen.pack(fill=X,padx=5,pady=5)
#list of all the inputs
valuelist=["/","%","C","<=","7","8","9","*","4","5","6","-","1","2","3","+","1/x","0",".","="]
#this loop
for i in range(20):
if i%4 == 0:
frame=Frame(root,bg="gray")
frame.pack()
b=Button(frame,text=valuelist[i],height=button_height,width=button_width,font="lucida 35 bold")
b.bind("<Button-1>",click_me)
b.pack(side=LEFT,padx=3,pady=3)
root.mainloop()

Why is the execution of my code (the program) happening faster, every time I hit the start button?

I just recently made a pomodoro clock implementation on python and I was facing some trouble with its execution but I came up with a solution for it but I observed a discrepancy in its execution.
So my whole code and implementation looks something like this (my code is not clean or pretty; sorry about that, I am one of those people who uses a mixture of tabs and spaces):
from tkinter import *
from time import *
from threading import Thread
# ---------------------------- CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5*60000
LONG_BREAK_MIN = 20*60000
class Reset:
def __init__(self):
self.click = False
self.activation = False
def button_command(self):
self.click = True
def timer_command(self):
return self.click
# ---------------------------- TIMER RESET ------------------------------- #
timer_reset = Reset()
reset = timer_reset.click
# ---------------------------- TIMER MECHANISM ------------------------------- #
def timer_mechanism():
minute=0
if counter[0]<60000:
if counter[0] % 1000 == 0 and counter[0]/1000<10:
canvas.itemconfig(clock_counter, text=(f"00:0{int(counter[0]/1000)}"))
canvas.update_idletasks()
elif counter[0]% 1000==0 and counter[0]/1000>=10:
canvas.itemconfig(clock_counter, text=(f"00:{int(counter[0] / 1000)}"))
canvas.update_idletasks()
elif counter[0]>=60000:
if counter[0]%1000==0:
transition=int(counter[0]/1000)
while transition>=60:
minute+=1
transition-=60
second=transition
if second<10 and minute<10:
canvas.itemconfig(clock_counter,text=(f"0{minute}:0{second}"))
canvas.update_idletasks()
elif second>=10 and minute<10:
canvas.itemconfig(clock_counter,text=(f"0{minute}:{second}"))
canvas.update_idletasks()
elif minute>=10 and second<10:
canvas.itemconfig(clock_counter, text=(f"{minute}:0{second}"))
canvas.update_idletasks()
else:
canvas.itemconfig(clock_counter,text=(f"{minute}:{second}"))
canvas.update_idletasks()
# -----------------------------New countdown mechanism----------------------------#
i = [4]
def start_countdown():
if not timer_reset.click and i[0] > 0:
# keep listening to the function that receives from the button while doing an after for the 25 min and 10 min respectively.3
timer.config(text="Work", fg=GREEN)
window.update_idletasks()
# the solution to this problem is to break up the after process instead of doing it all at the same time make use of small increments so that this after could finish withing a second or two and then go to another function that contains all the timer_reset.click values update and come everytime until we reach a limit somewhere probably an array value that will be updated until we get to the 25 minute mark so this insures as the signal from the button will be accepted.
execute("Work")
# start=time()
# end=time()
# while end-start<5:
# end=time()
# timer_reset.click=timer_reset.timer_command()
else:
window.destroy()
timer_reset.click = False
i[0] = 4
beginning()
def rest():
global start_time
start_time=0
timer_reset.activation = True
if not timer_reset.click:
global restloop
restloop = True
global workloop
workloop = False
timer.config(text="Break", fg=PINK)
if i[0] == 4:
global frame
frame = Frame(window, width=20, height=20)
frame.grid(row=3, column=1)
tick = Label(frame, text="✔", font=(FONT_NAME, 12, "bold"), bg=YELLOW, fg=GREEN)
tick.pack(side=LEFT)
window.update_idletasks()
if i[0] > 0:
execute("Break")
if timer_reset.click:
timer_reset.click = False
window.destroy()
beginning()
else:
window.destroy()
beginning()
else:
window.destroy()
i[0] = 4
timer_reset.click = False
beginning()
i[0] -= 1
counter=[0]
def execute(identifier):
if identifier=="Work":
window.after(1,mirror,LONG_BREAK_MIN)
if identifier=="Break":
window.after(1,mirror,SHORT_BREAK_MIN)
def mirror(value):
if timer_reset.click:
window.destroy()
i[0]=4
timer_reset.click=False
counter[0]=0
beginning()
elif counter[0]<value:
counter[0]+=1
timer_mechanism()
if value==LONG_BREAK_MIN:
execute("Work")
if value==SHORT_BREAK_MIN:
execute("Break")
elif value==LONG_BREAK_MIN:
counter[0]=0
window.deiconify()
window.attributes("-topmost",1)
window.after(300,window.attributes,"-topmost",0)
window.update()
rest()
elif value==SHORT_BREAK_MIN:
counter[0]=0
window.deiconify()
window.attributes("-topmost",1)
window.after(300,window.attributes,"-topmost",0)
window.update()
start_countdown()
# ---------------------------- UI SETUP ------------------------------- #
def beginning():
global window
window = Tk(className="Pomodoro")
window.title("Pomodoro")
window.config(pady=50, padx=100, bg=YELLOW)
window.wm_state("normal")
global timer
timer = Label(text="Timer", font=(FONT_NAME, 50, "bold"), bg=YELLOW, foreground=GREEN)
timer.grid(row=0, column=1)
global canvas
canvas = Canvas(width=200, height=223, bg=YELLOW, highlightthickness=0)
tomato = PhotoImage(file="tomato.png")
canvas.create_image(100, 100, image=tomato)
global clock_counter
clock_counter=canvas.create_text(100, 120, text="00:00", fill="white", font=(FONT_NAME, 35, "bold"))
canvas.grid(row=1, column=1)
start = Button(text="Start", highlightthickness=0, borderwidth=0, command=start_countdown)
start.grid(row=2, column=0)
end = Button(text="Reset", highlightthickness=0, borderwidth=0, command=timer_reset.button_command)
end.grid(row=2, column=2)
window.mainloop()
beginning()
And the UI part of my code looks something like this:
So the discrepnancy I was talking about was that after starting the program and the countdown is happening if by mistake or whatever reason the user presses the Start button again the countdown starts to happen faster and if you keep pressing the start button without hitting the reset button it starts counting down even faster and faster.
Now I think I understand why this might be but this is like a sliver of what the solution might be, I might be completely wrong for all I know but is it because of the after method since every time the user hits the button he is starting another thread of the after method process and this kind of creates a sense/illusion of multiprocessing(parallelism)? I really don't know, to be honest. I might be stretching too far, but please any type of explanation would really be helpful even if it is a jab at my answer. I am very genuinely curious as to why this is happening.
Any help/suggestion will be really helpful.

tkinter: how to use after method in response to another function

The general idea of the code is that every one-and-a-half seconds, the text on the buttons changes randomly, so that each reads either ‘click’, ‘clack’ or ‘cluck’. If the player clicks a button labeled ‘click’, he or she scores 10 points. If the player clicks a button labeled ‘clack’ or ‘cluck’, he or she loses 10 points. When a button has been clicked, it changes color—to light green if the click scored points and to light yellow if it lost points. Clicking the same button again has no effect until the next time the button labels are changed, at which time the colors should also revert to gray.
The problem that I have is modifying the code so that each time the player scores 10 points the interval between label changes is reduced by 50 milliseconds and each time the player loses 10 points the interval is increased by 100 milliseconds.
Here is the original code, but I don't know how to modify the code for the intervals.
from tkinter import *
import random
score = 0
root = Tk()
scoreFrame = Frame(root)
scoreFrame.pack(expand=YES, fill=BOTH)
scoreLabel = Label(scoreFrame)
scoreLabel.pack(expand=YES)
def showScore():
scoreLabel['text'] = 'Score: {0}'.format(score)
clickFrame = Frame(root)
clickFrame.pack(side=BOTTOM, expand=YES, fill=BOTH)
def changeLabels():
for button in buttons:
button['text'] = random.choice(['click', 'clack', 'cluck'])
button['bg'] = buttonDefaultColor
root.after(1500, changeLabels)
def makeButton():
button = Button(clickFrame)
def cmd():
global score
if button['bg'] == buttonDefaultColor:
if button['text'] == 'click':
score += 10
button['bg'] = 'light green'
else:
score -= 10
button['bg'] = 'light yellow'
showScore()
button['command'] = cmd
button.pack(side=LEFT, expand=YES, fill=BOTH)
return button
buttons = [makeButton() for i in range(5)]
buttonDefaultColor = buttons[0]['bg']
changeLabels()
showScore()
You need to change the 1500 to either a global value or a class property. Something that can be updated.

Python tkinter Entry widget usage

I'm currently trying to use the entry widget in tkinter to get a number from the user, and then use that number to define a parameter of one of my other functions.
The code is very long, so I'll try summarize my thoughts after the block.
class NimGame():
def __init__(self, numberOfBalls):
self.numberOfBallsRemaining = numberOfBalls
print("Nim game initialized with {} balls.".format(self.numberOfBallsRemaining))
def remainingBalls(self):
return self.numberOfBallsRemaining
def take(self, numberOfBalls):
if (numberOfBalls < 1) or (numberOfBalls > 3) or (numberOfBalls > self.numberOfBallsRemaining):
print("You can't take that number of balls. Try again.")
# ## Update Label in the GUI to tell user they can't take that many balls.
# It might be better to "inactivate" the buttons that correspond to invalid number to take.
statusLabel.configure(text="You can't take that number of balls. Try again.")
else:
self.numberOfBallsRemaining = self.numberOfBallsRemaining - numberOfBalls
print("You took {} balls. {} remain.".format(numberOfBalls, self.numberOfBallsRemaining))
if self.numberOfBallsRemaining == 0:
print("Computer wins!")
else:
# ## After removing player-chosen balls, update graphics and then pause for 1.0 seconds
# before removing computer-chosen balls. This way the player can "see" the
# intermediate status. Perhaps think about a nicer way of showing this.
updateGraphics()
sleep(1.0)
computerMaxBalls = min(3, self.numberOfBallsRemaining)
compBallsTaken = random.randint(1,computerMaxBalls)
self.numberOfBallsRemaining = self.numberOfBallsRemaining - compBallsTaken
# ## After removing computer-chosen balls, update graphics again.
updateGraphics()
print("Computer took {} balls. {} remain.".format(compBallsTaken, self.numberOfBallsRemaining))
if self.numberOfBallsRemaining == 0:
print("You win!")
def updateGraphics():
canvas.delete('all')
centerX = leftmostBallXPosition
centerY = ballYPosition
for i in range(nimGame.remainingBalls()):
canvas.create_oval(centerX - halfBallSize,
centerY - halfBallSize,
centerX + halfBallSize,
centerY + halfBallSize,
fill="#9999ff")
centerX = centerX + spaceBetweenBalls + ballSize
canvas.update_idletasks()
def initializeNewGame():
numberOfBalls = e1.get()
initializeNimAndGUI(numberOfBalls)
def initializeNimAndGUI(numberOfBalls):
global nimGame
global ballSize, halfBallSize, spaceBetweenBalls, leftmostBallXPosition, ballYPosition
nimGame = NimGame(numberOfBalls)
canvas.delete('all')
ballSize = min(maxBallSize, int(((canvasWidth-canvasBorderBuffer)//numberOfBalls)/1.2))
halfBallSize = ballSize // 2
spaceBetweenBalls = int(0.2 * ballSize)
leftmostBallXPosition = (canvasBorderBuffer//2) + (spaceBetweenBalls//2) + halfBallSize
ballYPosition = canvasHeight // 2
updateGraphics()
def createGUI():
global rootWindow
global canvas
global statusLabel
global textEntry
global e1
rootWindow = Tk()
canvasAndButtons = Frame(rootWindow)
canvas = Canvas(canvasAndButtons, height=canvasHeight, width=canvasWidth, relief=SUNKEN, borderwidth=2)
canvas.pack(side=LEFT)
buttonframe = Frame(canvasAndButtons)
e1 = Entry(buttonframe)
e1.pack()
button1 = Button(buttonframe, text='Take 1', command=lambda:takeBalls(1))
button2 = Button(buttonframe, text='Take 2', command=lambda:takeBalls(2))
button3 = Button(buttonframe, text='Take 3', command=lambda:takeBalls(3))
button4 = Button(buttonframe, text='New Game', command=initializeNewGame)
button1.pack()
button2.pack()
button3.pack()
button4.pack()
buttonframe.pack(side=RIGHT)
canvasAndButtons.pack()
statusLabel = Label(rootWindow, text="Play Nim")
statusLabel.pack()
def runNim(numberOfBalls):
createGUI()
initializeNimAndGUI(numberOfBalls)
rootWindow.mainloop()
So to me it seems that the program is having issues updating the graphics when I do a second game. What should happen is that, for example, i call runNim(20) and play a game with 20 balls. After the game, I need to be able to enter a number in the entry widget, click new game, and have that be the new numberOfBalls. When I do that, I get the init message back stating "Nim game initialized with 10 balls." But the GUI doesnt change, no balls appear in the GUI, and if I try to take anything it gives traceback and errors.
I figured out my problem. When I was trying to convert the string from e1.get() into an integer, I wasn't accounting for the empty string when I first run the program. This gave me a ValueError: invalid literal for int() with base 10: ''. So I had to account for that, and now it works.

Python: Connect 4 with TKinter

Alrighty I'm trying to implement a GUI for a game of Connect Four by using TKinter. Now I have the grid and everything set up what I'm having trouble with is getting the chip to show up on the board.
Here is my output:
What I'm trying to do is make it so when I click one of the bottom column buttons a chip appears (and since this is connect four it should go from bottom to top)
Here is my code:
from Tkinter import *
from connectfour import *
from minimax import *
from player import *
import tkMessageBox
class ConnectFourGUI:
def DrawGrid(self):
for i in range(0,self.cols+1):
self.c.create_line((i+1)*self.mag,self.mag,\
(i+1)*self.mag,(self.rows+1)*self.mag)
for i in range(0,self.rows+1):
self.c.create_line(self.mag,(i+1)*self.mag,\
self.mag*(1+self.cols),(i+1)*self.mag)
def __init__(self,wdw):
wdw.title("Connect Four")
self.mag = 60
self.rows = 6
self.cols = 7
self.c = Canvas(wdw,\
width=self.mag*self.cols+2*self.mag,\
height = self.mag*self.rows+2*self.mag,\
bg='white')
self.c.grid(row=1,column=1,columnspan=2)
rlabel=Label(root, text="Player1:")
rlabel.grid(row=0,column=0)
self.player1_type=StringVar(root)
options= ["Human", "Random", "Minimax"]
self.player1_type.set(options[2])
self.rowbox=OptionMenu(root, self.player1_type, *options)
self.rowbox.grid(row=0, column=1)
rlabel2=Label(root, text="Player2:")
rlabel2.grid(row=0,column=2)
self.player2_type=StringVar(root)
self.player2_type.set(options[0])
self.rowbox=OptionMenu(root, self.player2_type, *options)
self.rowbox.grid(row=0, column=3)
begin=Button(root, text="Start", command=self.game_start)
begin.grid(row=0, column=4)
self.c.grid(row=1, column=0, columnspan=7)
play_col=[]
for i in range(self.cols):
play_col.append(Button(root, text= "Col %d" %i, command=lambda col= i: self.human_play(col)))
play_col[i].grid(row=10,column="%d"%i)
## self.DrawCircle(1,1,1)
## self.DrawCircle(2,2,1)
## self.DrawCircle(5,3,2)
self.DrawGrid()
self.brd = ConnectFour()
def game_start(self):
self.board=ConnectFour()
print self.player1_type.get()
print self.player2_type.get()
if self.player1_type.get()=="Random":
self.player1 = RandomPlayer(playernum=1)
if self.player2_type.get()== "Random" or self.player2_type.get() == "Minimax":
tkMessageBox.showinfo("Bad Choice", "You Have to choose At least 1 Human Player")
else:
self.player
elif self.player1_type.get()=="Minimax":
self.player1=MinimaxPlayer(playernum=2, ply_depth=4, utility=SimpleUtility(5,1))
if self.player2_type.get()== "Random" or self.player2_type.get() == "Minimax":
tkMessageBox.showinfo("Bad Choice", "You Have to choose At least 1 Human Player")
elif self.player1_type.get()=="Human":
self.player1=Human(playernum=1)
if self.player2_type.get()=="Human":
self.player2=Human(playernum=2)
elif self.player2_type.get()=="Random":
self.player2=RandomPlayer(playernum=2)
elif self.player2_type.get()=="Minimax":
self.player2=MinimaxPlayer(playernum=2, ply_depth=4, utility=SimpleUitlity(5,1))
#self.currentplayer==1
#self.draw()
def human_play(self, col):
if self.player1_type.get()=="Human" and self.player2_type.get() =="Human":
while True:
self.DrawCircle(row,col,1)
if self.brd.is_game_over() is None:
self.DrawCircle(row,col,2)
if self.brd.is_game_over() is None:
pass
else:
print "Player 2 wins!"
break
else:
print "Player 1 wins!"
break
def DrawCircle(self,row,col,player_num):
if player_num == 1:
fill_color = 'red'
elif player_num == 2:
fill_color = 'black'
#(startx, starty, endx, endy)
self.c.create_oval(col*self.mag,row*self.mag,(col+1)*self.mag,(row+1)*self.mag,fill=fill_color)
root=Tk()
ConnectFourGUI(root)
root.mainloop()
I know I'm supposed to call the DrawCircle function in the Human Play function, I'm just unsure as to how I'm supposed to set it all up. any advice as to how I could go about this would be greatly appreciated!
Your code is depending on a few packages I don't have, so I can't be more specific, but the way I'd go about doing something like this is to track the X and Y coords of the chip works out the the row and column that it'd go into in the widget.
You'll need to create a location object, a tuple maybe, and then a way to translate the location object into a drawable location. Then it's just a matter of incrementing either X or Y and detecting if there's a chip below it.

Categories

Resources