首先pip 那个pygame;
然后看代码;
临时写的,图片就不插了(防止舍友砍我,现在是凌晨。。。。)
[TOC]
井字棋游戏
# 此代码基本能立于不败之地;
import random
#可视化输出
def draw_Board(board):
print('-----------')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('-----------')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print('-----------')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print('-----------')
#输入选择符号
def input_Player_Letter():
letters = ''
while not (letters == 'X' or letters == 'O'):
print('Do you want to be X or O?')
letters = input().upper()
if letters == 'X':return ['X','O']
else:return ['O','X']
#谁先?
def who_Goes_First():
if random.randint(0, 1) == 0:
return 'computer'
else: return 'player'
#是否再来一次?
def play_Again():
print('Do you want to play again?(yes or no?)')
return input().lower().startswith('y')
#下子
def make_Move(board, letter, move):
board[move] = letter
#判断是否有获胜者
def is_Winner(bo, le):
return ((bo[7] == bo[8] == bo[9] == le) or
(bo[4] == bo[5] == bo[6] == le) or
(bo[1] == bo[2] == bo[3] == le) or
(bo[7] == bo[4] == bo[1] == le) or
(bo[8] == bo[5] == bo[2] == le) or
(bo[9] == bo[6] == bo[3] == le) or
(bo[7] == bo[5] == bo[3] == le) or
(bo[1] == bo[5] == bo[9] == le))
#复制表盘测试
def get_Board_Copy(board):
dupe_Board = []
for i in board:
dupe_Board.append(i)
return dupe_Board
#判断位置是否为空
def is_Space_Free(board,move):
return board[move] == ' '
#选手下棋
def get_Player_Move(board):
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not is_Space_Free(board,int(move)):
print('What is your next move?')
move = input()
return int(move)
#随机下棋
def choose_Random_Move_From_List(board, movesList):
possibleMoves = []
for i in movesList:
if is_Space_Free(board, i):
possibleMoves.append(i)
if len(possibleMoves ) != 0 :
return random.choice(possibleMoves)#随机返回
else:
return None ##不在此中下棋
#简易AI
def get_Computer_Move(board, computerLetter):
if computerLetter == 'X':
playerLetter = 'O'
else :playerLetter = 'X'
#是否有胜利的一步
for i in range(1,10):
copy = get_Board_Copy(board)
if is_Space_Free(copy, i):
make_Move(copy, computerLetter, i)
if is_Winner(copy, computer_Letter):
return i
#阻止选手胜利
for i in range(1,10):
copy = get_Board_Copy(board)
if is_Space_Free(copy, i):
make_Move(copy, player_Letter, i)
if is_Winner(copy, player_Letter):
return i
#占中间的
if is_Space_Free(board, 5):
return 5
#选角落不易输
move = choose_Random_Move_From_List(board, [1,3,7,9])
if move != None:
return move
#别无后路
return choose_Random_Move_From_List(board, [2, 4, 6, 8])
#判断棋盘是否满
def is_Board_Full(board):
for i in range(1, 10):
if is_Space_Free(board, i):
return False
return True
####主函数:
print("Welcome to 井字棋:")
while 1:
the_Board = [" "]*10
player_Letter, computer_Letter = input_Player_Letter()
turn = who_Goes_First()
print('The {} will go first.'.format(turn))
game_Is_Playing = True
#游戏开始
while game_Is_Playing:
if turn == 'player':
draw_Board(the_Board)
move = get_Player_Move(the_Board)
make_Move(the_Board, player_Letter, move)
#判断是否胜利
if is_Winner(the_Board,player_Letter):
draw_Board(the_Board)
print("You have won the game!")
game_Is_Playing = False
else:
if is_Board_Full(the_Board):
draw_Board(the_Board)
print('The game is a tie!')
break
else:
turn = 'computer' #交换下棋方
else:
move = get_Computer_Move(the_Board, computer_Letter)
make_Move(the_Board, computer_Letter, move)
#判断胜利
if is_Winner(the_Board,computer_Letter):
draw_Board(the_Board)
print("You have lost the game!")
game_Is_Playing = False
else:
if is_Board_Full(the_Board):
draw_Board(the_Board)
print('The game is axx tie!')
break
else:
turn = 'player' #交换下棋方
if not play_Again():
break
hello world
#学会能画出图形
#这称不上是一个游戏
import pygame, sys
from pygame.locals import *
pygame.init()
window_Surface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Hello world!')
#RBG
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
#fonts
basic_Font = pygame.font.SysFont(None, 48)
text = basic_Font.render('Hello world~~', True, WHITE, BLUE)
text_Rect = text.get_rect()
text_Rect.centerx = window_Surface.get_rect().centerx
text_Rect.centery = window_Surface.get_rect().centery
window_Surface.fill(WHITE)
pygame.draw.polygon(window_Surface, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))
pygame.draw.line(window_Surface, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(window_Surface, BLUE, (120, 60), (60, 120))
pygame.draw.line(window_Surface, BLUE, (60, 120), (120, 120), 4)
pygame.draw.circle(window_Surface, BLUE, (300, 50), 20, 1)
pygame.draw.ellipse(window_Surface, RED, (300, 250, 40, 80), 1)
pygame.draw.rect(window_Surface, RED,
(text_Rect.left - 20,
text_Rect.top - 20,
text_Rect.width + 40,
text_Rect.height + 40))
pixArry = pygame.PixelArray(window_Surface)
pixArry[480][380] = BLACK
del pixArry
window_Surface.blit(text, text_Rect)
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
移动的方块
#和上式差不多,也是画出来的
import pygame, sys, time
import random
from pygame.locals import *
pygame.init()
window_Width = 400
window_Height = 400
window_Surface = pygame.display.set_mode((window_Width, window_Height), 0, 32)
pygame.display.set_caption('Animation')
down_Left = 1
down_Right = 3
up_Left = 7
up_Right = 9
move_Speed = 4
Black = (0, 0, 0)
RED = (255, 0, 0)
GREEN =(0, 255, 0)
BLUE = (0, 0, 255)
b1 = {'rect':pygame.Rect(300, 80, 50, 100),'color':RED, 'dir':up_Right} #红长方形
b2 = {'rect':pygame.Rect(120, 200, 20, 20),'color':GREEN, 'dir':up_Left}#绿
b3 = {'rect':pygame.Rect(100, 150, 60, 60),'color':BLUE, 'dir':down_Left}#蓝
blocks = [b1, b2, b3]
while 1:
window_Surface.fill(Black)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
for b in blocks:
#移动
if b['dir'] == down_Left:
b['rect'].left -= move_Speed
b['rect'].top += move_Speed
if b['dir'] == down_Right:
b['rect'].left += move_Speed
b['rect'].top += move_Speed
if b['dir'] == up_Left:
b['rect'].left -= move_Speed
b['rect'].top -= move_Speed
if b['dir'] == up_Right:
b['rect'].left += move_Speed
b['rect'].top -= move_Speed
#反弹
if b['rect'].top < 0:
if b['dir'] == up_Left:
b['dir'] = down_Left
if b['dir'] == up_Right:
b['dir'] = down_Right
if b['rect'].bottom > window_Height:
if b['dir'] == down_Left:
b['dir'] = up_Left
if b['dir'] == down_Right:
b['dir'] = up_Right
if b['rect'].left < 0:
if b['dir'] == down_Left:
b['dir'] = down_Right
if b['dir'] == up_Left:
b['dir'] = up_Right
if b['rect'].right > window_Width:
if b['dir'] == down_Right:
b['dir'] = down_Left
if b['dir'] == up_Right:
b['dir'] = up_Left
pygame.draw.rect(window_Surface, b['color'], b['rect'])
#重置
pygame.display.update()
time.sleep(random.uniform(0.01,0.03)) #控制时间随机速度
移动的方块二
#♪(^∀^●)ノ随便改了一下,和上面的差不多
import pygame, sys, random
from pygame.locals import *
#查看是否吃到食物
def do_Rects_Overlap(rect1,rect2):
for a, b in [(rect1, rect2), (rect2, rect1)]:
if((is_Point_Inside_Rect(a.left, a.top, b))or
(is_Point_Inside_Rect(a.left, a.bottom, b)) or
(is_Point_Inside_Rect(a.right, a.top, b)) or
(is_Point_Inside_Rect(a.right, a.bottom, b))):
return True
return False
def is_Point_Inside_Rect(x, y, rect):
if (x > rect.left) and (x < rect.right) and (y > rect.top ) and (y < rect .bottom):
return True
else:
return False
#初始化
pygame.init()
mainClock = pygame.time.Clock()
#游戏界面大小
window_Width = 800
window_Height = 600
window_Surface = pygame.display.set_mode((window_Width, window_Height),0,32)
#标题
pygame.display.set_caption("呼哧's game")
down_Left = 1
down_Right = 3
up_Left = 7
up_Right = 9
#速度
move_Speed = 4
#颜色
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
#食物计数
food_Counter = 0
new_Food = 4
#食物大小
food_Size = 2
bouncer = {'rect':pygame.Rect(300, 100, 50, 50), 'dir':down_Left}
foods = []
#初始化有6000个食物
for i in range(6000):
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size, food_Size))
while True:
for event in pygame.event.get():
#关闭按钮
if event.type == QUIT:
pygame.quit()
sys.exit()
#增加食物功能
food_Counter += 1
if food_Counter >= new_Food :
food_Counter = 0
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size, food_Size))
#填充
window_Surface.fill(BLACK)
#移动
if bouncer['dir'] == down_Left :
bouncer['rect'].left -= move_Speed
bouncer['rect'].top += move_Speed
if bouncer['dir'] == down_Right :
bouncer['rect'].left += move_Speed
bouncer['rect'].top += move_Speed
if bouncer['dir'] == up_Left :
bouncer['rect'].left -= move_Speed
bouncer['rect'].top -= move_Speed
if bouncer['dir'] == up_Right :
bouncer['rect'].left += move_Speed
bouncer['rect'].top -= move_Speed
#反弹
if bouncer['rect'].top < 0:
if bouncer['dir'] == up_Left:
bouncer['dir'] = down_Left
if bouncer['dir'] == up_Right:
bouncer['dir'] = down_Right
if bouncer['rect'].bottom > window_Height:
if bouncer['dir'] == down_Left:
bouncer['dir'] = up_Left
if bouncer['dir'] == down_Right:
bouncer['dir'] = up_Right
if bouncer['rect'].left < 0:
if bouncer['dir'] == up_Left:
bouncer['dir'] = up_Right
if bouncer['dir'] == down_Left:
bouncer['dir'] = down_Right
if bouncer['rect'].right > window_Width:
if bouncer['dir'] == down_Right:
bouncer['dir'] = down_Left
if bouncer['dir'] == up_Right:
bouncer['dir'] = up_Left
#移动的方块
pygame.draw.rect(window_Surface, WHITE, bouncer['rect'])
#擦去绿色方块
for food in foods[:]:
if do_Rects_Overlap(bouncer['rect'], food):
foods.remove(food)
#显示绿色方块
for i in range(len(foods)):
pygame.draw.rect(window_Surface, GREEN, foods[i])
#重置
pygame.display.update()
#类似time.sleep
mainClock.tick(40)
可操作的方块一
#有了这个是不是就感觉有了天下一样呢,哈哈哈。^_^
#游戏简要说明:上下左右wsad或者上下左右;
#单机增加食物,x随机移动;
#食物变化具体请看代码;
import pygame, sys, random, time
from pygame.locals import *
#初始化
pygame.init()
main_Clock = pygame.time.Clock()
#界面设计
window_Width = 800
window_Height = 500
window_Surface = pygame.display.set_mode((window_Width, window_Height), 0, 32)
pygame.display.set_caption("Huchi's moving rect")
#颜色
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
#食物
food_Counter = 0
new_Food = 40
food_Size = 20
player = pygame.Rect(300, 0, 50 ,50)
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size, food_Size))
#移动
move_Left = False
move_Right = False
move_Up = False
move_Down = False
#速度
move_Speed = 10
while True:
for event in pygame.event.get():
#关闭按钮
if event.type == QUIT:
pygame.quit()
sys.exit()
#按键
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
move_Right = False
move_Left = True
if event.key == K_RIGHT or event.key == ord('d'):
move_Left = False
move_Right = True
if event.key == K_UP or event.key == ord('w'):
move_Down = False
move_Up = True
if event.key == K_DOWN or event.key == ord('s'):
move_Up = False
move_Down = True
#松开
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
move_Left = False
if event.key == K_RIGHT or event.key == ord('d'):
move_Right = False
if event.key == K_UP or event.key == ord('w'):
move_Up = False
if event.key == K_DOWN or event.key == ord('s'):
move_Down = False
if event.key == ord('x'):
player.top = random.randint(0, window_Height - player.height)
player.left = random.randint(0, window_Width - player.width)
#鼠标增加
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size,food_Size))
#食物增加
food_Counter += 1
if food_Counter >= new_Food:
food_Counter = 0
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size, food_Size))
# 填充
window_Surface.fill(BLACK)
#阻止越界
if move_Down and player.bottom < window_Height:
player.top += move_Speed
if move_Up and player.top > 0:
player.top -= move_Speed
if move_Left and player.left > 0:
player.left -= move_Speed
if move_Right and player.right <window_Width:
player.left += move_Speed
#画玩者的rect
pygame.draw.rect(window_Surface, WHITE, player)
#吃掉食物
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
#画食物
for i in range(len(foods)):
pygame.draw.rect(window_Surface, GREEN, foods[i])
#动态化
pygame.display.update()
main_Clock.tick(40)
#胜利
if len(foods) == 0:
basic_Font = pygame.font.SysFont(None, 48)
text = basic_Font.render('You won!', True, BLACK, BLUE)
text_Rect = text.get_rect()
window_Surface.blit(text, text_Rect)
pygame.display.update()
time.sleep(1)
入门期的第一个成果
#加入了图片,在上述的游戏中加入了图片与背景音乐(可以开关);
#我的图片与bgm是放在同目录的文件下的;
import pygame, sys, random, time
from pygame.locals import *
pygame.init()
main_Clock = pygame.time.Clock()
window_Width = 800
window_Height = 644
window_Surface = pygame.display.set_mode((window_Width, window_Height),0 ,32)
#颜色
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
#食物设置
food_Counter = 0
new_Food = 20
food_Size = 100
#玩家图片
player = pygame.Rect(300, 100, 40, 40)
player_Image = pygame.image.load('images\\player.jpg')#图片1
player_Stretched_Image = pygame.transform.scale(player_Image, (20, 20))
food_Image = pygame.image.load('images\\food.jpg')
foods_Image = pygame.transform.scale(food_Image, (20, 20))
foods = []
#初始20个食物
for i in range(20):
foods.append(pygame.Rect(random.randint(0, window_Width - 20),
random.randint(0, window_Height - 20),
food_Size, food_Size ))
#移动
move_Left = False
move_Right = False
move_Up = False
move_Down = False
#速度
move_Speed = 10
#背景音乐
pickup_Sound = pygame.mixer.Sound('videos\\eat.wav')
pygame.mixer.music.load('videos\\bgm.mp3') #音乐
pygame.mixer.music.play(-1, 0.0)
music_Playing = True
while True:
for event in pygame.event.get():
#关闭按钮
if event.type == QUIT:
pygame.quit()
sys.exit()
#按键
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
move_Right = False
move_Left = True
if event.key == K_RIGHT or event.key == ord('d'):
move_Left = False
move_Right = True
if event.key == K_UP or event.key == ord('w'):
move_Down = False
move_Up = True
if event.key == K_DOWN or event.key == ord('s'):
move_Up = False
move_Down = True
#松开
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
move_Left = False
if event.key == K_RIGHT or event.key == ord('d'):
move_Right = False
if event.key == K_UP or event.key == ord('w'):
move_Up = False
if event.key == K_DOWN or event.key == ord('s'):
move_Down = False
if event.key == ord('x'):
player.top = random.randint(0, window_Height - player.height)
player.left = random.randint(0, window_Width - player.width)
if event.key == ord('m'):
if music_Playing:
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1, 0.0)
music_Playing = not music_Playing
#鼠标增加
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size,food_Size))
#食物增加
food_Counter += 1
if food_Counter >= new_Food:
food_Counter = 0
foods.append(pygame.Rect(random.randint(0, window_Width - food_Size),
random.randint(0, window_Height - food_Size),
food_Size, food_Size))
# 填充
window_Surface.fill(BLACK)
# 阻止越界
if move_Down and player.bottom < window_Height:
player.top += move_Speed
if move_Up and player.top > 0:
player.top -= move_Speed
if move_Left and player.left > 0:
player.left -= move_Speed
if move_Right and player.right < window_Width:
player.left += move_Speed
window_Surface.blit(player_Stretched_Image, player)
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
player = pygame.Rect(player.left, player.top, player.width + 2, player.height + 2)
player_Stretched_Image = pygame.transform.scale(player_Image, (player.width, player.height))
if music_Playing:
pickup_Sound.play()
if len(foods) >= 40:
foods = []
if len(foods) == 0:
for i in range(20):
foods.append(pygame.Rect(random.randint(0, window_Width - 20),
random.randint(0, window_Height - 20),
food_Size, food_Size))
#胜利条件
if player.height > window_Height:
player.width = player.height = 1
basic_Font = pygame.font.SysFont(None, 48)
text = basic_Font.render('You won!', True, BLACK, BLUE)
text_Rect = text.get_rect()
window_Surface.blit(text, text_Rect)
window_Surface.blit(player_Stretched_Image, player)
pygame.display.update()
time.sleep(3)
window_Surface.blit(player_Stretched_Image, player)
pygame.display.update()
for food in foods:
window_Surface.blit(food_Image, food)
pygame.display.update()
main_Clock.tick(40)
别拦我,我要去看源码,哈哈哈,interesting。:)