Forum Archive

Tic Tac Toe

techteej

Starting off a Tic Tac Toe game in Pythonista, but I can't quite figure out how to get the computer to randomly pick a button then draw the image. Any help?

# coding: utf-8

import ui
import random

global buttons
buttons = ['button1', 'button2', 'button3', 'button4', 'button5', 'button6', 'button7', 'button8','button9']

def computer_pick():
    global buttons
    computer = random.choice(buttons)
    name = 'name: %s' % computer
    computer = ui.Button(name)
    computer.image = ui.Image.named('ionicons-ios7-circle-outline-32')

def button_tapped(sender):
    global buttons
    sender.image = ui.Image.named('ionicons-close-32')
    buttons.remove(sender.name)
    print buttons
    computer_pick()

v = ui.load_view('tic-tac-toe')
v.present('sheet')

I just want help with this, I'd like to figure the rest out on my own :)

JonB

Do those buttons already exist in the view?
ui.Button(name) is creating a new instance. I think you want to send sender to computer_pick, and use
computer = sender.superview[name]

techteej

Tried this and doesn't work.

techteej

sender gets only what the user pressed

JonB

The point is, you need to get to the view containing the buttons. Sender presumably is a subview of your root view, so the superview is the view containing all buttons. But Not having your pyui, I'm guessing. So passing sender as an argument to computer_ pick should let you select the appropriate subview. You could also just pass sender.superview, or have that be a global, given that you are using globals anyway. ( you might later consider putting globals in a class so they are not actually global, but constrained to a class instance). The point is, the computer pick function needs to know where to find the actual button instances.

ccc

Unbeatable tictactoe was a bit more complicated than I thought it would be...

https://github.com/cclauss/Pythonista_ui/blob/master/TicTacToe.py

Please let me know if you can win against it.