程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Gaga knowledge of 7 small games, played all can not put it down (with source code, can be run directly)

編輯:Python

Preface

Today is Sunday , It's a happy day . Office workers don't have to go to work , Students don't have to study . I don't want to share too much knowledge to embarrass everyone , Just give us seven games

Well , From Monday to Sunday , Learn to remember to come to me PK…

1、 Xiaoxiaole

How to play : Three connected can eliminate

The source code to share :

python Exchange of learning Q Group :906715085###
import os
import sys
import cfg
import pygame
from modules import *
''' The main program of the game '''
def main():
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Gemgem —— Nine songs ')
# Load background music 
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))
pygame.mixer.music.set_volume(0.6)
pygame.mixer.music.play(-1)
# Loading sound effects 
sounds = {
}
sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))
sounds['match'] = []
for i in range(6):
sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))
# Load Fonts 
font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)
# Image loading 
gem_imgs = []
for i in range(1, 8):
gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))
# Main circulation 
game = gemGame(screen, sounds, font, gem_imgs, cfg)
while True:
score = game.start()
flag = False
# After a round of the game, players choose to play again or exit 
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == pygame.KEYUP and event.key == pygame.K_r:
flag = True
if flag:
break
screen.fill((135, 206, 235))
text0 = 'Final score: %s' % score
text1 = 'Press <R> to restart the game.'
text2 = 'Press <Esc> to quit the game.'
y = 150
for idx, text in enumerate([text0, text1, text2]):
text_render = font.render(text, 1, (85, 65, 0))
rect = text_render.get_rect()
if idx == 0:
rect.left, rect.top = (212, y)
elif idx == 1:
rect.left, rect.top = (122.5, y)
else:
rect.left, rect.top = (126.5, y)
y += 100
screen.blit(text_render, rect)
pygame.display.update()
game.reset()
'''run'''
if __name__ == '__main__':
main()

2、 tetris

How to play : Childhood classics , Normal mode doesn't mean much , When we were young, we all played acceleration .

The source code to share :


import os
import sys
import random
from modules import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
''' Define Tetris game class '''
class TetrisGame(QMainWindow):
def __init__(self, parent=None):
super(TetrisGame, self).__init__(parent)
# Whether to suspend ing
self.is_paused = False
# Do you want to start ing
self.is_started = False
self.initUI()
''' Interface initialization '''
def initUI(self):
# icon
self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg')))
# Block size 
self.grid_size = 22
# Game frame rate 
self.fps = 200
self.timer = QBasicTimer()
# The focus of 
self.setFocusPolicy(Qt.StrongFocus)
# Horizontal layout 
layout_horizontal = QHBoxLayout()
self.inner_board = InnerBoard()
self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)
layout_horizontal.addWidget(self.external_board)
self.side_panel = SidePanel(self, self.grid_size, self.inner_board)
layout_horizontal.addWidget(self.side_panel)
self.status_bar = self.statusBar()
self.external_board.score_signal[str].connect(self.status_bar.showMessage)
self.start()
self.center()
self.setWindowTitle('Tetris —— Nine songs ')
self.show()
self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())
''' The game interface moves to the middle of the screen '''
def center(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
''' Update the interface '''
def updateWindow(self):
self.external_board.updateData()
self.side_panel.updateData()
self.update()
''' Start '''
def start(self):
if self.is_started:
return
self.is_started = True
self.inner_board.createNewTetris()
self.timer.start(self.fps, self)
''' Pause / Don't pause '''
def pause(self):
if not self.is_started:
return
self.is_paused = not self.is_paused
if self.is_paused:
self.timer.stop()
self.external_board.score_signal.emit('Paused')
else:
self.timer.start(self.fps, self)
self.updateWindow()
''' Timer events '''
def timerEvent(self, event):
if event.timerId() == self.timer.timerId():
removed_lines = self.inner_board.moveDown()
self.external_board.score += removed_lines
self.updateWindow()
else:
super(TetrisGame, self).timerEvent(event)
''' Key events '''
def keyPressEvent(self, event):
if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:
super(TetrisGame, self).keyPressEvent(event)
return
key = event.key()
# P Key pause 
if key == Qt.Key_P:
self.pause()
return
if self.is_paused:
return
# towards the left 
elif key == Qt.Key_Left:
self.inner_board.moveLeft()
# towards the right 
elif key == Qt.Key_Right:
self.inner_board.moveRight()
# rotate 
elif key == Qt.Key_Up:
self.inner_board.rotateAnticlockwise()
# Fall fast 
elif key == Qt.Key_Space:
self.external_board.score += self.inner_board.dropDown()
else:
super(TetrisGame, self).keyPressEvent(event)
self.updateWindow()
'''run'''
if __name__ == '__main__':
app = QApplication([])
tetris = TetrisGame()
sys.exit(app.exec_())

3、 snake

How to play : Childhood classics , Ordinary magic is not interesting , When I was a child, I played accelerated .

The source code to share :

 python Exchange of learning Q Group :906715085###
import cfg
import sys
import pygame
from modules import *
''' The main function '''
def main(cfg):
# Game initialization 
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Greedy Snake —— Nine songs ')
clock = pygame.time.Clock()
# Play background music 
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1)
# The main cycle of the game 
snake = Snake(cfg)
apple = Apple(cfg, snake.coords)
score = 0
while True:
screen.fill(cfg.BLACK)
# -- Key detection 
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
snake.setDirection({
pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])
# -- Update greedy snakes and food 
if snake.update(apple):
apple = Apple(cfg, snake.coords)
score += 1
# -- Determine if the game is over 
if snake.isgameover: break
# -- Show the necessary elements in the game 
drawGameGrid(cfg, screen)
snake.draw(screen)
apple.draw(screen)
showScore(cfg, score, screen)
# -- Screen update 
pygame.display.update()
clock.tick(cfg.FPS)
return endInterface(screen, cfg)
'''run'''
if __name__ == '__main__':
while True:
if not main(cfg):
break

4、24 A little game

How to play : Through addition, subtraction, multiplication and division , Primary school students have no problem .

The source code to share :


import os
import sys
import pygame
from cfg import *
from modules import *
from fractions import Fraction
''' Check whether the control has been clicked '''
def checkClicked(group, mouse_pos, group_type='NUMBER'):
selected = []
# Digital cards / Operator cards 
if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]:
max_selected = 2 if group_type == GROUPTYPES[0] else 1
num_selected = 0
for each in group:
num_selected += int(each.is_selected)
for each in group:
if each.rect.collidepoint(mouse_pos):
if each.is_selected:
each.is_selected = not each.is_selected
num_selected -= 1
each.select_order = None
else:
if num_selected < max_selected:
each.is_selected = not each.is_selected
num_selected += 1
each.select_order = str(num_selected)
if each.is_selected:
selected.append(each.attribute)
# Button card 
elif group_type == GROUPTYPES[2]:
for each in group:
if each.rect.collidepoint(mouse_pos):
each.is_selected = True
selected.append(each.attribute)
# Throw an exception 
else:
raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES))
return selected
''' Get the digital Genie group '''
def getNumberSpritesGroup(numbers):
number_sprites_group = pygame.sprite.Group()
for idx, number in enumerate(numbers):
args = (*NUMBERCARD_POSITIONS[idx], str(number), NUMBERFONT, NUMBERFONT_COLORS, NUMBERCARD_COLORS, str(number))
number_sprites_group.add(Card(*args))
return number_sprites_group
''' Get operator sprite group '''
def getOperatorSpritesGroup(operators):
operator_sprites_group = pygame.sprite.Group()
for idx, operator in enumerate(operators):
args = (*OPERATORCARD_POSITIONS[idx], str(operator), OPERATORFONT, OPREATORFONT_COLORS, OPERATORCARD_COLORS, str(operator))
operator_sprites_group.add(Card(*args))
return operator_sprites_group
''' Get button sprite group '''
def getButtonSpritesGroup(buttons):
button_sprites_group = pygame.sprite.Group()
for idx, button in enumerate(buttons):
args = (*BUTTONCARD_POSITIONS[idx], str(button), BUTTONFONT, BUTTONFONT_COLORS, BUTTONCARD_COLORS, str(button))
button_sprites_group.add(Button(*args))
return button_sprites_group
''' Calculation '''
def calculate(number1, number2, operator):
operator_map = {
'+': '+', '-': '-', '×': '*', '÷': '/'}
try:
result = str(eval(number1+operator_map[operator]+number2))
return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))
except:
return None
''' Display information on the screen '''
def showInfo(text, screen):
rect = pygame.Rect(200, 180, 400, 200)
pygame.draw.rect(screen, PAPAYAWHIP, rect)
font = pygame.font.Font(FONTPATH, 40)
text_render = font.render(text, True, BLACK)
font_size = font.size(text)
screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2))
''' The main function '''
def main():
# initialization , Import the necessary game material 
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(SCREENSIZE)
pygame.display.set_caption('24 point —— Nine songs ')
win_sound = pygame.mixer.Sound(AUDIOWINPATH)
lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
warn_sound = pygame.mixer.Sound(AUDIOWARNPATH)
pygame.mixer.music.load(BGMPATH)
pygame.mixer.music.play(-1, 0.0)
# 24 Click game builder 
game24_gen = game24Generator()
game24_gen.generate()
# Spirit group 
# -- Numbers 
number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
# -- Operator 
operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
# -- Button 
button_sprites_group = getButtonSpritesGroup(BUTTONS)
# The main cycle of the game 
clock = pygame.time.Clock()
selected_numbers = []
selected_operators = []
selected_buttons = []
is_win = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(-1)
elif event.type == pygame.MOUSEBUTTONUP:
mouse_pos = pygame.mouse.get_pos()
selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER')
selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR')
selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON')
screen.fill(AZURE)
# Update numbers 
if len(selected_numbers) == 2 and len(selected_operators) == 1:
noselected_numbers = []
for each in number_sprites_group:
if each.is_selected:
if each.select_order == '1':
selected_number1 = each.attribute
elif each.select_order == '2':
selected_number2 = each.attribute
else:
raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order)
else:
noselected_numbers.append(each.attribute)
each.is_selected = False
for each in operator_sprites_group:
each.is_selected = False
result = calculate(selected_number1, selected_number2, *selected_operators)
if result is not None:
game24_gen.numbers_now = noselected_numbers + [result]
is_win = game24_gen.check()
if is_win:
win_sound.play()
if not is_win and len(game24_gen.numbers_now) == 1:
lose_sound.play()
else:
warn_sound.play()
selected_numbers = []
selected_operators = []
number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
# All the elves draw screen On 
for each in number_sprites_group:
each.draw(screen, pygame.mouse.get_pos())
for each in operator_sprites_group:
each.draw(screen, pygame.mouse.get_pos())
for each in button_sprites_group:
if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']:
is_win = False
if selected_buttons and each.attribute == selected_buttons[0]:
each.is_selected = False
number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group)
selected_buttons = []
each.draw(screen, pygame.mouse.get_pos())
# Game wins 
if is_win:
showInfo('Congratulations', screen)
# The game failed 
if not is_win and len(game24_gen.numbers_now) == 1:
showInfo('Game Over', screen)
pygame.display.flip()
clock.tick(30)
'''run'''
if __name__ == '__main__':
main()

5、 balance beam

How to play : It's also a classic game when I was a child , Just control the left and right , It's a little difficult to get to the back .

The source code to share :

import cfg
from modules import breakoutClone
''' The main function '''
def main():
game = breakoutClone(cfg)
game.run()
'''run'''
if __name__ == '__main__':
main()

6、 Alien invasion

How to play : This reminds me of the first level of soul duel boss, It's kind of similar , But the difficulty of soul duel must be higher .

The source code to share :

python Exchange of learning Q Group :906715085###
import os
import sys
import cfg
import random
import pygame
from modules import *
''' Start the game '''
def startGame(screen):
clock = pygame.time.Clock()
# Load Fonts 
font = pygame.font.SysFont('arial', 18)
if not os.path.isfile('score'):
f = open('score', 'w')
f.write('0')
f.close()
with open('score', 'r') as f:
highest_score = int(f.read().strip())
# The enemy 
enemies_group = pygame.sprite.Group()
for i in range(55):
if i < 11:
enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)
elif i < 33:
enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)
else:
enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)
enemy.rect.x = 85 + (i % 11) * 50
enemy.rect.y = 120 + (i // 11) * 45
enemies_group.add(enemy)
boomed_enemies_group = pygame.sprite.Group()
en_bullets_group = pygame.sprite.Group()
ufo = ufoSprite(color=cfg.RED)
# We 
myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)
my_bullets_group = pygame.sprite.Group()
# Used to control enemy location updates 
# -- Move a line 
enemy_move_count = 24
enemy_move_interval = 24
enemy_move_flag = False
# -- Change the direction of movement ( Change direction at the same time, collective descent once )
enemy_change_direction_count = 0
enemy_change_direction_interval = 60
enemy_need_down = False
enemy_move_right = True
enemy_need_move_row = 6
enemy_max_row = 5
# Used to control enemy firing 
enemy_shot_interval = 100
enemy_shot_count = 0
enemy_shot_flag = False
# The game is in progress 
running = True
is_win = False
# Main circulation 
while running:
screen.fill(cfg.BLACK)
for event in pygame.event.get():
# -- Point at the top right X Or press Esc Key to exit the game 
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
# -- Shooting 
if event.type == pygame.MOUSEBUTTONDOWN:
my_bullet = myaircraft.shot()
if my_bullet:
my_bullets_group.add(my_bullet)
# -- Our bullets and the enemy /UFO collision detection 
for enemy in enemies_group:
if pygame.sprite.spritecollide(enemy, my_bullets_group, True, None):
boomed_enemies_group.add(enemy)
enemies_group.remove(enemy)
myaircraft.score += enemy.reward
if pygame.sprite.spritecollide(ufo, my_bullets_group, True, None):
ufo.is_dead = True
myaircraft.score += ufo.reward
# -- Update and draw enemy 
# ---- Enemy bullets 
enemy_shot_count += 1
if enemy_shot_count > enemy_shot_interval:
enemy_shot_flag = True
enemies_survive_list = [enemy.number for enemy in enemies_group]
shot_number = random.choice(enemies_survive_list)
enemy_shot_count = 0
# ---- The enemy moves 
enemy_move_count += 1
if enemy_move_count > enemy_move_interval:
enemy_move_count = 0
enemy_move_flag = True
enemy_need_move_row -= 1
if enemy_need_move_row == 0:
enemy_need_move_row = enemy_max_row
enemy_change_direction_count += 1
if enemy_change_direction_count > enemy_change_direction_interval:
enemy_change_direction_count = 1
enemy_move_right = not enemy_move_right
enemy_need_down = True
# ---- Each descent increases movement and firing speed 
enemy_move_interval = max(15, enemy_move_interval-3)
enemy_shot_interval = max(50, enemy_move_interval-10)
# ---- Traverse updates 
for enemy in enemies_group:
if enemy_shot_flag:
if enemy.number == shot_number:
en_bullet = enemy.shot()
en_bullets_group.add(en_bullet)
if enemy_move_flag:
if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):
if enemy_move_right:
enemy.update('right', cfg.SCREENSIZE[1])
else:
enemy.update('left', cfg.SCREENSIZE[1])
else:
enemy.update(None, cfg.SCREENSIZE[1])
if enemy_need_down:
if enemy.update('down', cfg.SCREENSIZE[1]):
running = False
is_win = False
enemy.change_count -= 1
enemy.draw(screen)
enemy_move_flag = False
enemy_need_down = False
enemy_shot_flag = False
# ---- Enemy explosion effects 
for boomed_enemy in boomed_enemies_group:
if boomed_enemy.boom(screen):
boomed_enemies_group.remove(boomed_enemy)
del boomed_enemy
# -- Collision detection between enemy bullets and our spacecraft 
if not myaircraft.one_dead:
if pygame.sprite.spritecollide(myaircraft, en_bullets_group, True, None):
myaircraft.one_dead = True
if myaircraft.one_dead:
if myaircraft.boom(screen):
myaircraft.resetBoom()
myaircraft.num_life -= 1
if myaircraft.num_life < 1:
running = False
is_win = False
else:
# ---- Update the ship 
myaircraft.update(cfg.SCREENSIZE[0])
# ---- Painting spaceships 
myaircraft.draw(screen)
if (not ufo.has_boomed) and (ufo.is_dead):
if ufo.boom(screen):
ufo.has_boomed = True
else:
# ---- to update UFO
ufo.update(cfg.SCREENSIZE[0])
# ---- draw UFO
ufo.draw(screen)
# -- Draw our spaceship bullets 
for bullet in my_bullets_group:
if bullet.update():
my_bullets_group.remove(bullet)
del bullet
else:
bullet.draw(screen)
# -- Draw enemy bullets 
for bullet in en_bullets_group:
if bullet.update(cfg.SCREENSIZE[1]):
en_bullets_group.remove(bullet)
del bullet
else:
bullet.draw(screen)
if myaircraft.score > highest_score:
highest_score = myaircraft.score
# -- Every time the score increases 2000 Our spaceship adds one life 
if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old_score):
myaircraft.old_score = myaircraft.score
myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)
# -- If all the enemies are dead, they will win 
if len(enemies_group) < 1:
is_win = True
running = False
# -- According to the text 
# ---- The current score 
showText(screen, 'SCORE: ', cfg.WHITE, font, 200, 8)
showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)
# ---- The number of enemies 
showText(screen, 'ENEMY: ', cfg.WHITE, font, 370, 8)
showText(screen, str(len(enemies_group)), cfg.WHITE, font, 370, 24)
# ---- The highest score in history 
showText(screen, 'HIGHEST: ', cfg.WHITE, font, 540, 8)
showText(screen, str(highest_score), cfg.WHITE, font, 540, 24)
# ----FPS
showText(screen, 'FPS: ' + str(int(clock.get_fps())), cfg.RED, font, 8, 8)
# -- Show remaining health 
showLife(screen, myaircraft.num_life, cfg.GREEN)
pygame.display.update()
clock.tick(cfg.FPS)
with open('score', 'w') as f:
f.write(str(highest_score))
return is_win
''' The main function '''
def main():
# initialization 
pygame.init()
pygame.display.set_caption(' Alien invasion —— Nine songs ')
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
while True:
is_win = startGame(screen)
endInterface(screen, cfg.BLACK, is_win)
'''run'''
if __name__ == '__main__':
main()

7、 Jingzi chess 888

How to play : I bet you've played this in class , Think about playing with my deskmate and wasting several books .

The source code to share

from tkinter import *
import tkinter.messagebox as msg
root = Tk()
root.title('TIC-TAC-TOE---Project Gurukul')
# labels
Label(root, text="player1 : X", font="times 15").grid(row=0, column=1)
Label(root, text="player2 : O", font="times 15").grid(row=0, column=2)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# for player1 sign = X and for player2 sign= Y
mark = ''
# counting the no. of click
count = 0
panels = ["panel"] * 10
def win(panels, sign):
return ((panels[1] == panels[2] == panels[3] == sign)
or (panels[1] == panels[4] == panels[7] == sign)
or (panels[1] == panels[5] == panels[9] == sign)
or (panels[2] == panels[5] == panels[8] == sign)
or (panels[3] == panels[6] == panels[9] == sign)
or (panels[3] == panels[5] == panels[7] == sign)
or (panels[4] == panels[5] == panels[6] == sign)
or (panels[7] == panels[8] == panels[9] == sign))
def checker(digit):
global count, mark, digits
# Check which button clicked
if digit == 1 and digit in digits:
digits.remove(digit)
##player1 will play if the value of count is even and for odd player2 will play
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button1.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 2 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button2.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 3 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button3.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 4 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button4.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 5 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button5.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 6 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button6.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 7 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button7.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 8 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button8.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
if digit == 9 and digit in digits:
digits.remove(digit)
if count % 2 == 0:
mark = 'X'
panels[digit] = mark
elif count % 2 != 0:
mark = 'O'
panels[digit] = mark
button9.config(text=mark)
count = count + 1
sign = mark
if (win(panels, sign) and sign == 'X'):
msg.showinfo("Result", "Player1 wins")
root.destroy()
elif (win(panels, sign) and sign == 'O'):
msg.showinfo("Result", "Player2 wins")
root.destroy()
###if count is greater then 8 then the match has been tied
if (count > 8 and win(panels, 'X') == False and win(panels, 'O') == False):
msg.showinfo("Result", "Match Tied")
root.destroy()
####define buttons
button1 = Button(root, width=15, font=('Times 16 bold'), height=7, command=lambda: checker(1))
button1.grid(row=1, column=1)
button2 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(2))
button2.grid(row=1, column=2)
button3 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(3))
button3.grid(row=1, column=3)
button4 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(4))
button4.grid(row=2, column=1)
button5 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(5))
button5.grid(row=2, column=2)
button6 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(6))
button6.grid(row=2, column=3)
button7 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(7))
button7.grid(row=3, column=1)
button8 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(8))
button8.grid(row=3, column=2)
button9 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(9))
button9.grid(row=3, column=3)
root.mainloop()

Last

All rivers and mountains are always in love , Order one OK? . Have a nice weekend !!! Today's small game I personally test very interesting !

If you like this article, remember to like it , If you miss this village, you won't have this store , See you in the next chapter …


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved