python小游戏井字棋积分制带界面
时间: 2023-07-01 07:25:03 浏览: 204
好的,我可以为你提供一个简单的井字棋游戏,带有积分制和图形用户界面。请先确保你已经安装了Python和Pygame库。
以下是代码示例:
``` python
import pygame
# 初始化Pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
# 定义游戏界面大小
SIZE = (300, 300)
# 创建游戏界面
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Tic Tac Toe")
# 定义字体
font = pygame.font.Font(None, 36)
# 定义游戏变量
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
player = 1
score = {"Player 1": 0, "Player 2": 0}
# 定义绘制游戏界面的函数
def draw_board():
screen.fill(WHITE)
pygame.draw.line(screen, BLACK, (100, 0), (100, 300), 5)
pygame.draw.line(screen, BLACK, (200, 0), (200, 300), 5)
pygame.draw.line(screen, BLACK, (0, 100), (300, 100), 5)
pygame.draw.line(screen, BLACK, (0, 200), (300, 200), 5)
for row in range(3):
for col in range(3):
if board[row][col] == 1:
pygame.draw.circle(screen, BLUE, (col*100+50, row*100+50), 40, 5)
elif board[row][col] == 2:
pygame.draw.line(screen, BLUE, (col*100+20, row*100+80), (col*100+80, row*100+20), 5)
# 定义检查游戏是否结束的函数
def check_winner():
winner = 0
for row in range(3):
if board[row][0] == board[row][1] == board[row][2] != 0:
winner = board[row][0]
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != 0:
winner = board[0][col]
if board[0][0] == board[1][1] == board[2][2] != 0:
winner = board[0][0]
if board[0][2] == board[1][1] == board[2][0] != 0:
winner = board[0][2]
if winner == 1:
score["Player 1"] += 1
return "Player 1 wins!"
elif winner == 2:
score["Player 2"] += 1
return "Player 2 wins!"
elif sum([board[row][col] != 0 for row in range(3) for col in range(3)]) == 9:
return "Tie!"
else:
return None
# 定义显示分数的函数
def show_score():
text1 = font.render("Player 1: " + str(score["Player 1"]), True, BLACK)
text2 = font.render("Player 2: " + str(score["Player 2"]), True, BLACK)
screen.blit(text1, (10, 10))
screen.blit(text2, (10, 50))
# 定义主函数
def main():
global player, board
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if player == 1:
pos = pygame.mouse.get_pos()
row = pos[1] // 100
col = pos[0] // 100
if board[row][col] == 0:
board[row][col] = player
player = 2
elif player == 2:
pos = pygame.mouse.get_pos()
row = pos[1] // 100
col = pos[0] // 100
if board[row][col] == 0:
board[row][col] = player
player = 1
draw_board()
show_score()
winner = check_winner()
if winner:
text = font.render(winner, True, BLACK)
screen.blit(text, (90, 140))
pygame.display.update()
pygame.time.delay(2000)
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
player = 1
pygame.display.update()
pygame.quit()
# 调用主函数
if __name__ == "__main__":
main()
```
这个程序包含了井字棋游戏的主要逻辑,包括绘制游戏界面、检查游戏是否结束、显示分数、处理玩家输入等。你可以将这个程序保存为.py文件并运行,就可以开始游戏了。
阅读全文